{"repo_name": "csharp-sdk", "file_name": "/csharp-sdk/src/ModelContextProtocol.Core/Client/McpHttpClient.cs", "inference_info": {"prefix_code": "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\n#if NET\nusing System.Net.Http.Json;\n#else\nusing System.Text;\nusing System.Text.Json;\n#endif\n\nnamespace ModelContextProtocol.Client;\n\n", "suffix_code": "\n", "middle_code": "internal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n Debug.Assert(request.Content is null, \"The request body should only be supplied as a JsonRpcMessage\");\n Debug.Assert(message is null || request.Method == HttpMethod.Post, \"All messages should be sent in POST requests.\");\n using var content = CreatePostBodyContent(message);\n request.Content = content;\n return await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);\n }\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null)\n {\n return null;\n }\n#if NET\n return JsonContent.Create(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n#else\n return new StringContent(\n JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage),\n Encoding.UTF8,\n \"application/json\"\n );\n#endif\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/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/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/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/Server/StreamableHttpPostTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Net.ServerSentEvents;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Handles processing the request/response body pairs for the Streamable HTTP transport.\n/// This is typically used via .\n/// \ninternal sealed class StreamableHttpPostTransport(StreamableHttpServerTransport parentTransport, IDuplexPipe httpBodies) : ITransport\n{\n private readonly SseWriter _sseWriter = new();\n private RequestId _pendingRequest;\n\n public ChannelReader MessageReader => throw new NotSupportedException(\"JsonRpcMessage.RelatedTransport should only be used for sending messages.\");\n\n string? ITransport.SessionId => parentTransport.SessionId;\n\n /// \n /// True, if data was written to the respond body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async ValueTask RunAsync(CancellationToken cancellationToken)\n {\n var message = await JsonSerializer.DeserializeAsync(httpBodies.Input.AsStream(),\n McpJsonUtilities.JsonContext.Default.JsonRpcMessage, cancellationToken).ConfigureAwait(false);\n await OnMessageReceivedAsync(message, cancellationToken).ConfigureAwait(false);\n\n if (_pendingRequest.Id is null)\n {\n return false;\n }\n\n _sseWriter.MessageFilter = StopOnFinalResponseFilter;\n await _sseWriter.WriteAllAsync(httpBodies.Output.AsStream(), cancellationToken).ConfigureAwait(false);\n return true;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (parentTransport.Stateless && message is JsonRpcRequest)\n {\n throw new InvalidOperationException(\"Server to client requests are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n private async IAsyncEnumerable> StopOnFinalResponseFilter(IAsyncEnumerable> messages, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n await foreach (var message in messages.WithCancellation(cancellationToken))\n {\n yield return message;\n\n if (message.Data is JsonRpcResponse or JsonRpcError && ((JsonRpcMessageWithId)message.Data).Id == _pendingRequest)\n {\n // Complete the SSE response stream now that all pending requests have been processed.\n break;\n }\n }\n }\n\n private async ValueTask OnMessageReceivedAsync(JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (message is null)\n {\n throw new InvalidOperationException(\"Received invalid null message.\");\n }\n\n if (message is JsonRpcRequest request)\n {\n _pendingRequest = request.Id;\n\n // Invoke the initialize request callback if applicable.\n if (parentTransport.OnInitRequestReceived is { } onInitRequest && request.Method == RequestMethods.Initialize)\n {\n var initializeRequest = JsonSerializer.Deserialize(request.Params, McpJsonUtilities.JsonContext.Default.InitializeRequestParams);\n await onInitRequest(initializeRequest).ConfigureAwait(false);\n }\n }\n\n message.RelatedTransport = this;\n\n if (parentTransport.FlowExecutionContextFromRequests)\n {\n message.ExecutionContext = ExecutionContext.Capture();\n }\n\n await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthenticatingMcpHttpClient.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Net.Http.Headers;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// A delegating handler that adds authentication tokens to requests and handles 401 responses.\n/// \ninternal sealed class AuthenticatingMcpHttpClient(HttpClient httpClient, ClientOAuthProvider credentialProvider) : McpHttpClient(httpClient)\n{\n // Select first supported scheme as the default\n private string _currentScheme = credentialProvider.SupportedSchemes.FirstOrDefault() ??\n throw new ArgumentException(\"Authorization provider must support at least one authentication scheme.\", nameof(credentialProvider));\n\n /// \n /// Sends an HTTP request with authentication handling.\n /// \n internal override async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (request.Headers.Authorization == null)\n {\n await AddAuthorizationHeaderAsync(request, _currentScheme, cancellationToken).ConfigureAwait(false);\n }\n\n var response = await base.SendAsync(request, message, cancellationToken).ConfigureAwait(false);\n\n if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)\n {\n return await HandleUnauthorizedResponseAsync(request, message, response, cancellationToken).ConfigureAwait(false);\n }\n\n return response;\n }\n\n /// \n /// Handles a 401 Unauthorized response by attempting to authenticate and retry the request.\n /// \n private async Task HandleUnauthorizedResponseAsync(\n HttpRequestMessage originalRequest,\n JsonRpcMessage? originalJsonRpcMessage,\n HttpResponseMessage response,\n CancellationToken cancellationToken)\n {\n // Gather the schemes the server wants us to use from WWW-Authenticate headers\n var serverSchemes = ExtractServerSupportedSchemes(response);\n\n if (!serverSchemes.Contains(_currentScheme))\n {\n // Find the first server scheme that's in our supported set\n var bestSchemeMatch = serverSchemes.Intersect(credentialProvider.SupportedSchemes, StringComparer.OrdinalIgnoreCase).FirstOrDefault();\n\n if (bestSchemeMatch is not null)\n {\n _currentScheme = bestSchemeMatch;\n }\n else if (serverSchemes.Count > 0)\n {\n // If no match was found, either throw an exception or use default\n throw new McpException(\n $\"The server does not support any of the provided authentication schemes.\" +\n $\"Server supports: [{string.Join(\", \", serverSchemes)}], \" +\n $\"Provider supports: [{string.Join(\", \", credentialProvider.SupportedSchemes)}].\");\n }\n }\n\n // Try to handle the 401 response with the selected scheme\n await credentialProvider.HandleUnauthorizedResponseAsync(_currentScheme, response, cancellationToken).ConfigureAwait(false);\n\n using var retryRequest = new HttpRequestMessage(originalRequest.Method, originalRequest.RequestUri);\n\n // Copy headers except Authorization which we'll set separately\n foreach (var header in originalRequest.Headers)\n {\n if (!header.Key.Equals(\"Authorization\", StringComparison.OrdinalIgnoreCase))\n {\n retryRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);\n }\n }\n\n await AddAuthorizationHeaderAsync(retryRequest, _currentScheme, cancellationToken).ConfigureAwait(false);\n return await base.SendAsync(retryRequest, originalJsonRpcMessage, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Extracts the authentication schemes that the server supports from the WWW-Authenticate headers.\n /// \n private static HashSet ExtractServerSupportedSchemes(HttpResponseMessage response)\n {\n var serverSchemes = new HashSet(StringComparer.OrdinalIgnoreCase);\n\n foreach (var header in response.Headers.WwwAuthenticate)\n {\n serverSchemes.Add(header.Scheme);\n }\n\n return serverSchemes;\n }\n\n /// \n /// Adds an authorization header to the request.\n /// \n private async Task AddAuthorizationHeaderAsync(HttpRequestMessage request, string scheme, CancellationToken cancellationToken)\n {\n if (request.RequestUri is null)\n {\n return;\n }\n\n var token = await credentialProvider.GetCredentialAsync(scheme, request.RequestUri, cancellationToken).ConfigureAwait(false);\n if (string.IsNullOrEmpty(token))\n {\n return;\n }\n\n request.Headers.Authorization = new AuthenticationHeaderValue(scheme, token);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseWriter.cs", "using ModelContextProtocol.Protocol;\nusing System.Buffers;\nusing System.Net.ServerSentEvents;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class SseWriter(string? messageEndpoint = null, BoundedChannelOptions? channelOptions = null) : IAsyncDisposable\n{\n private readonly Channel> _messages = Channel.CreateBounded>(channelOptions ?? new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private Utf8JsonWriter? _jsonWriter;\n private Task? _writeTask;\n private CancellationToken? _writeCancellationToken;\n\n private readonly SemaphoreSlim _disposeLock = new(1, 1);\n private bool _disposed;\n\n public Func>, CancellationToken, IAsyncEnumerable>>? MessageFilter { get; set; }\n\n public Task WriteAllAsync(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n // When messageEndpoint is set, the very first SSE event isn't really an IJsonRpcMessage, but there's no API to write a single\n // item of a different type, so we fib and special-case the \"endpoint\" event type in the formatter.\n if (messageEndpoint is not null && !_messages.Writer.TryWrite(new SseItem(null, \"endpoint\")))\n {\n throw new InvalidOperationException(\"You must call RunAsync before calling SendMessageAsync.\");\n }\n\n _writeCancellationToken = cancellationToken;\n\n var messages = _messages.Reader.ReadAllAsync(cancellationToken);\n if (MessageFilter is not null)\n {\n messages = MessageFilter(messages, cancellationToken);\n }\n\n _writeTask = SseFormatter.WriteAsync(messages, sseResponseStream, WriteJsonRpcMessageToBuffer, cancellationToken);\n return _writeTask;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(message);\n\n using var _ = await _disposeLock.LockAsync(cancellationToken).ConfigureAwait(false);\n\n if (_disposed)\n {\n // Don't throw an ODE, because this is disposed internally when the transport disconnects due to an abort\n // or sending all the responses for the a give given Streamable HTTP POST request, so the user might not be at fault.\n // There's precedence for no-oping here similar to writing to the response body of an aborted request in ASP.NET Core.\n return;\n }\n\n // Emit redundant \"event: message\" lines for better compatibility with other SDKs.\n await _messages.Writer.WriteAsync(new SseItem(message, SseParser.EventTypeDefault), cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);\n\n if (_disposed)\n {\n return;\n }\n\n _messages.Writer.Complete();\n try\n {\n if (_writeTask is not null)\n {\n await _writeTask.ConfigureAwait(false);\n }\n }\n catch (OperationCanceledException) when (_writeCancellationToken?.IsCancellationRequested == true)\n {\n // Ignore exceptions caused by intentional cancellation during shutdown.\n }\n finally\n {\n _jsonWriter?.Dispose();\n _disposed = true;\n }\n }\n\n private void WriteJsonRpcMessageToBuffer(SseItem item, IBufferWriter writer)\n {\n if (item.EventType == \"endpoint\" && messageEndpoint is not null)\n {\n writer.Write(Encoding.UTF8.GetBytes(messageEndpoint));\n return;\n }\n\n JsonSerializer.Serialize(GetUtf8JsonWriter(writer), item.Data, McpJsonUtilities.JsonContext.Default.JsonRpcMessage!);\n }\n\n private Utf8JsonWriter GetUtf8JsonWriter(IBufferWriter writer)\n {\n if (_jsonWriter is null)\n {\n _jsonWriter = new Utf8JsonWriter(writer);\n }\n else\n {\n _jsonWriter.Reset(writer);\n }\n\n return _jsonWriter;\n }\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/Server/McpServerExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides extension methods for interacting with an instance.\n/// \npublic static class McpServerExtensions\n{\n /// \n /// Requests to sample an LLM via the client using the specified request parameters.\n /// \n /// The server instance initiating the request.\n /// The parameters for the sampling request.\n /// The to monitor for cancellation requests.\n /// A task containing the sampling result from the client.\n /// is .\n /// The client does not support sampling.\n /// \n /// This method requires the client to support sampling capabilities.\n /// It allows detailed control over sampling parameters including messages, system prompt, temperature, \n /// and token limits.\n /// \n public static ValueTask SampleAsync(\n this IMcpServer server, CreateMessageRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.SamplingCreateMessage,\n request,\n McpJsonUtilities.JsonContext.Default.CreateMessageRequestParams,\n McpJsonUtilities.JsonContext.Default.CreateMessageResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests to sample an LLM via the client using the provided chat messages and options.\n /// \n /// The server initiating the request.\n /// The messages to send as part of the request.\n /// The options to use for the request, including model parameters and constraints.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the chat response from the model.\n /// is .\n /// is .\n /// The client does not support sampling.\n /// \n /// This method converts the provided chat messages into a format suitable for the sampling API,\n /// handling different content types such as text, images, and audio.\n /// \n public static async Task SampleAsync(\n this IMcpServer server,\n IEnumerable messages, ChatOptions? options = default, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n Throw.IfNull(messages);\n\n StringBuilder? systemPrompt = null;\n\n if (options?.Instructions is { } instructions)\n {\n (systemPrompt ??= new()).Append(instructions);\n }\n\n List samplingMessages = [];\n foreach (var message in messages)\n {\n if (message.Role == ChatRole.System)\n {\n if (systemPrompt is null)\n {\n systemPrompt = new();\n }\n else\n {\n systemPrompt.AppendLine();\n }\n\n systemPrompt.Append(message.Text);\n continue;\n }\n\n if (message.Role == ChatRole.User || message.Role == ChatRole.Assistant)\n {\n Role role = message.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n foreach (var content in message.Contents)\n {\n switch (content)\n {\n case TextContent textContent:\n samplingMessages.Add(new()\n {\n Role = role,\n Content = new TextContentBlock { Text = textContent.Text },\n });\n break;\n\n case DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") || dataContent.HasTopLevelMediaType(\"audio\"):\n samplingMessages.Add(new()\n {\n Role = role,\n Content = dataContent.HasTopLevelMediaType(\"image\") ?\n new ImageContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n } :\n new AudioContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n },\n });\n break;\n }\n }\n }\n }\n\n ModelPreferences? modelPreferences = null;\n if (options?.ModelId is { } modelId)\n {\n modelPreferences = new() { Hints = [new() { Name = modelId }] };\n }\n\n var result = await server.SampleAsync(new()\n {\n Messages = samplingMessages,\n MaxTokens = options?.MaxOutputTokens,\n StopSequences = options?.StopSequences?.ToArray(),\n SystemPrompt = systemPrompt?.ToString(),\n Temperature = options?.Temperature,\n ModelPreferences = modelPreferences,\n }, cancellationToken).ConfigureAwait(false);\n\n AIContent? responseContent = result.Content.ToAIContent();\n\n return new(new ChatMessage(result.Role is Role.User ? ChatRole.User : ChatRole.Assistant, responseContent is not null ? [responseContent] : []))\n {\n ModelId = result.Model,\n FinishReason = result.StopReason switch\n {\n \"maxTokens\" => ChatFinishReason.Length,\n \"endTurn\" or \"stopSequence\" or _ => ChatFinishReason.Stop,\n }\n };\n }\n\n /// \n /// Creates an wrapper that can be used to send sampling requests to the client.\n /// \n /// The server to be wrapped as an .\n /// The that can be used to issue sampling requests to the client.\n /// is .\n /// The client does not support sampling.\n public static IChatClient AsSamplingChatClient(this IMcpServer server)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return new SamplingChatClient(server);\n }\n\n /// Gets an on which logged messages will be sent as notifications to the client.\n /// The server to wrap as an .\n /// An that can be used to log to the client..\n public static ILoggerProvider AsClientLoggerProvider(this IMcpServer server)\n {\n Throw.IfNull(server);\n\n return new ClientLoggerProvider(server);\n }\n\n /// \n /// Requests the client to list the roots it exposes.\n /// \n /// The server initiating the request.\n /// The parameters for the list roots request.\n /// The to monitor for cancellation requests.\n /// A task containing the list of roots exposed by the client.\n /// is .\n /// The client does not support roots.\n /// \n /// This method requires the client to support the roots capability.\n /// Root resources allow clients to expose a hierarchical structure of resources that can be\n /// navigated and accessed by the server. These resources might include file systems, databases,\n /// or other structured data sources that the client makes available through the protocol.\n /// \n public static ValueTask RequestRootsAsync(\n this IMcpServer server, ListRootsRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfRootsUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.RootsList,\n request,\n McpJsonUtilities.JsonContext.Default.ListRootsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListRootsResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests additional information from the user via the client, allowing the server to elicit structured data.\n /// \n /// The server initiating the request.\n /// The parameters for the elicitation request.\n /// The to monitor for cancellation requests.\n /// A task containing the elicitation result.\n /// is .\n /// The client does not support elicitation.\n /// \n /// This method requires the client to support the elicitation capability.\n /// \n public static ValueTask ElicitAsync(\n this IMcpServer server, ElicitRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfElicitationUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.ElicitationCreate,\n request,\n McpJsonUtilities.JsonContext.Default.ElicitRequestParams,\n McpJsonUtilities.JsonContext.Default.ElicitResult,\n cancellationToken: cancellationToken);\n }\n\n private static void ThrowIfSamplingUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Sampling is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Sampling is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support sampling.\");\n }\n }\n\n private static void ThrowIfRootsUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Roots is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Roots are not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support roots.\");\n }\n }\n\n private static void ThrowIfElicitationUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Elicitation is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Elicitation is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support elicitation requests.\");\n }\n }\n\n /// Provides an implementation that's implemented via client sampling.\n private sealed class SamplingChatClient(IMcpServer server) : IChatClient\n {\n /// \n public Task GetResponseAsync(IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) =>\n server.SampleAsync(messages, options, cancellationToken);\n\n /// \n async IAsyncEnumerable IChatClient.GetStreamingResponseAsync(\n IEnumerable messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n var response = await GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);\n foreach (var update in response.ToChatResponseUpdates())\n {\n yield return update;\n }\n }\n\n /// \n object? IChatClient.GetService(Type serviceType, object? serviceKey)\n {\n Throw.IfNull(serviceType);\n\n return\n serviceKey is not null ? null :\n serviceType.IsInstanceOfType(this) ? this :\n serviceType.IsInstanceOfType(server) ? server :\n null;\n }\n\n /// \n void IDisposable.Dispose() { } // nop\n }\n\n /// \n /// Provides an implementation for creating loggers\n /// that send logging message notifications to the client for logged messages.\n /// \n private sealed class ClientLoggerProvider(IMcpServer server) : ILoggerProvider\n {\n /// \n public ILogger CreateLogger(string categoryName)\n {\n Throw.IfNull(categoryName);\n\n return new ClientLogger(server, categoryName);\n }\n\n /// \n void IDisposable.Dispose() { }\n\n private sealed class ClientLogger(IMcpServer server, string categoryName) : ILogger\n {\n /// \n public IDisposable? BeginScope(TState state) where TState : notnull =>\n null;\n\n /// \n public bool IsEnabled(LogLevel logLevel) =>\n server?.LoggingLevel is { } loggingLevel &&\n McpServer.ToLoggingLevel(logLevel) >= loggingLevel;\n\n /// \n public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)\n {\n if (!IsEnabled(logLevel))\n {\n return;\n }\n\n Throw.IfNull(formatter);\n\n Log(logLevel, formatter(state, exception));\n\n void Log(LogLevel logLevel, string message)\n {\n _ = server.SendNotificationAsync(NotificationMethods.LoggingMessageNotification, new LoggingMessageNotificationParams\n {\n Level = McpServer.ToLoggingLevel(logLevel),\n Data = JsonSerializer.SerializeToElement(message, McpJsonUtilities.JsonContext.Default.String),\n Logger = categoryName,\n });\n }\n }\n }\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.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
posts.\n internal static UserIdClaim? GetUserIdClaim(ClaimsPrincipal user)\n {\n if (user?.Identity?.IsAuthenticated != true)\n {\n return null;\n }\n\n var claim = user.FindFirst(ClaimTypes.NameIdentifier) ?? user.FindFirst(\"sub\") ?? user.FindFirst(ClaimTypes.Upn);\n\n if (claim is { } idClaim)\n {\n return new(idClaim.Type, idClaim.Value, idClaim.Issuer);\n }\n\n return null;\n }\n\n private static JsonTypeInfo GetRequiredJsonTypeInfo() => (JsonTypeInfo)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));\n\n private static bool MatchesApplicationJsonMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"application/json\");\n\n private static bool MatchesTextEventStreamMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"text/event-stream\");\n\n private sealed class HttpDuplexPipe(HttpContext context) : IDuplexPipe\n {\n public PipeReader Input => context.Request.BodyReader;\n public PipeWriter Output => context.Response.BodyWriter;\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/Server/AIFunctionMcpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed partial class AIFunctionMcpServerTool : McpServerTool\n{\n private readonly ILogger _logger;\n private readonly bool _structuredOutputRequiresWrapping;\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n \n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n object? target,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerToolCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options)\n {\n Throw.IfNull(function);\n\n Tool tool = new()\n {\n Name = options?.Name ?? function.Name,\n Description = options?.Description ?? function.Description,\n InputSchema = function.JsonSchema,\n OutputSchema = CreateOutputSchema(function, options, out bool structuredOutputRequiresWrapping),\n };\n\n if (options is not null)\n {\n if (options.Title is not null ||\n options.Idempotent is not null ||\n options.Destructive is not null ||\n options.OpenWorld is not null ||\n options.ReadOnly is not null)\n {\n tool.Title = options.Title;\n\n tool.Annotations = new()\n {\n Title = options.Title,\n IdempotentHint = options.Idempotent,\n DestructiveHint = options.Destructive,\n OpenWorldHint = options.OpenWorld,\n ReadOnlyHint = options.ReadOnly,\n };\n }\n }\n\n return new AIFunctionMcpServerTool(function, tool, options?.Services, structuredOutputRequiresWrapping);\n }\n\n private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpServerToolCreateOptions? options)\n {\n McpServerToolCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } toolAttr)\n {\n newOptions.Name ??= toolAttr.Name;\n newOptions.Title ??= toolAttr.Title;\n\n if (toolAttr._destructive is bool destructive)\n {\n newOptions.Destructive ??= destructive;\n }\n\n if (toolAttr._idempotent is bool idempotent)\n {\n newOptions.Idempotent ??= idempotent;\n }\n\n if (toolAttr._openWorld is bool openWorld)\n {\n newOptions.OpenWorld ??= openWorld;\n }\n\n if (toolAttr._readOnly is bool readOnly)\n {\n newOptions.ReadOnly ??= readOnly;\n }\n\n newOptions.UseStructuredContent = toolAttr.UseStructuredContent;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this tool.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerTool(AIFunction function, Tool tool, IServiceProvider? serviceProvider, bool structuredOutputRequiresWrapping)\n {\n AIFunction = function;\n ProtocolTool = tool;\n _logger = serviceProvider?.GetService()?.CreateLogger() ?? (ILogger)NullLogger.Instance;\n _structuredOutputRequiresWrapping = structuredOutputRequiresWrapping;\n }\n\n /// \n public override Tool ProtocolTool { get; }\n\n /// \n public override async ValueTask InvokeAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result;\n try\n {\n result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e) when (e is not OperationCanceledException)\n {\n ToolCallError(request.Params?.Name ?? string.Empty, e);\n\n string errorMessage = e is McpException ?\n $\"An error occurred invoking '{request.Params?.Name}': {e.Message}\" :\n $\"An error occurred invoking '{request.Params?.Name}'.\";\n\n return new()\n {\n IsError = true,\n Content = [new TextContentBlock { Text = errorMessage }],\n };\n }\n\n JsonNode? structuredContent = CreateStructuredResponse(result);\n return result switch\n {\n AIContent aiContent => new()\n {\n Content = [aiContent.ToContent()],\n StructuredContent = structuredContent,\n IsError = aiContent is ErrorContent\n },\n\n null => new()\n {\n Content = [],\n StructuredContent = structuredContent,\n },\n \n string text => new()\n {\n Content = [new TextContentBlock { Text = text }],\n StructuredContent = structuredContent,\n },\n \n ContentBlock content => new()\n {\n Content = [content],\n StructuredContent = structuredContent,\n },\n \n IEnumerable texts => new()\n {\n Content = [.. texts.Select(x => new TextContentBlock { Text = x ?? string.Empty })],\n StructuredContent = structuredContent,\n },\n \n IEnumerable contentItems => ConvertAIContentEnumerableToCallToolResult(contentItems, structuredContent),\n \n IEnumerable contents => new()\n {\n Content = [.. contents],\n StructuredContent = structuredContent,\n },\n \n CallToolResult callToolResponse => callToolResponse,\n\n _ => new()\n {\n Content = [new TextContentBlock { Text = JsonSerializer.Serialize(result, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))) }],\n StructuredContent = structuredContent,\n },\n };\n }\n\n /// Creates a name to use based on the supplied method and naming policy.\n internal static string DeriveName(MethodInfo method, JsonNamingPolicy? policy = null)\n {\n string name = method.Name;\n\n // Remove any \"Async\" suffix if the method is an async method and if the method name isn't just \"Async\".\n const string AsyncSuffix = \"Async\";\n if (IsAsyncMethod(method) &&\n name.EndsWith(AsyncSuffix, StringComparison.Ordinal) &&\n name.Length > AsyncSuffix.Length)\n {\n name = name.Substring(0, name.Length - AsyncSuffix.Length);\n }\n\n // Replace anything other than ASCII letters or digits with underscores, trim off any leading or trailing underscores.\n name = NonAsciiLetterDigitsRegex().Replace(name, \"_\").Trim('_');\n\n // If after all our transformations the name is empty, just use the original method name.\n if (name.Length == 0)\n {\n name = method.Name;\n }\n\n // Case the name based on the provided naming policy.\n return (policy ?? JsonNamingPolicy.SnakeCaseLower).ConvertName(name) ?? name;\n\n static bool IsAsyncMethod(MethodInfo method)\n {\n Type t = method.ReturnType;\n\n if (t == typeof(Task) || t == typeof(ValueTask))\n {\n return true;\n }\n\n if (t.IsGenericType)\n {\n t = t.GetGenericTypeDefinition();\n if (t == typeof(Task<>) || t == typeof(ValueTask<>) || t == typeof(IAsyncEnumerable<>))\n {\n return true;\n }\n }\n\n return false;\n }\n }\n\n /// Regex that flags runs of characters other than ASCII digits or letters.\n#if NET\n [GeneratedRegex(\"[^0-9A-Za-z]+\")]\n private static partial Regex NonAsciiLetterDigitsRegex();\n#else\n private static Regex NonAsciiLetterDigitsRegex() => _nonAsciiLetterDigits;\n private static readonly Regex _nonAsciiLetterDigits = new(\"[^0-9A-Za-z]+\", RegexOptions.Compiled);\n#endif\n\n private static JsonElement? CreateOutputSchema(AIFunction function, McpServerToolCreateOptions? toolCreateOptions, out bool structuredOutputRequiresWrapping)\n {\n structuredOutputRequiresWrapping = false;\n\n if (toolCreateOptions?.UseStructuredContent is not true)\n {\n return null;\n }\n\n if (function.ReturnJsonSchema is not JsonElement outputSchema)\n {\n return null;\n }\n\n if (outputSchema.ValueKind is not JsonValueKind.Object ||\n !outputSchema.TryGetProperty(\"type\", out JsonElement typeProperty) ||\n typeProperty.ValueKind is not JsonValueKind.String ||\n typeProperty.GetString() is not \"object\")\n {\n // If the output schema is not an object, need to modify to be a valid MCP output schema.\n JsonNode? schemaNode = JsonSerializer.SerializeToNode(outputSchema, McpJsonUtilities.JsonContext.Default.JsonElement);\n\n if (schemaNode is JsonObject objSchema &&\n objSchema.TryGetPropertyValue(\"type\", out JsonNode? typeNode) &&\n typeNode is JsonArray { Count: 2 } typeArray && typeArray.Any(type => (string?)type is \"object\") && typeArray.Any(type => (string?)type is \"null\"))\n {\n // For schemas that are of type [\"object\", \"null\"], replace with just \"object\" to be conformant.\n objSchema[\"type\"] = \"object\";\n }\n else\n {\n // For anything else, wrap the schema in an envelope with a \"result\" property.\n schemaNode = new JsonObject\n {\n [\"type\"] = \"object\",\n [\"properties\"] = new JsonObject\n {\n [\"result\"] = schemaNode\n },\n [\"required\"] = new JsonArray { (JsonNode)\"result\" }\n };\n\n structuredOutputRequiresWrapping = true;\n }\n\n outputSchema = JsonSerializer.Deserialize(schemaNode, McpJsonUtilities.JsonContext.Default.JsonElement);\n }\n\n return outputSchema;\n }\n\n private JsonNode? CreateStructuredResponse(object? aiFunctionResult)\n {\n if (ProtocolTool.OutputSchema is null)\n {\n // Only provide structured responses if the tool has an output schema defined.\n return null;\n }\n\n JsonNode? nodeResult = aiFunctionResult switch\n {\n JsonNode node => node,\n JsonElement jsonElement => JsonSerializer.SerializeToNode(jsonElement, McpJsonUtilities.JsonContext.Default.JsonElement),\n _ => JsonSerializer.SerializeToNode(aiFunctionResult, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))),\n };\n\n if (_structuredOutputRequiresWrapping)\n {\n return new JsonObject\n {\n [\"result\"] = nodeResult\n };\n }\n\n return nodeResult;\n }\n\n private static CallToolResult ConvertAIContentEnumerableToCallToolResult(IEnumerable contentItems, JsonNode? structuredContent)\n {\n List contentList = [];\n bool allErrorContent = true;\n bool hasAny = false;\n\n foreach (var item in contentItems)\n {\n contentList.Add(item.ToContent());\n hasAny = true;\n\n if (allErrorContent && item is not ErrorContent)\n {\n allErrorContent = false;\n }\n }\n\n return new()\n {\n Content = contentList,\n StructuredContent = structuredContent,\n IsError = allErrorContent && hasAny\n };\n }\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"\\\"{ToolName}\\\" threw an unhandled exception.\")]\n private partial void ToolCallError(string toolName, Exception exception);\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/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.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/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/McpClientExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class contains extension methods that simplify common operations with an MCP client,\n/// such as pinging a server, listing and working with tools, prompts, and resources, and\n/// managing subscriptions to resources.\n/// \n/// \npublic static class McpClientExtensions\n{\n /// \n /// Sends a ping request to verify server connectivity.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A task that completes when the ping is successful.\n /// \n /// \n /// This method is used to check if the MCP server is online and responding to requests.\n /// It can be useful for health checking, ensuring the connection is established, or verifying \n /// that the client has proper authorization to communicate with the server.\n /// \n /// \n /// The ping operation is lightweight and does not require any parameters. A successful completion\n /// of the task indicates that the server is operational and accessible.\n /// \n /// \n /// is .\n /// Thrown when the server cannot be reached or returns an error response.\n public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.Ping,\n parameters: null,\n McpJsonUtilities.JsonContext.Default.Object!,\n McpJsonUtilities.JsonContext.Default.Object,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Retrieves a list of available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available tools as instances.\n /// \n /// \n /// This method fetches all available tools from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of tools and that responds with paginated responses, consider using \n /// instead, as it streams tools as they arrive rather than loading them all at once.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// \n /// \n /// // Get all tools available on the server\n /// var tools = await mcpClient.ListToolsAsync();\n /// \n /// // Use tools with an AI client\n /// ChatOptions chatOptions = new()\n /// {\n /// Tools = [.. tools]\n /// };\n /// \n /// await foreach (var update in chatClient.GetStreamingResponseAsync(userMessage, chatOptions))\n /// {\n /// Console.Write(update);\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n List? tools = null;\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n tools ??= new List(toolResults.Tools.Count);\n foreach (var tool in toolResults.Tools)\n {\n tools.Add(new McpClientTool(client, tool, serializerOptions));\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n\n return tools;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available tools as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve tools from the server, which allows processing tools\n /// as they arrive rather than waiting for all tools to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with tools split across multiple responses.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available tools.\n /// \n /// \n /// \n /// \n /// // Enumerate all tools available on the server\n /// await foreach (var tool in client.EnumerateToolsAsync())\n /// {\n /// Console.WriteLine($\"Tool: {tool.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var tool in toolResults.Tools)\n {\n yield return new McpClientTool(client, tool, serializerOptions);\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available prompts as instances.\n /// \n /// \n /// This method fetches all available prompts from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of prompts and that responds with paginated responses, consider using \n /// instead, as it streams prompts as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListPromptsAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? prompts = null;\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n prompts ??= new List(promptResults.Prompts.Count);\n foreach (var prompt in promptResults.Prompts)\n {\n prompts.Add(new McpClientPrompt(client, prompt));\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n\n return prompts;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available prompts as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve prompts from the server, which allows processing prompts\n /// as they arrive rather than waiting for all prompts to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with prompts split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available prompts.\n /// \n /// \n /// \n /// \n /// // Enumerate all prompts available on the server\n /// await foreach (var prompt in client.EnumeratePromptsAsync())\n /// {\n /// Console.WriteLine($\"Prompt: {prompt.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumeratePromptsAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var prompt in promptResults.Prompts)\n {\n yield return new(client, prompt);\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a specific prompt from the MCP server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the prompt to retrieve.\n /// Optional arguments for the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to create the specified prompt with the provided arguments.\n /// The server will process the arguments and return a prompt containing messages or other content.\n /// \n /// \n /// Arguments are serialized into JSON and passed to the server, where they may be used to customize the \n /// prompt's behavior or content. Each prompt may have different argument requirements.\n /// \n /// \n /// The returned contains a collection of objects,\n /// which can be converted to objects using the method.\n /// \n /// \n /// Thrown when the prompt does not exist, when required arguments are missing, or when the server encounters an error processing the prompt.\n /// is .\n public static ValueTask GetPromptAsync(\n this IMcpClient client,\n string name,\n IReadOnlyDictionary? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(name);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n return client.SendRequestAsync(\n RequestMethods.PromptsGet,\n new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },\n McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,\n McpJsonUtilities.JsonContext.Default.GetPromptResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Retrieves a list of available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resource templates as instances.\n /// \n /// \n /// This method fetches all available resource templates from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resource templates and that responds with paginated responses, consider using \n /// instead, as it streams templates as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListResourceTemplatesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resourceTemplates = null;\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resourceTemplates ??= new List(templateResults.ResourceTemplates.Count);\n foreach (var template in templateResults.ResourceTemplates)\n {\n resourceTemplates.Add(new McpClientResourceTemplate(client, template));\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n\n return resourceTemplates;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resource templates as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resource templates from the server, which allows processing templates\n /// as they arrive rather than waiting for all templates to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with templates split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resource templates.\n /// \n /// \n /// \n /// \n /// // Enumerate all resource templates available on the server\n /// await foreach (var template in client.EnumerateResourceTemplatesAsync())\n /// {\n /// Console.WriteLine($\"Template: {template.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourceTemplatesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var templateResult in templateResults.ResourceTemplates)\n {\n yield return new McpClientResourceTemplate(client, templateResult);\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resources as instances.\n /// \n /// \n /// This method fetches all available resources from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resources and that responds with paginated responses, consider using \n /// instead, as it streams resources as they arrive rather than loading them all at once.\n /// \n /// \n /// \n /// \n /// // Get all resources available on the server\n /// var resources = await client.ListResourcesAsync();\n /// \n /// // Display information about each resource\n /// foreach (var resource in resources)\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListResourcesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resources = null;\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resources ??= new List(resourceResults.Resources.Count);\n foreach (var resource in resourceResults.Resources)\n {\n resources.Add(new McpClientResource(client, resource));\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n\n return resources;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resources as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resources from the server, which allows processing resources\n /// as they arrive rather than waiting for all resources to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with resources split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resources.\n /// \n /// \n /// \n /// \n /// // Enumerate all resources available on the server\n /// await foreach (var resource in client.EnumerateResourcesAsync())\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourcesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var resource in resourceResults.Resources)\n {\n yield return new McpClientResource(client, resource);\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return ReadResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri template of the resource.\n /// Arguments to use to format .\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uriTemplate, IReadOnlyDictionary arguments, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uriTemplate);\n Throw.IfNull(arguments);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = UriTemplate.FormatUri(uriTemplate, arguments) },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests completion suggestions for a prompt argument or resource reference.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The reference object specifying the type and optional URI or name.\n /// The name of the argument for which completions are requested.\n /// The current value of the argument, used to filter relevant completions.\n /// The to monitor for cancellation requests. The default is .\n /// A containing completion suggestions.\n /// \n /// \n /// This method allows clients to request auto-completion suggestions for arguments in a prompt template\n /// or for resource references.\n /// \n /// \n /// When working with prompt references, the server will return suggestions for the specified argument\n /// that match or begin with the current argument value. This is useful for implementing intelligent\n /// auto-completion in user interfaces.\n /// \n /// \n /// When working with resource references, the server will return suggestions relevant to the specified \n /// resource URI.\n /// \n /// \n /// is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n /// The server returned an error response.\n public static ValueTask CompleteAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(reference);\n Throw.IfNullOrWhiteSpace(argumentName);\n\n return client.SendRequestAsync(\n RequestMethods.CompletionComplete,\n new()\n {\n Ref = reference,\n Argument = new Argument { Name = argumentName, Value = argumentValue }\n },\n McpJsonUtilities.JsonContext.Default.CompleteRequestParams,\n McpJsonUtilities.JsonContext.Default.CompleteResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesSubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n public static Task SubscribeToResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return SubscribeToResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesUnsubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return UnsubscribeFromResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Invokes a tool on the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the tool to call on the server..\n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// is .\n /// is .\n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// // Call a simple echo tool with a string argument\n /// var result = await client.CallToolAsync(\n /// \"echo\",\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public static ValueTask CallToolAsync(\n this IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(toolName);\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n if (progress is not null)\n {\n return SendRequestWithProgressAsync(client, toolName, arguments, progress, serializerOptions, cancellationToken);\n }\n\n return client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken);\n\n static async ValueTask SendRequestWithProgressAsync(\n IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments,\n IProgress progress,\n JsonSerializerOptions serializerOptions,\n CancellationToken cancellationToken)\n {\n ProgressToken progressToken = new(Guid.NewGuid().ToString(\"N\"));\n\n await using var _ = client.RegisterNotificationHandler(NotificationMethods.ProgressNotification,\n (notification, cancellationToken) =>\n {\n if (JsonSerializer.Deserialize(notification.Params, McpJsonUtilities.JsonContext.Default.ProgressNotificationParams) is { } pn &&\n pn.ProgressToken == progressToken)\n {\n progress.Report(pn.Progress);\n }\n\n return default;\n }).ConfigureAwait(false);\n\n return await client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n ProgressToken = progressToken,\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n }\n\n /// \n /// Converts the contents of a into a pair of\n /// and instances to use\n /// as inputs into a operation.\n /// \n /// \n /// The created pair of messages and options.\n /// is .\n internal static (IList Messages, ChatOptions? Options) ToChatClientArguments(\n this CreateMessageRequestParams requestParams)\n {\n Throw.IfNull(requestParams);\n\n ChatOptions? options = null;\n\n if (requestParams.MaxTokens is int maxTokens)\n {\n (options ??= new()).MaxOutputTokens = maxTokens;\n }\n\n if (requestParams.Temperature is float temperature)\n {\n (options ??= new()).Temperature = temperature;\n }\n\n if (requestParams.StopSequences is { } stopSequences)\n {\n (options ??= new()).StopSequences = stopSequences.ToArray();\n }\n\n List messages =\n (from sm in requestParams.Messages\n let aiContent = sm.Content.ToAIContent()\n where aiContent is not null\n select new ChatMessage(sm.Role == Role.Assistant ? ChatRole.Assistant : ChatRole.User, [aiContent]))\n .ToList();\n\n return (messages, options);\n }\n\n /// Converts the contents of a into a .\n /// The whose contents should be extracted.\n /// The created .\n /// is .\n internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chatResponse)\n {\n Throw.IfNull(chatResponse);\n\n // The ChatResponse can include multiple messages, of varying modalities, but CreateMessageResult supports\n // only either a single blob of text or a single image. Heuristically, we'll use an image if there is one\n // in any of the response messages, or we'll use all the text from them concatenated, otherwise.\n\n ChatMessage? lastMessage = chatResponse.Messages.LastOrDefault();\n\n ContentBlock? content = null;\n if (lastMessage is not null)\n {\n foreach (var lmc in lastMessage.Contents)\n {\n if (lmc is DataContent dc && (dc.HasTopLevelMediaType(\"image\") || dc.HasTopLevelMediaType(\"audio\")))\n {\n content = dc.ToContent();\n }\n }\n }\n\n return new()\n {\n Content = content ?? new TextContentBlock { Text = lastMessage?.Text ?? string.Empty },\n Model = chatResponse.ModelId ?? \"unknown\",\n Role = lastMessage?.Role == ChatRole.User ? Role.User : Role.Assistant,\n StopReason = chatResponse.FinishReason == ChatFinishReason.Length ? \"maxTokens\" : \"endTurn\",\n };\n }\n\n /// \n /// Creates a sampling handler for use with that will\n /// satisfy sampling requests using the specified .\n /// \n /// The with which to satisfy sampling requests.\n /// The created handler delegate that can be assigned to .\n /// \n /// \n /// This method creates a function that converts MCP message requests into chat client calls, enabling\n /// an MCP client to generate text or other content using an actual AI model via the provided chat client.\n /// \n /// \n /// The handler can process text messages, image messages, and resource messages as defined in the\n /// Model Context Protocol.\n /// \n /// \n /// is .\n public static Func, CancellationToken, ValueTask> CreateSamplingHandler(\n this IChatClient chatClient)\n {\n Throw.IfNull(chatClient);\n\n return async (requestParams, progress, cancellationToken) =>\n {\n Throw.IfNull(requestParams);\n\n var (messages, options) = requestParams.ToChatClientArguments();\n var progressToken = requestParams.ProgressToken;\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false))\n {\n updates.Add(update);\n\n if (progressToken is not null)\n {\n progress.Report(new()\n {\n Progress = updates.Count,\n });\n }\n }\n\n return updates.ToChatResponse().ToCreateMessageResult();\n };\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// , , and \n /// level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LoggingLevel level, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.LoggingSetLevel,\n new() { Level = level },\n McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// and level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LogLevel level, CancellationToken cancellationToken = default) =>\n SetLoggingLevel(client, McpServer.ToLoggingLevel(level), cancellationToken);\n\n /// Convers a dictionary with values to a dictionary with values.\n private static Dictionary? ToArgumentsDictionary(\n IReadOnlyDictionary? arguments, JsonSerializerOptions options)\n {\n var typeInfo = options.GetTypeInfo();\n\n Dictionary? result = null;\n if (arguments is not null)\n {\n result = new(arguments.Count);\n foreach (var kvp in arguments)\n {\n result.Add(kvp.Key, kvp.Value is JsonElement je ? je : JsonSerializer.SerializeToElement(kvp.Value, typeInfo));\n }\n }\n\n return result;\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DestinationBoundMcpServer.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class DestinationBoundMcpServer(McpServer server, ITransport? transport) : IMcpServer\n{\n public string EndpointName => server.EndpointName;\n public string? SessionId => transport?.SessionId ?? server.SessionId;\n public ClientCapabilities? ClientCapabilities => server.ClientCapabilities;\n public Implementation? ClientInfo => server.ClientInfo;\n public McpServerOptions ServerOptions => server.ServerOptions;\n public IServiceProvider? Services => server.Services;\n public LoggingLevel? LoggingLevel => server.LoggingLevel;\n\n public ValueTask DisposeAsync() => server.DisposeAsync();\n\n public IAsyncDisposable RegisterNotificationHandler(string method, Func handler) => server.RegisterNotificationHandler(method, handler);\n\n // This will throw because the server must already be running for this class to be constructed, but it should give us a good Exception message.\n public Task RunAsync(CancellationToken cancellationToken) => server.RunAsync(cancellationToken);\n\n public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Debug.Assert(message.RelatedTransport is null);\n message.RelatedTransport = transport;\n return server.SendMessageAsync(message, cancellationToken);\n }\n\n public Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)\n {\n Debug.Assert(request.RelatedTransport is null);\n request.RelatedTransport = transport;\n return server.SendRequestAsync(request, cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Diagnostics.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\n\nnamespace ModelContextProtocol;\n\ninternal static class Diagnostics\n{\n internal static ActivitySource ActivitySource { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Meter Meter { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Histogram CreateDurationHistogram(string name, string description, bool longBuckets) =>\n Meter.CreateHistogram(name, \"s\", description\n#if NET9_0_OR_GREATER\n , advice: longBuckets ? LongSecondsBucketBoundaries : ShortSecondsBucketBoundaries\n#endif\n );\n\n#if NET9_0_OR_GREATER\n /// \n /// Follows boundaries from http.server.request.duration/http.client.request.duration\n /// \n private static InstrumentAdvice ShortSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n };\n\n /// \n /// Not based on a standard. Larger bucket sizes for longer lasting operations, e.g. HTTP connection duration.\n /// See https://github.com/open-telemetry/semantic-conventions/issues/336\n /// \n private static InstrumentAdvice LongSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300],\n };\n#endif\n\n internal static ActivityContext ExtractActivityContext(this DistributedContextPropagator propagator, JsonRpcMessage message)\n {\n propagator.ExtractTraceIdAndState(message, ExtractContext, out var traceparent, out var tracestate);\n ActivityContext.TryParse(traceparent, tracestate, true, out var activityContext);\n return activityContext;\n }\n\n private static void ExtractContext(object? message, string fieldName, out string? fieldValue, out IEnumerable? fieldValues)\n {\n fieldValues = null;\n fieldValue = null;\n\n JsonNode? meta = null;\n switch (message)\n {\n case JsonRpcRequest request:\n meta = request.Params?[\"_meta\"];\n break;\n\n case JsonRpcNotification notification:\n meta = notification.Params?[\"_meta\"];\n break;\n }\n\n if (meta?[fieldName] is JsonValue value && value.GetValueKind() == JsonValueKind.String)\n {\n fieldValue = value.GetValue();\n }\n }\n\n internal static void InjectActivityContext(this DistributedContextPropagator propagator, Activity? activity, JsonRpcMessage message)\n {\n // noop if activity is null\n propagator.Inject(activity, message, InjectContext);\n }\n\n private static void InjectContext(object? message, string key, string value)\n {\n JsonNode? parameters = null;\n switch (message)\n {\n case JsonRpcRequest request:\n parameters = request.Params;\n break;\n\n case JsonRpcNotification notification:\n parameters = notification.Params;\n break;\n }\n\n // Replace any params._meta with the current value\n if (parameters is JsonObject jsonObject)\n {\n if (jsonObject[\"_meta\"] is not JsonObject meta)\n {\n meta = new JsonObject();\n jsonObject[\"_meta\"] = meta;\n }\n meta[key] = value;\n }\n }\n\n internal static bool ShouldInstrumentMessage(JsonRpcMessage message) =>\n ActivitySource.HasListeners() &&\n message switch\n {\n JsonRpcRequest => true,\n JsonRpcNotification notification => notification.Method != NotificationMethods.LoggingMessageNotification,\n _ => false\n };\n\n internal static ActivityLink[] ActivityLinkFromCurrent() => Activity.Current is null ? [] : [new ActivityLink(Activity.Current.Context)];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as\n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \npublic sealed class StreamableHttpServerTransport : ITransport\n{\n // For JsonRpcMessages without a RelatedTransport, we don't want to block just because the client didn't make a GET request to handle unsolicited messages.\n private readonly SseWriter _sseWriter = new(channelOptions: new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n FullMode = BoundedChannelFullMode.DropOldest,\n });\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n private readonly CancellationTokenSource _disposeCts = new();\n\n private int _getRequestStarted;\n\n /// \n public string? SessionId { get; set; }\n\n /// \n /// Configures whether the transport should be in stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process. Unsolicited server-to-client messages are not supported in this mode,\n /// so calling results in an .\n /// Server-to-client requests are also unsupported, because the responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// \n public bool Stateless { get; init; }\n\n /// \n /// Gets a value indicating whether the execution context should flow from the calls to \n /// to the corresponding emitted by the .\n /// \n /// \n /// Defaults to .\n /// \n public bool FlowExecutionContextFromRequests { get; init; }\n\n /// \n /// Gets or sets a callback to be invoked before handling the initialize request.\n /// \n public Func? OnInitRequestReceived { get; set; }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n internal ChannelWriter MessageWriter => _incomingChannel.Writer;\n\n /// \n /// Handles an optional SSE GET request a client using the Streamable HTTP transport might make by\n /// writing any unsolicited JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The response stream to write MCP JSON-RPC messages as SSE events to.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task HandleGetRequest(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"GET requests are not supported in stateless mode.\");\n }\n\n if (Interlocked.Exchange(ref _getRequestStarted, 1) == 1)\n {\n throw new InvalidOperationException(\"Session resumption is not yet supported. Please start a new session.\");\n }\n\n // We do not need to reference _disposeCts like in HandlePostRequest, because the session ending completes the _sseWriter gracefully.\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles a Streamable HTTP POST request processing both the request body and response body ensuring that\n /// and other correlated messages are sent back to the client directly in response\n /// to the that initiated the message.\n /// \n /// The duplex pipe facilitates the reading and writing of HTTP request and response data.\n /// This token allows for the operation to be canceled if needed.\n /// \n /// True, if data was written to the response body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async Task HandlePostRequest(IDuplexPipe httpBodies, CancellationToken cancellationToken)\n {\n using var postCts = CancellationTokenSource.CreateLinkedTokenSource(_disposeCts.Token, cancellationToken);\n await using var postTransport = new StreamableHttpPostTransport(this, httpBodies);\n return await postTransport.RunAsync(postCts.Token).ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"Unsolicited server to client messages are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n }\n finally\n {\n try\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n finally\n {\n _disposeCts.Dispose();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerPrompt : McpServerPrompt\n{\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n object? target,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerPromptCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(function);\n\n List args = [];\n HashSet? requiredProps = function.JsonSchema.TryGetProperty(\"required\", out JsonElement required)\n ? new(required.EnumerateArray().Select(p => p.GetString()!), StringComparer.Ordinal)\n : null;\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n foreach (var param in properties.EnumerateObject())\n {\n args.Add(new()\n {\n Name = param.Name,\n Description = param.Value.TryGetProperty(\"description\", out JsonElement description) ? description.GetString() : null,\n Required = requiredProps?.Contains(param.Name) ?? false,\n });\n }\n }\n\n Prompt prompt = new()\n {\n Name = options?.Name ?? function.Name,\n Title = options?.Title,\n Description = options?.Description ?? function.Description,\n Arguments = args,\n };\n\n return new AIFunctionMcpServerPrompt(function, prompt);\n }\n\n private static McpServerPromptCreateOptions DeriveOptions(MethodInfo method, McpServerPromptCreateOptions? options)\n {\n McpServerPromptCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } promptAttr)\n {\n newOptions.Name ??= promptAttr.Name;\n newOptions.Title ??= promptAttr.Title;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this prompt.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerPrompt(AIFunction function, Prompt prompt)\n {\n AIFunction = function;\n ProtocolPrompt = prompt;\n }\n\n /// \n public override Prompt ProtocolPrompt { get; }\n\n /// \n public override async ValueTask GetAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n return result switch\n {\n GetPromptResult getPromptResult => getPromptResult,\n\n string text => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [new() { Role = Role.User, Content = new TextContentBlock { Text = text } }],\n },\n\n PromptMessage promptMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [promptMessage],\n },\n\n IEnumerable promptMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. promptMessages],\n },\n\n ChatMessage chatMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessage.ToPromptMessages()],\n },\n\n IEnumerable chatMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessages.SelectMany(chatMessage => chatMessage.ToPromptMessages())],\n },\n\n null => throw new InvalidOperationException(\"Null result returned from prompt function.\"),\n\n _ => throw new InvalidOperationException($\"Unknown result type '{result.GetType()}' returned from prompt function.\"),\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerResource : McpServerResource\n{\n private readonly Regex? _uriParser;\n private readonly string[] _templateVariableNames = [];\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n object? target,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerResourceCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n // These parameters are the ones and only ones to include in the schema. The schema\n // won't be consumed by anyone other than this instance, which will use it to determine\n // which properties should show up in the URI template.\n if (pi.Name is not null && GetConverter(pi.ParameterType) is { } converter)\n {\n return new()\n {\n ExcludeFromSchema = false,\n BindParameter = (pi, args) =>\n {\n if (args.TryGetValue(pi.Name!, out var value))\n {\n return\n value is null || pi.ParameterType.IsInstanceOfType(value) ? value :\n value is string stringValue ? converter(stringValue) :\n throw new ArgumentException($\"Parameter '{pi.Name}' is of type '{pi.ParameterType}', but value '{value}' is of type '{value.GetType()}'.\");\n }\n\n return\n pi.HasDefaultValue ? pi.DefaultValue :\n throw new ArgumentException($\"Missing a value for the required parameter '{pi.Name}'.\");\n },\n };\n }\n\n return default;\n },\n };\n\n private static readonly ConcurrentDictionary> s_convertersCache = [];\n\n private static Func? GetConverter(Type type)\n {\n Type key = type;\n\n if (s_convertersCache.TryGetValue(key, out var converter))\n {\n return converter;\n }\n\n if (Nullable.GetUnderlyingType(type) is { } underlyingType)\n {\n // We will have already screened out null values by the time the converter is used,\n // so we can parse just the underlying type.\n type = underlyingType;\n }\n\n if (type == typeof(string) || type == typeof(object)) converter = static s => s;\n if (type == typeof(bool)) converter = static s => bool.Parse(s);\n if (type == typeof(char)) converter = static s => char.Parse(s);\n if (type == typeof(byte)) converter = static s => byte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(sbyte)) converter = static s => sbyte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ushort)) converter = static s => ushort.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(short)) converter = static s => short.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(uint)) converter = static s => uint.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(int)) converter = static s => int.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ulong)) converter = static s => ulong.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(long)) converter = static s => long.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(float)) converter = static s => float.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(double)) converter = static s => double.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(decimal)) converter = static s => decimal.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeSpan)) converter = static s => TimeSpan.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTime)) converter = static s => DateTime.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTimeOffset)) converter = static s => DateTimeOffset.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Uri)) converter = static s => new Uri(s, UriKind.RelativeOrAbsolute);\n if (type == typeof(Guid)) converter = static s => Guid.Parse(s);\n if (type == typeof(Version)) converter = static s => Version.Parse(s);\n#if NET\n if (type == typeof(Half)) converter = static s => Half.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Int128)) converter = static s => Int128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UInt128)) converter = static s => UInt128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(IntPtr)) converter = static s => IntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UIntPtr)) converter = static s => UIntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateOnly)) converter = static s => DateOnly.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeOnly)) converter = static s => TimeOnly.Parse(s, CultureInfo.InvariantCulture);\n#endif\n if (type.IsEnum) converter = s => Enum.Parse(type, s);\n\n if (type.GetCustomAttribute() is TypeConverterAttribute tca &&\n Type.GetType(tca.ConverterTypeName, throwOnError: false) is { } converterType &&\n Activator.CreateInstance(converterType) is TypeConverter typeConverter &&\n typeConverter.CanConvertFrom(typeof(string)))\n {\n converter = s => typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, s);\n }\n\n if (converter is not null)\n {\n s_convertersCache.TryAdd(key, converter);\n }\n\n return converter;\n }\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerResource Create(AIFunction function, McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(function);\n\n string name = options?.Name ?? function.Name;\n\n ResourceTemplate resource = new()\n {\n UriTemplate = options?.UriTemplate ?? DeriveUriTemplate(name, function),\n Name = name,\n Title = options?.Title,\n Description = options?.Description,\n MimeType = options?.MimeType ?? \"application/octet-stream\",\n };\n\n return new AIFunctionMcpServerResource(function, resource);\n }\n\n private static McpServerResourceCreateOptions DeriveOptions(MemberInfo member, McpServerResourceCreateOptions? options)\n {\n McpServerResourceCreateOptions newOptions = options?.Clone() ?? new();\n\n if (member.GetCustomAttribute() is { } resourceAttr)\n {\n newOptions.UriTemplate ??= resourceAttr.UriTemplate;\n newOptions.Name ??= resourceAttr.Name;\n newOptions.Title ??= resourceAttr.Title;\n newOptions.MimeType ??= resourceAttr.MimeType;\n }\n\n if (member.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Derives a name to be used as a resource name.\n private static string DeriveUriTemplate(string name, AIFunction function)\n {\n StringBuilder template = new();\n\n template.Append(\"resource://mcp/\").Append(Uri.EscapeDataString(name));\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n string separator = \"{?\";\n foreach (var prop in properties.EnumerateObject())\n {\n template.Append(separator).Append(prop.Name);\n separator = \",\";\n }\n\n if (separator == \",\")\n {\n template.Append('}');\n }\n }\n\n return template.ToString();\n }\n\n /// Gets the wrapped by this resource.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerResource(AIFunction function, ResourceTemplate resourceTemplate)\n {\n AIFunction = function;\n ProtocolResourceTemplate = resourceTemplate;\n ProtocolResource = resourceTemplate.AsResource();\n\n if (ProtocolResource is null)\n {\n _uriParser = UriTemplate.CreateParser(resourceTemplate.UriTemplate);\n _templateVariableNames = _uriParser.GetGroupNames().Where(n => n != \"0\").ToArray();\n }\n }\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// \n public override Resource? ProtocolResource { get; }\n\n /// \n public override async ValueTask ReadAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n Throw.IfNull(request.Params);\n Throw.IfNull(request.Params.Uri);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check to see if this URI template matches the request URI. If it doesn't, return null.\n // For templates, use the Regex to parse. For static resources, we can just compare the URIs.\n Match? match = null;\n if (_uriParser is not null)\n {\n match = _uriParser.Match(request.Params.Uri);\n if (!match.Success)\n {\n return null;\n }\n }\n else if (!UriTemplate.UriTemplateComparer.Instance.Equals(request.Params.Uri, ProtocolResource!.Uri))\n {\n return null;\n }\n\n // Build up the arguments for the AIFunction call, including all of the name/value pairs from the URI.\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n // For templates, populate the arguments from the URI template.\n if (match is not null)\n {\n foreach (string varName in _templateVariableNames)\n {\n if (match.Groups[varName] is { Success: true } value)\n {\n arguments[varName] = Uri.UnescapeDataString(value.Value);\n }\n }\n }\n\n // Invoke the function.\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n // And process the result.\n return result switch\n {\n ReadResourceResult readResourceResult => readResourceResult,\n\n ResourceContents content => new()\n {\n Contents = [content],\n },\n\n TextContent tc => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = tc.Text }],\n },\n\n DataContent dc => new()\n {\n Contents = [new BlobResourceContents { Uri = request.Params!.Uri, MimeType = dc.MediaType, Blob = dc.Base64Data.ToString() }],\n },\n\n string text => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = text }],\n },\n\n IEnumerable contents => new()\n {\n Contents = contents.ToList(),\n },\n\n IEnumerable aiContents => new()\n {\n Contents = aiContents.Select(\n ac => ac switch\n {\n TextContent tc => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = tc.Text\n },\n\n DataContent dc => new BlobResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = dc.MediaType,\n Blob = dc.Base64Data.ToString()\n },\n\n _ => throw new InvalidOperationException($\"Unsupported AIContent type '{ac.GetType()}' returned from resource function.\"),\n }).ToList(),\n },\n\n IEnumerable strings => new()\n {\n Contents = strings.Select(text => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = text\n }).ToList(),\n },\n\n null => throw new InvalidOperationException(\"Null result returned from resource function.\"),\n\n _ => throw new InvalidOperationException($\"Unsupported result type '{result.GetType()}' returned from resource function.\"),\n };\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/Client/StdioClientSessionTransport.cs", "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 protected override async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)\n {\n // Only clean up once.\n if (Interlocked.Exchange(ref _cleanedUp, 1) != 0)\n {\n return;\n }\n\n // We've not yet forcefully terminated the server. If it's already shut down, something went wrong,\n // so create an exception with details about that.\n error ??= await GetUnexpectedExitExceptionAsync(cancellationToken).ConfigureAwait(false);\n\n // Now terminate the server process.\n try\n {\n StdioClientTransport.DisposeProcess(_process, processRunning: true, _options.ShutdownTimeout, Name);\n }\n catch (Exception ex)\n {\n LogTransportShutdownFailed(Name, ex);\n }\n\n // And handle cleanup in the base type.\n await base.CleanupAsync(error, cancellationToken);\n }\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"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpJsonUtilities.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Authentication;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// Provides a collection of utility methods for working with JSON data in the context of MCP.\npublic static partial class McpJsonUtilities\n{\n /// \n /// Gets the singleton used as the default in JSON serialization operations.\n /// \n /// \n /// \n /// For Native AOT or applications disabling , this instance \n /// includes source generated contracts for all common exchange types contained in the ModelContextProtocol library.\n /// \n /// \n /// It additionally turns on the following settings:\n /// \n /// Enables defaults.\n /// Enables as the default ignore condition for properties.\n /// Enables as the default number handling for number types.\n /// \n /// \n /// \n public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();\n\n /// \n /// Creates default options to use for MCP-related serialization.\n /// \n /// The configured options.\n [UnconditionalSuppressMessage(\"ReflectionAnalysis\", \"IL3050:RequiresDynamicCode\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n [UnconditionalSuppressMessage(\"Trimming\", \"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n private static JsonSerializerOptions CreateDefaultOptions()\n {\n // Copy the configuration from the source generated context.\n JsonSerializerOptions options = new(JsonContext.Default.Options);\n\n // Chain with all supported types from MEAI.\n options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);\n\n // Add a converter for user-defined enums, if reflection is enabled by default.\n if (JsonSerializer.IsReflectionEnabledByDefault)\n {\n options.Converters.Add(new CustomizableJsonStringEnumConverter());\n }\n\n options.MakeReadOnly();\n return options;\n }\n\n internal static JsonTypeInfo GetTypeInfo(this JsonSerializerOptions options) =>\n (JsonTypeInfo)options.GetTypeInfo(typeof(T));\n\n internal static JsonElement DefaultMcpToolSchema { get; } = ParseJsonElement(\"\"\"{\"type\":\"object\"}\"\"\"u8);\n internal static object? AsObject(this JsonElement element) => element.ValueKind is JsonValueKind.Null ? null : element;\n\n internal static bool IsValidMcpToolSchema(JsonElement element)\n {\n if (element.ValueKind is not JsonValueKind.Object)\n {\n return false;\n }\n\n foreach (JsonProperty property in element.EnumerateObject())\n {\n if (property.NameEquals(\"type\"))\n {\n if (property.Value.ValueKind is not JsonValueKind.String ||\n !property.Value.ValueEquals(\"object\"))\n {\n return false;\n }\n\n return true; // No need to check other properties\n }\n }\n\n return false; // No type keyword found.\n }\n\n // Keep in sync with CreateDefaultOptions above.\n [JsonSourceGenerationOptions(JsonSerializerDefaults.Web,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n NumberHandling = JsonNumberHandling.AllowReadingFromString)]\n \n // JSON-RPC\n [JsonSerializable(typeof(JsonRpcMessage))]\n [JsonSerializable(typeof(JsonRpcMessage[]))]\n [JsonSerializable(typeof(JsonRpcRequest))]\n [JsonSerializable(typeof(JsonRpcNotification))]\n [JsonSerializable(typeof(JsonRpcResponse))]\n [JsonSerializable(typeof(JsonRpcError))]\n\n // MCP Notification Params\n [JsonSerializable(typeof(CancelledNotificationParams))]\n [JsonSerializable(typeof(InitializedNotificationParams))]\n [JsonSerializable(typeof(LoggingMessageNotificationParams))]\n [JsonSerializable(typeof(ProgressNotificationParams))]\n [JsonSerializable(typeof(PromptListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceUpdatedNotificationParams))]\n [JsonSerializable(typeof(RootsListChangedNotificationParams))]\n [JsonSerializable(typeof(ToolListChangedNotificationParams))]\n\n // MCP Request Params / Results\n [JsonSerializable(typeof(CallToolRequestParams))]\n [JsonSerializable(typeof(CallToolResult))]\n [JsonSerializable(typeof(CompleteRequestParams))]\n [JsonSerializable(typeof(CompleteResult))]\n [JsonSerializable(typeof(CreateMessageRequestParams))]\n [JsonSerializable(typeof(CreateMessageResult))]\n [JsonSerializable(typeof(ElicitRequestParams))]\n [JsonSerializable(typeof(ElicitResult))]\n [JsonSerializable(typeof(EmptyResult))]\n [JsonSerializable(typeof(GetPromptRequestParams))]\n [JsonSerializable(typeof(GetPromptResult))]\n [JsonSerializable(typeof(InitializeRequestParams))]\n [JsonSerializable(typeof(InitializeResult))]\n [JsonSerializable(typeof(ListPromptsRequestParams))]\n [JsonSerializable(typeof(ListPromptsResult))]\n [JsonSerializable(typeof(ListResourcesRequestParams))]\n [JsonSerializable(typeof(ListResourcesResult))]\n [JsonSerializable(typeof(ListResourceTemplatesRequestParams))]\n [JsonSerializable(typeof(ListResourceTemplatesResult))]\n [JsonSerializable(typeof(ListRootsRequestParams))]\n [JsonSerializable(typeof(ListRootsResult))]\n [JsonSerializable(typeof(ListToolsRequestParams))]\n [JsonSerializable(typeof(ListToolsResult))]\n [JsonSerializable(typeof(PingResult))]\n [JsonSerializable(typeof(ReadResourceRequestParams))]\n [JsonSerializable(typeof(ReadResourceResult))]\n [JsonSerializable(typeof(SetLevelRequestParams))]\n [JsonSerializable(typeof(SubscribeRequestParams))]\n [JsonSerializable(typeof(UnsubscribeRequestParams))]\n\n // MCP Content\n [JsonSerializable(typeof(ContentBlock))]\n [JsonSerializable(typeof(TextContentBlock))]\n [JsonSerializable(typeof(ImageContentBlock))]\n [JsonSerializable(typeof(AudioContentBlock))]\n [JsonSerializable(typeof(EmbeddedResourceBlock))]\n [JsonSerializable(typeof(ResourceLinkBlock))]\n [JsonSerializable(typeof(PromptReference))]\n [JsonSerializable(typeof(ResourceTemplateReference))]\n [JsonSerializable(typeof(BlobResourceContents))]\n [JsonSerializable(typeof(TextResourceContents))]\n\n // Other MCP Types\n [JsonSerializable(typeof(IReadOnlyDictionary))]\n [JsonSerializable(typeof(ProgressToken))]\n\n [JsonSerializable(typeof(ProtectedResourceMetadata))]\n [JsonSerializable(typeof(AuthorizationServerMetadata))]\n [JsonSerializable(typeof(TokenContainer))]\n [JsonSerializable(typeof(DynamicClientRegistrationRequest))]\n [JsonSerializable(typeof(DynamicClientRegistrationResponse))]\n\n // Primitive types for use in consuming AIFunctions\n [JsonSerializable(typeof(string))]\n [JsonSerializable(typeof(byte))]\n [JsonSerializable(typeof(byte?))]\n [JsonSerializable(typeof(sbyte))]\n [JsonSerializable(typeof(sbyte?))]\n [JsonSerializable(typeof(ushort))]\n [JsonSerializable(typeof(ushort?))]\n [JsonSerializable(typeof(short))]\n [JsonSerializable(typeof(short?))]\n [JsonSerializable(typeof(uint))]\n [JsonSerializable(typeof(uint?))]\n [JsonSerializable(typeof(int))]\n [JsonSerializable(typeof(int?))]\n [JsonSerializable(typeof(ulong))]\n [JsonSerializable(typeof(ulong?))]\n [JsonSerializable(typeof(long))]\n [JsonSerializable(typeof(long?))]\n [JsonSerializable(typeof(nuint))]\n [JsonSerializable(typeof(nuint?))]\n [JsonSerializable(typeof(nint))]\n [JsonSerializable(typeof(nint?))]\n [JsonSerializable(typeof(bool))]\n [JsonSerializable(typeof(bool?))]\n [JsonSerializable(typeof(char))]\n [JsonSerializable(typeof(char?))]\n [JsonSerializable(typeof(float))]\n [JsonSerializable(typeof(float?))]\n [JsonSerializable(typeof(double))]\n [JsonSerializable(typeof(double?))]\n [JsonSerializable(typeof(decimal))]\n [JsonSerializable(typeof(decimal?))]\n [JsonSerializable(typeof(Guid))]\n [JsonSerializable(typeof(Guid?))]\n [JsonSerializable(typeof(Uri))]\n [JsonSerializable(typeof(Version))]\n [JsonSerializable(typeof(TimeSpan))]\n [JsonSerializable(typeof(TimeSpan?))]\n [JsonSerializable(typeof(DateTime))]\n [JsonSerializable(typeof(DateTime?))]\n [JsonSerializable(typeof(DateTimeOffset))]\n [JsonSerializable(typeof(DateTimeOffset?))]\n#if NET\n [JsonSerializable(typeof(DateOnly))]\n [JsonSerializable(typeof(DateOnly?))]\n [JsonSerializable(typeof(TimeOnly))]\n [JsonSerializable(typeof(TimeOnly?))]\n [JsonSerializable(typeof(Half))]\n [JsonSerializable(typeof(Half?))]\n [JsonSerializable(typeof(Int128))]\n [JsonSerializable(typeof(Int128?))]\n [JsonSerializable(typeof(UInt128))]\n [JsonSerializable(typeof(UInt128?))]\n#endif\n\n [ExcludeFromCodeCoverage]\n internal sealed partial class JsonContext : JsonSerializerContext;\n\n private static JsonElement ParseJsonElement(ReadOnlySpan utf8Json)\n {\n Utf8JsonReader reader = new(utf8Json);\n return JsonElement.ParseValue(ref reader);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseResponseStreamTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as \n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \n/// The response stream to write MCP JSON-RPC messages as SSE events to.\n/// \n/// The relative or absolute URI the client should use to post MCP JSON-RPC messages for this session.\n/// These messages should be passed to .\n/// Defaults to \"/message\".\n/// \n/// The identifier corresponding to the current MCP session.\npublic sealed class SseResponseStreamTransport(Stream sseResponseStream, string? messageEndpoint = \"/message\", string? sessionId = null) : ITransport\n{\n private readonly SseWriter _sseWriter = new(messageEndpoint);\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private bool _isConnected;\n\n /// \n /// Starts the transport and writes the JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task RunAsync(CancellationToken cancellationToken)\n {\n _isConnected = true;\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n /// \n public string? SessionId { get; } = sessionId;\n\n /// \n public async ValueTask DisposeAsync()\n {\n _isConnected = false;\n _incomingChannel.Writer.TryComplete();\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles incoming JSON-RPC messages received on the /message endpoint.\n /// \n /// The JSON-RPC message received from the client.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation to buffer the JSON-RPC message for processing.\n /// Thrown when there is an attempt to process a message before calling .\n /// \n /// \n /// This method is the entry point for processing client-to-server communication in the SSE transport model. \n /// While the SSE protocol itself is unidirectional (server to client), this method allows bidirectional \n /// communication by handling HTTP POST requests sent to the message endpoint.\n /// \n /// \n /// When a client sends a JSON-RPC message to the /message endpoint, the server calls this method to\n /// process the message and make it available to the MCP server via the channel.\n /// \n /// \n /// This method validates that the transport is connected before processing the message, ensuring proper\n /// sequencing of operations in the transport lifecycle.\n /// \n /// \n public async Task OnMessageReceivedAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n Throw.IfNull(message);\n\n if (!_isConnected)\n {\n throw new InvalidOperationException($\"Transport is not connected. Make sure to call {nameof(RunAsync)} first.\");\n }\n\n await _incomingChannel.Writer.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessage.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents any JSON-RPC message used in the Model Context Protocol (MCP).\n/// \n/// \n/// This interface serves as the foundation for all message types in the JSON-RPC 2.0 protocol\n/// used by MCP, including requests, responses, notifications, and errors. JSON-RPC is a stateless,\n/// lightweight remote procedure call (RPC) protocol that uses JSON as its data format.\n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessage()\n {\n }\n\n /// \n /// Gets the JSON-RPC protocol version used.\n /// \n /// \n [JsonPropertyName(\"jsonrpc\")]\n public string JsonRpc { get; init; } = \"2.0\";\n\n /// \n /// Gets or sets the transport the was received on or should be sent over.\n /// \n /// \n /// This is used to support the Streamable HTTP transport where the specification states that the server\n /// SHOULD include JSON-RPC responses in the HTTP response body for the POST request containing\n /// the corresponding JSON-RPC request. It may be for other transports.\n /// \n [JsonIgnore]\n public ITransport? RelatedTransport { get; set; }\n\n /// \n /// Gets or sets the that should be used to run any handlers\n /// \n /// \n /// This is used to support the Streamable HTTP transport in its default stateful mode. In this mode,\n /// the outlives the initial HTTP request context it was created on, and new\n /// JSON-RPC messages can originate from future HTTP requests. This allows the transport to flow the\n /// context with the JSON-RPC message. This is particularly useful for enabling IHttpContextAccessor\n /// in tool calls.\n /// \n [JsonIgnore]\n public ExecutionContext? ExecutionContext { get; set; }\n\n /// \n /// Provides a for messages,\n /// handling polymorphic deserialization of different message types.\n /// \n /// \n /// \n /// This converter is responsible for correctly deserializing JSON-RPC messages into their appropriate\n /// concrete types based on the message structure. It analyzes the JSON payload and determines if it\n /// represents a request, notification, successful response, or error response.\n /// \n /// \n /// The type determination rules follow the JSON-RPC 2.0 specification:\n /// \n /// Messages with \"method\" and \"id\" properties are deserialized as .\n /// Messages with \"method\" but no \"id\" property are deserialized as .\n /// Messages with \"id\" and \"result\" properties are deserialized as .\n /// Messages with \"id\" and \"error\" properties are deserialized as .\n /// \n /// \n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override JsonRpcMessage? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException(\"Expected StartObject token\");\n }\n\n using var doc = JsonDocument.ParseValue(ref reader);\n var root = doc.RootElement;\n\n // All JSON-RPC messages must have a jsonrpc property with value \"2.0\"\n if (!root.TryGetProperty(\"jsonrpc\", out var versionProperty) ||\n versionProperty.GetString() != \"2.0\")\n {\n throw new JsonException(\"Invalid or missing jsonrpc version\");\n }\n\n // Determine the message type based on the presence of id, method, and error properties\n bool hasId = root.TryGetProperty(\"id\", out _);\n bool hasMethod = root.TryGetProperty(\"method\", out _);\n bool hasError = root.TryGetProperty(\"error\", out _);\n\n var rawText = root.GetRawText();\n\n // Messages with an id but no method are responses\n if (hasId && !hasMethod)\n {\n // Messages with an error property are error responses\n if (hasError)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with a result property are success responses\n if (root.TryGetProperty(\"result\", out _))\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Response must have either result or error\");\n }\n\n // Messages with a method but no id are notifications\n if (hasMethod && !hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with both method and id are requests\n if (hasMethod && hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Invalid JSON-RPC message format\");\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, JsonRpcMessage value, JsonSerializerOptions options)\n {\n switch (value)\n {\n case JsonRpcRequest request:\n JsonSerializer.Serialize(writer, request, options.GetTypeInfo());\n break;\n case JsonRpcNotification notification:\n JsonSerializer.Serialize(writer, notification, options.GetTypeInfo());\n break;\n case JsonRpcResponse response:\n JsonSerializer.Serialize(writer, response, options.GetTypeInfo());\n break;\n case JsonRpcError error:\n JsonSerializer.Serialize(writer, error, options.GetTypeInfo());\n break;\n default:\n throw new JsonException($\"Unknown JSON-RPC message type: {value.GetType()}\");\n }\n }\n }\n}\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/samples/ProtectedMCPClient/Program.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Text;\nusing System.Web;\n\nvar serverUrl = \"http://localhost:7071/\";\n\nConsole.WriteLine(\"Protected MCP Client\");\nConsole.WriteLine($\"Connecting to weather server at {serverUrl}...\");\nConsole.WriteLine();\n\n// We can customize a shared HttpClient with a custom handler if desired\nvar sharedHandler = new SocketsHttpHandler\n{\n PooledConnectionLifetime = TimeSpan.FromMinutes(2),\n PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1)\n};\nvar httpClient = new HttpClient(sharedHandler);\n\nvar consoleLoggerFactory = LoggerFactory.Create(builder =>\n{\n builder.AddConsole();\n});\n\nvar transport = new SseClientTransport(new()\n{\n Endpoint = new Uri(serverUrl),\n Name = \"Secure Weather Client\",\n OAuth = new()\n {\n ClientName = \"ProtectedMcpClient\",\n RedirectUri = new Uri(\"http://localhost:1179/callback\"),\n AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,\n }\n}, httpClient, consoleLoggerFactory);\n\nvar client = await McpClientFactory.CreateAsync(transport, loggerFactory: consoleLoggerFactory);\n\nvar tools = await client.ListToolsAsync();\nif (tools.Count == 0)\n{\n Console.WriteLine(\"No tools available on the server.\");\n return;\n}\n\nConsole.WriteLine($\"Found {tools.Count} tools on the server.\");\nConsole.WriteLine();\n\nif (tools.Any(t => t.Name == \"get_alerts\"))\n{\n Console.WriteLine(\"Calling get_alerts tool...\");\n\n var result = await client.CallToolAsync(\n \"get_alerts\",\n new Dictionary { { \"state\", \"WA\" } }\n );\n\n Console.WriteLine(\"Result: \" + ((TextContentBlock)result.Content[0]).Text);\n Console.WriteLine();\n}\n\n/// Handles the OAuth authorization URL by starting a local HTTP server and opening a browser.\n/// This implementation demonstrates how SDK consumers can provide their own authorization flow.\n/// \n/// The authorization URL to open in the browser.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// The authorization code extracted from the callback, or null if the operation failed.\nstatic async Task HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken)\n{\n Console.WriteLine(\"Starting OAuth authorization flow...\");\n Console.WriteLine($\"Opening browser to: {authorizationUrl}\");\n\n var listenerPrefix = redirectUri.GetLeftPart(UriPartial.Authority);\n if (!listenerPrefix.EndsWith(\"/\")) listenerPrefix += \"/\";\n\n using var listener = new HttpListener();\n listener.Prefixes.Add(listenerPrefix);\n\n try\n {\n listener.Start();\n Console.WriteLine($\"Listening for OAuth callback on: {listenerPrefix}\");\n\n OpenBrowser(authorizationUrl);\n\n var context = await listener.GetContextAsync();\n var query = HttpUtility.ParseQueryString(context.Request.Url?.Query ?? string.Empty);\n var code = query[\"code\"];\n var error = query[\"error\"];\n\n string responseHtml = \"

Authentication complete

You can close this window now.

\";\n byte[] buffer = Encoding.UTF8.GetBytes(responseHtml);\n context.Response.ContentLength64 = buffer.Length;\n context.Response.ContentType = \"text/html\";\n context.Response.OutputStream.Write(buffer, 0, buffer.Length);\n context.Response.Close();\n\n if (!string.IsNullOrEmpty(error))\n {\n Console.WriteLine($\"Auth error: {error}\");\n return null;\n }\n\n if (string.IsNullOrEmpty(code))\n {\n Console.WriteLine(\"No authorization code received\");\n return null;\n }\n\n Console.WriteLine(\"Authorization code received successfully.\");\n return code;\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error getting auth code: {ex.Message}\");\n return null;\n }\n finally\n {\n if (listener.IsListening) listener.Stop();\n }\n}\n\n/// \n/// Opens the specified URL in the default browser.\n/// \n/// The URL to open.\nstatic void OpenBrowser(Uri url)\n{\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = url.ToString(),\n UseShellExecute = true\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error opening browser. {ex.Message}\");\n Console.WriteLine($\"Please manually open this URL: {url}\");\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/AIContentExtensions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\n#if !NET\nusing System.Runtime.InteropServices;\n#endif\nusing System.Text.Json;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for converting between Model Context Protocol (MCP) types and Microsoft.Extensions.AI types.\n/// \n/// \n/// This class serves as an adapter layer between Model Context Protocol (MCP) types and the model types\n/// from the Microsoft.Extensions.AI namespace.\n/// \npublic static class AIContentExtensions\n{\n /// \n /// Converts a to a object.\n /// \n /// The prompt message to convert.\n /// A object created from the prompt message.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries.\n /// \n public static ChatMessage ToChatMessage(this PromptMessage promptMessage)\n {\n Throw.IfNull(promptMessage);\n\n AIContent? content = ToAIContent(promptMessage.Content);\n\n return new()\n {\n RawRepresentation = promptMessage,\n Role = promptMessage.Role == Role.User ? ChatRole.User : ChatRole.Assistant,\n Contents = content is not null ? [content] : [],\n };\n }\n\n /// \n /// Converts a to a object.\n /// \n /// The tool result to convert.\n /// The identifier for the function call request that triggered the tool invocation.\n /// A object created from the tool result.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries. It produces a\n /// message containing a with result as a\n /// serialized .\n /// \n public static ChatMessage ToChatMessage(this CallToolResult result, string callId)\n {\n Throw.IfNull(result);\n Throw.IfNull(callId);\n\n return new(ChatRole.Tool, [new FunctionResultContent(callId, JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult))\n {\n RawRepresentation = result,\n }]);\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The prompt result containing messages to convert.\n /// A list of objects created from the prompt messages.\n /// \n /// This method transforms protocol-specific objects from a Model Context Protocol\n /// prompt result into standard objects that can be used with AI client libraries.\n /// \n public static IList ToChatMessages(this GetPromptResult promptResult)\n {\n Throw.IfNull(promptResult);\n\n return promptResult.Messages.Select(m => m.ToChatMessage()).ToList();\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The chat message to convert.\n /// A list of objects created from the chat message's contents.\n /// \n /// This method transforms standard objects used with AI client libraries into\n /// protocol-specific objects for the Model Context Protocol system.\n /// Only representable content items are processed.\n /// \n public static IList ToPromptMessages(this ChatMessage chatMessage)\n {\n Throw.IfNull(chatMessage);\n\n Role r = chatMessage.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n List messages = [];\n foreach (var content in chatMessage.Contents)\n {\n if (content is TextContent or DataContent)\n {\n messages.Add(new PromptMessage { Role = r, Content = content.ToContent() });\n }\n }\n\n return messages;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// \n /// The created . If the content can't be converted (such as when it's a resource link), is returned.\n /// \n /// \n /// This method converts Model Context Protocol content types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent? ToAIContent(this ContentBlock content)\n {\n Throw.IfNull(content);\n\n AIContent? ac = content switch\n {\n TextContentBlock textContent => new TextContent(textContent.Text),\n ImageContentBlock imageContent => new DataContent(Convert.FromBase64String(imageContent.Data), imageContent.MimeType),\n AudioContentBlock audioContent => new DataContent(Convert.FromBase64String(audioContent.Data), audioContent.MimeType),\n EmbeddedResourceBlock resourceContent => resourceContent.Resource.ToAIContent(),\n _ => null,\n };\n\n if (ac is not null)\n {\n ac.RawRepresentation = content;\n }\n\n return ac;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// The created .\n /// \n /// This method converts Model Context Protocol resource types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent ToAIContent(this ResourceContents content)\n {\n Throw.IfNull(content);\n\n AIContent ac = content switch\n {\n BlobResourceContents blobResource => new DataContent(Convert.FromBase64String(blobResource.Blob), blobResource.MimeType ?? \"application/octet-stream\"),\n TextResourceContents textResource => new TextContent(textResource.Text),\n _ => throw new NotSupportedException($\"Resource type '{content.GetType().Name}' is not supported.\")\n };\n\n (ac.AdditionalProperties ??= [])[\"uri\"] = content.Uri;\n ac.RawRepresentation = content;\n\n return ac;\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// The created instances.\n /// \n /// \n /// This method converts a collection of Model Context Protocol content objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple content items, such as\n /// when processing the contents of a message or response.\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic for text, images, audio, and resources.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent).OfType()];\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// A list of objects created from the resource contents.\n /// \n /// \n /// This method converts a collection of Model Context Protocol resource objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple resources, such as\n /// when processing the contents of a .\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic: text resources become objects and\n /// binary resources become objects.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent)];\n }\n\n internal static ContentBlock ToContent(this AIContent content) =>\n content switch\n {\n TextContent textContent => new TextContentBlock\n {\n Text = textContent.Text,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") => new ImageContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"audio\") => new AudioContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent => new EmbeddedResourceBlock\n {\n Resource = new BlobResourceContents\n {\n Blob = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n }\n },\n\n _ => new TextContentBlock\n {\n Text = JsonSerializer.Serialize(content, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))),\n }\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContentBlock.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents content within the Model Context Protocol (MCP).\n/// \n/// \n/// \n/// The class is a fundamental type in the MCP that can represent different forms of content\n/// based on the property. Derived types like , ,\n/// and provide the type-specific content.\n/// \n/// \n/// This class is used throughout the MCP for representing content in messages, tool responses,\n/// and other communication between clients and servers.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\npublic abstract class ContentBlock\n{\n /// Prevent external derivations.\n private protected ContentBlock()\n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This determines the structure of the content object. Valid values include \"image\", \"audio\", \"text\", \"resource\", and \"resource_link\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Gets or sets optional annotations for the content.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the content. Clients can use this information to filter or prioritize content for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ContentBlock? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? text = null;\n string? name = null;\n string? data = null;\n string? mimeType = null;\n string? uri = null;\n string? description = null;\n long? size = null;\n ResourceContents? resource = null;\n Annotations? annotations = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"data\":\n data = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"size\":\n size = reader.GetInt64();\n break;\n\n case \"resource\":\n resource = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.ResourceContents);\n break;\n\n case \"annotations\":\n annotations = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.Annotations);\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n return type switch\n {\n \"text\" => new TextContentBlock\n {\n Text = text ?? throw new JsonException(\"Text contents must be provided for 'text' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"image\" => new ImageContentBlock\n {\n Data = data ?? throw new JsonException(\"Image data must be provided for 'image' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'image' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"audio\" => new AudioContentBlock\n {\n Data = data ?? throw new JsonException(\"Audio data must be provided for 'audio' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'audio' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource\" => new EmbeddedResourceBlock\n {\n Resource = resource ?? throw new JsonException(\"Resource contents must be provided for 'resource' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource_link\" => new ResourceLinkBlock\n {\n Uri = uri ?? throw new JsonException(\"URI must be provided for 'resource_link' type.\"),\n Name = name ?? throw new JsonException(\"Name must be provided for 'resource_link' type.\"),\n Description = description,\n MimeType = mimeType,\n Size = size,\n Annotations = annotations,\n },\n\n _ => throw new JsonException($\"Unknown content type: '{type}'\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case TextContentBlock textContent:\n writer.WriteString(\"text\", textContent.Text);\n if (textContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, textContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ImageContentBlock imageContent:\n writer.WriteString(\"data\", imageContent.Data);\n writer.WriteString(\"mimeType\", imageContent.MimeType);\n if (imageContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, imageContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case AudioContentBlock audioContent:\n writer.WriteString(\"data\", audioContent.Data);\n writer.WriteString(\"mimeType\", audioContent.MimeType);\n if (audioContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, audioContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case EmbeddedResourceBlock embeddedResource:\n writer.WritePropertyName(\"resource\");\n JsonSerializer.Serialize(writer, embeddedResource.Resource, McpJsonUtilities.JsonContext.Default.ResourceContents);\n if (embeddedResource.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, embeddedResource.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ResourceLinkBlock resourceLink:\n writer.WriteString(\"uri\", resourceLink.Uri);\n writer.WriteString(\"name\", resourceLink.Name);\n if (resourceLink.Description is not null)\n {\n writer.WriteString(\"description\", resourceLink.Description);\n }\n if (resourceLink.MimeType is not null)\n {\n writer.WriteString(\"mimeType\", resourceLink.MimeType);\n }\n if (resourceLink.Size.HasValue)\n {\n writer.WriteNumber(\"size\", resourceLink.Size.Value);\n }\n break;\n }\n\n if (value.Annotations is { } annotations)\n {\n writer.WritePropertyName(\"annotations\");\n JsonSerializer.Serialize(writer, annotations, McpJsonUtilities.JsonContext.Default.Annotations);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// Represents text provided to or from an LLM.\npublic sealed class TextContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public TextContentBlock() => Type = \"text\";\n\n /// \n /// Gets or sets the text content of the message.\n /// \n [JsonPropertyName(\"text\")]\n public required string Text { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents an image provided to or from an LLM.\npublic sealed class ImageContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ImageContentBlock() => Type = \"image\";\n\n /// \n /// Gets or sets the base64-encoded image data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"image/png\" and \"image/jpeg\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents audio provided to or from an LLM.\npublic sealed class AudioContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public AudioContentBlock() => Type = \"audio\";\n\n /// \n /// Gets or sets the base64-encoded audio data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"audio/wav\" and \"audio/mp3\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents the contents of a resource, embedded into a prompt or tool call result.\n/// \n/// It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user.\n/// \npublic sealed class EmbeddedResourceBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public EmbeddedResourceBlock() => Type = \"resource\";\n\n /// \n /// Gets or sets the resource content of the message when is \"resource\".\n /// \n /// \n /// \n /// Resources can be either text-based () or \n /// binary (), allowing for flexible data representation.\n /// Each resource has a URI that can be used for identification and retrieval.\n /// \n /// \n [JsonPropertyName(\"resource\")]\n public required ResourceContents Resource { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents a resource that the server is capable of reading, included in a prompt or tool call result.\n/// \n/// Resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n/// \npublic sealed class ResourceLinkBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ResourceLinkBlock() => Type = \"resource_link\";\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for this resource.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpEndpointExtensions.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class provides strongly-typed methods for working with the Model Context Protocol (MCP) endpoints,\n/// simplifying JSON-RPC communication by handling serialization and deserialization of parameters and results.\n/// \n/// \n/// These extension methods are designed to be used with both client () and\n/// server () implementations of the interface.\n/// \n/// \npublic static class McpEndpointExtensions\n{\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The request id for the request.\n /// The options governing request serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n public static ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo paramsTypeInfo = serializerOptions.GetTypeInfo();\n JsonTypeInfo resultTypeInfo = serializerOptions.GetTypeInfo();\n return SendRequestAsync(endpoint, method, parameters, paramsTypeInfo, resultTypeInfo, requestId, cancellationToken);\n }\n\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The type information for request parameter deserialization.\n /// The request id for the request.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n internal static async ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n JsonTypeInfo resultTypeInfo,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n Throw.IfNull(resultTypeInfo);\n\n JsonRpcRequest jsonRpcRequest = new()\n {\n Id = requestId,\n Method = method,\n Params = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo),\n };\n\n JsonRpcResponse response = await endpoint.SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.Deserialize(response.Result, resultTypeInfo) ?? throw new JsonException(\"Unexpected JSON result in response.\");\n }\n\n /// \n /// Sends a parameterless notification to the connected endpoint.\n /// \n /// The MCP client or server instance.\n /// The notification method name.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification without any parameters. Notifications are one-way messages \n /// that don't expect a response. They are commonly used for events, status updates, or to signal \n /// changes in state.\n /// \n /// \n public static Task SendNotificationAsync(this IMcpEndpoint client, string method, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(method);\n return client.SendMessageAsync(new JsonRpcNotification { Method = method }, cancellationToken);\n }\n\n /// \n /// Sends a notification with parameters to the connected endpoint.\n /// \n /// The type of the notification parameters to serialize.\n /// The MCP client or server instance.\n /// The JSON-RPC method name for the notification.\n /// Object representing the notification parameters.\n /// The options governing parameter serialization. If null, default options are used.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification with parameters to the connected endpoint. Notifications are one-way \n /// messages that don't expect a response, commonly used for events, status updates, or signaling changes.\n /// \n /// \n /// The parameters object is serialized to JSON according to the provided serializer options or the default \n /// options if none are specified.\n /// \n /// \n /// The Model Context Protocol defines several standard notification methods in ,\n /// but custom methods can also be used for application-specific notifications.\n /// \n /// \n public static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo parametersTypeInfo = serializerOptions.GetTypeInfo();\n return SendNotificationAsync(endpoint, method, parameters, parametersTypeInfo, cancellationToken);\n }\n\n /// \n /// Sends a notification to the server with parameters.\n /// \n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The to monitor for cancellation requests. The default is .\n internal static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n\n JsonNode? parametersJson = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo);\n return endpoint.SendMessageAsync(new JsonRpcNotification { Method = method, Params = parametersJson }, cancellationToken);\n }\n\n /// \n /// Notifies the connected endpoint of progress for a long-running operation.\n /// \n /// The endpoint issuing the notification.\n /// The identifying the operation for which progress is being reported.\n /// The progress update to send, containing information such as percentage complete or status message.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the completion of the notification operation (not the operation being tracked).\n /// is .\n /// \n /// \n /// This method sends a progress notification to the connected endpoint using the Model Context Protocol's\n /// standardized progress notification format. Progress updates are identified by a \n /// that allows the recipient to correlate multiple updates with a specific long-running operation.\n /// \n /// \n /// Progress notifications are sent asynchronously and don't block the operation from continuing.\n /// \n /// \n public static Task NotifyProgressAsync(\n this IMcpEndpoint endpoint,\n ProgressToken progressToken,\n ProgressNotificationValue progress, \n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n\n return endpoint.SendNotificationAsync(\n NotificationMethods.ProgressNotification,\n new ProgressNotificationParams\n {\n ProgressToken = progressToken,\n Progress = progress,\n },\n McpJsonUtilities.JsonContext.Default.ProgressNotificationParams,\n cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ProgressNotificationParams.cs", "using Microsoft.Extensions.Logging.Abstractions;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an out-of-band notification used to inform the receiver of a progress update for a long-running request.\n/// \n/// \n/// See the schema for more details.\n/// \n[JsonConverter(typeof(Converter))]\npublic sealed class ProgressNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the progress token which was given in the initial request, used to associate this notification with \n /// the corresponding request.\n /// \n /// \n /// \n /// This token acts as a correlation identifier that links progress updates to their corresponding request.\n /// \n /// \n /// When an endpoint initiates a request with a in its metadata, \n /// the receiver can send progress notifications using this same token. This allows both sides to \n /// correlate the notifications with the original request.\n /// \n /// \n public required ProgressToken ProgressToken { get; init; }\n\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// This should increase for each notification issued as part of the same request, even if the total is unknown.\n /// \n public required ProgressNotificationValue Progress { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressNotificationParams? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n ProgressToken? progressToken = null;\n float? progress = null;\n float? total = null;\n string? message = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType == JsonTokenType.PropertyName)\n {\n var propertyName = reader.GetString();\n reader.Read();\n switch (propertyName)\n {\n case \"progressToken\":\n progressToken = (ProgressToken)JsonSerializer.Deserialize(ref reader, options.GetTypeInfo(typeof(ProgressToken)))!;\n break;\n\n case \"progress\":\n progress = reader.GetSingle();\n break;\n\n case \"total\":\n total = reader.GetSingle();\n break;\n\n case \"message\":\n message = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n }\n }\n }\n\n if (progress is null)\n {\n throw new JsonException(\"Missing required property 'progress'.\");\n }\n\n if (progressToken is null)\n {\n throw new JsonException(\"Missing required property 'progressToken'.\");\n }\n\n return new ProgressNotificationParams\n {\n ProgressToken = progressToken.GetValueOrDefault(),\n Progress = new ProgressNotificationValue\n {\n Progress = progress.GetValueOrDefault(),\n Total = total,\n Message = message,\n },\n Meta = meta,\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressNotificationParams value, JsonSerializerOptions options)\n {\n writer.WriteStartObject();\n\n writer.WritePropertyName(\"progressToken\");\n JsonSerializer.Serialize(writer, value.ProgressToken, options.GetTypeInfo(typeof(ProgressToken)));\n\n writer.WriteNumber(\"progress\", value.Progress.Progress);\n\n if (value.Progress.Total is { } total)\n {\n writer.WriteNumber(\"total\", total);\n }\n\n if (value.Progress.Message is { } message)\n {\n writer.WriteString(\"message\", message);\n }\n\n if (value.Meta is { } meta)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceContents.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class representing contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// serves as the base class for different types of resources that can be \n/// exchanged through the Model Context Protocol. Resources are identified by URIs and can contain\n/// different types of data.\n/// \n/// \n/// This class is abstract and has two concrete implementations:\n/// \n/// - For text-based resources\n/// - For binary data resources\n/// \n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class ResourceContents\n{\n /// Prevent external derivations.\n private protected ResourceContents()\n {\n }\n\n /// \n /// Gets or sets the URI of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n public string Uri { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the MIME type of the resource content.\n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ResourceContents? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? uri = null;\n string? mimeType = null;\n string? blob = null;\n string? text = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"blob\":\n blob = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n if (blob is not null)\n {\n return new BlobResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Blob = blob,\n Meta = meta,\n };\n }\n\n if (text is not null)\n {\n return new TextResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Text = text,\n Meta = meta,\n };\n }\n\n return null;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ResourceContents value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n writer.WriteString(\"uri\", value.Uri);\n writer.WriteString(\"mimeType\", value.MimeType);\n \n Debug.Assert(value is BlobResourceContents or TextResourceContents);\n if (value is BlobResourceContents blobResource)\n {\n writer.WriteString(\"blob\", blobResource.Blob);\n }\n else if (value is TextResourceContents textResource)\n {\n writer.WriteString(\"text\", textResource.Text);\n }\n\n if (value.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, value.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\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.Core/Protocol/ElicitRequestParams.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued from the server to elicit additional information from the user via the client.\n/// \npublic sealed class ElicitRequestParams\n{\n /// \n /// Gets or sets the message to present to the user.\n /// \n [JsonPropertyName(\"message\")]\n public string Message { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the requested schema.\n /// \n /// \n /// May be one of , , , or .\n /// \n [JsonPropertyName(\"requestedSchema\")]\n [field: MaybeNull]\n public RequestSchema RequestedSchema\n {\n get => field ??= new RequestSchema();\n set => field = value;\n }\n\n /// Represents a request schema used in an elicitation request.\n public class RequestSchema\n {\n /// Gets the type of the schema.\n /// This is always \"object\".\n [JsonPropertyName(\"type\")]\n public string Type => \"object\";\n\n /// Gets or sets the properties of the schema.\n [JsonPropertyName(\"properties\")]\n [field: MaybeNull]\n public IDictionary Properties\n {\n get => field ??= new Dictionary();\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets the required properties of the schema.\n [JsonPropertyName(\"required\")]\n public IList? Required { get; set; }\n }\n\n /// \n /// Represents restricted subset of JSON Schema: \n /// , , , or .\n /// \n [JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n public abstract class PrimitiveSchemaDefinition\n {\n /// Prevent external derivations.\n protected private PrimitiveSchemaDefinition()\n {\n }\n\n /// Gets the type of the schema.\n [JsonPropertyName(\"type\")]\n public abstract string Type { get; set; }\n\n /// Gets or sets a title for the schema.\n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// Gets or sets a description for the schema.\n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override PrimitiveSchemaDefinition? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? title = null;\n string? description = null;\n int? minLength = null;\n int? maxLength = null;\n string? format = null;\n double? minimum = null;\n double? maximum = null;\n bool? defaultBool = null;\n IList? enumValues = null;\n IList? enumNames = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"title\":\n title = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"minLength\":\n minLength = reader.GetInt32();\n break;\n\n case \"maxLength\":\n maxLength = reader.GetInt32();\n break;\n\n case \"format\":\n format = reader.GetString();\n break;\n\n case \"minimum\":\n minimum = reader.GetDouble();\n break;\n\n case \"maximum\":\n maximum = reader.GetDouble();\n break;\n\n case \"default\":\n defaultBool = reader.GetBoolean();\n break;\n\n case \"enum\":\n enumValues = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n case \"enumNames\":\n enumNames = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n default:\n break;\n }\n }\n\n if (type is null)\n {\n throw new JsonException(\"The 'type' property is required.\");\n }\n\n PrimitiveSchemaDefinition? psd = null;\n switch (type)\n {\n case \"string\":\n if (enumValues is not null)\n {\n psd = new EnumSchema\n {\n Enum = enumValues,\n EnumNames = enumNames\n };\n }\n else\n {\n psd = new StringSchema\n {\n MinLength = minLength,\n MaxLength = maxLength,\n Format = format,\n };\n }\n break;\n\n case \"integer\":\n case \"number\":\n psd = new NumberSchema\n {\n Minimum = minimum,\n Maximum = maximum,\n };\n break;\n\n case \"boolean\":\n psd = new BooleanSchema\n {\n Default = defaultBool,\n };\n break;\n }\n\n if (psd is not null)\n {\n psd.Type = type;\n psd.Title = title;\n psd.Description = description;\n }\n\n return psd;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, PrimitiveSchemaDefinition value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n if (value.Title is not null)\n {\n writer.WriteString(\"title\", value.Title);\n }\n if (value.Description is not null)\n {\n writer.WriteString(\"description\", value.Description);\n }\n\n switch (value)\n {\n case StringSchema stringSchema:\n if (stringSchema.MinLength.HasValue)\n {\n writer.WriteNumber(\"minLength\", stringSchema.MinLength.Value);\n }\n if (stringSchema.MaxLength.HasValue)\n {\n writer.WriteNumber(\"maxLength\", stringSchema.MaxLength.Value);\n }\n if (stringSchema.Format is not null)\n {\n writer.WriteString(\"format\", stringSchema.Format);\n }\n break;\n\n case NumberSchema numberSchema:\n if (numberSchema.Minimum.HasValue)\n {\n writer.WriteNumber(\"minimum\", numberSchema.Minimum.Value);\n }\n if (numberSchema.Maximum.HasValue)\n {\n writer.WriteNumber(\"maximum\", numberSchema.Maximum.Value);\n }\n break;\n\n case BooleanSchema booleanSchema:\n if (booleanSchema.Default.HasValue)\n {\n writer.WriteBoolean(\"default\", booleanSchema.Default.Value);\n }\n break;\n\n case EnumSchema enumSchema:\n if (enumSchema.Enum is not null)\n {\n writer.WritePropertyName(\"enum\");\n JsonSerializer.Serialize(writer, enumSchema.Enum, McpJsonUtilities.JsonContext.Default.IListString);\n }\n if (enumSchema.EnumNames is not null)\n {\n writer.WritePropertyName(\"enumNames\");\n JsonSerializer.Serialize(writer, enumSchema.EnumNames, McpJsonUtilities.JsonContext.Default.IListString);\n }\n break;\n\n default:\n throw new JsonException($\"Unexpected schema type: {value.GetType().Name}\");\n }\n\n writer.WriteEndObject();\n }\n }\n }\n\n /// Represents a schema for a string type.\n public sealed class StringSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the minimum length for the string.\n [JsonPropertyName(\"minLength\")]\n public int? MinLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Minimum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the maximum length for the string.\n [JsonPropertyName(\"maxLength\")]\n public int? MaxLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Maximum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets a specific format for the string (\"email\", \"uri\", \"date\", or \"date-time\").\n [JsonPropertyName(\"format\")]\n public string? Format\n {\n get => field;\n set\n {\n if (value is not (null or \"email\" or \"uri\" or \"date\" or \"date-time\"))\n {\n throw new ArgumentException(\"Format must be 'email', 'uri', 'date', or 'date-time'.\", nameof(value));\n }\n\n field = value;\n }\n }\n }\n\n /// Represents a schema for a number or integer type.\n public sealed class NumberSchema : PrimitiveSchemaDefinition\n {\n /// \n [field: MaybeNull]\n public override string Type\n {\n get => field ??= \"number\";\n set\n {\n if (value is not (\"number\" or \"integer\"))\n {\n throw new ArgumentException(\"Type must be 'number' or 'integer'.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the minimum allowed value.\n [JsonPropertyName(\"minimum\")]\n public double? Minimum { get; set; }\n\n /// Gets or sets the maximum allowed value.\n [JsonPropertyName(\"maximum\")]\n public double? Maximum { get; set; }\n }\n\n /// Represents a schema for a Boolean type.\n public sealed class BooleanSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"boolean\";\n set\n {\n if (value is not \"boolean\")\n {\n throw new ArgumentException(\"Type must be 'boolean'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the default value for the Boolean.\n [JsonPropertyName(\"default\")]\n public bool? Default { get; set; }\n }\n\n /// Represents a schema for an enum type.\n public sealed class EnumSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the list of allowed string values for the enum.\n [JsonPropertyName(\"enum\")]\n [field: MaybeNull]\n public IList Enum\n {\n get => field ??= [];\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets optional display names corresponding to the enum values.\n [JsonPropertyName(\"enumNames\")]\n public IList? EnumNames { get; set; }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/RequestHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\ninternal sealed class RequestHandlers : Dictionary>>\n{\n /// \n /// Registers a handler for incoming requests of a specific method in the MCP protocol.\n /// \n /// Type of request payload that will be deserialized from incoming JSON\n /// Type of response payload that will be serialized to JSON (not full RPC response)\n /// Method identifier to register for (e.g., \"tools/list\", \"logging/setLevel\")\n /// Handler function to be called when a request with the specified method identifier is received\n /// The JSON contract governing request parameter deserialization\n /// The JSON contract governing response serialization\n /// \n /// \n /// This method is used internally by the MCP infrastructure to register handlers for various protocol methods.\n /// When an incoming request matches the specified method, the registered handler will be invoked with the\n /// deserialized request parameters.\n /// \n /// \n /// The handler function receives the deserialized request object and a cancellation token, and should return\n /// a response object that will be serialized back to the client.\n /// \n /// \n public void Set(\n string method,\n Func> handler,\n JsonTypeInfo requestTypeInfo,\n JsonTypeInfo responseTypeInfo)\n {\n Throw.IfNull(method);\n Throw.IfNull(handler);\n Throw.IfNull(requestTypeInfo);\n Throw.IfNull(responseTypeInfo);\n\n this[method] = async (request, cancellationToken) =>\n {\n TRequest? typedRequest = JsonSerializer.Deserialize(request.Params, requestTypeInfo);\n object? result = await handler(typedRequest, request.RelatedTransport, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToNode(result, responseTypeInfo);\n };\n }\n}\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/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/NotificationHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol;\n\n/// Provides thread-safe storage for notification handlers.\ninternal sealed class NotificationHandlers\n{\n /// A dictionary of linked lists of registrations, indexed by the notification method.\n private readonly Dictionary _handlers = [];\n\n /// Gets the object to be used for all synchronization.\n private object SyncObj => _handlers;\n\n /// \n /// Registers a collection of notification handlers at once.\n /// \n /// \n /// A collection of notification method names paired with their corresponding handler functions.\n /// Each key in the collection is a notification method name, and each value is a handler function\n /// that will be invoked when a notification with that method name is received.\n /// \n /// \n /// \n /// This method is typically used during client or server initialization to register\n /// all notification handlers provided in capabilities.\n /// \n /// \n /// Registrations completed with this method are permanent and non-removable.\n /// This differs from handlers registered with which can be temporary.\n /// \n /// \n /// When multiple handlers are registered for the same method, all handlers will be invoked\n /// in reverse order of registration (newest first) when a notification is received.\n /// \n /// \n /// The registered handlers will be invoked by when a notification\n /// with the corresponding method name is received.\n /// \n /// \n public void RegisterRange(IEnumerable>> handlers)\n {\n foreach (var entry in handlers)\n {\n _ = Register(entry.Key, entry.Value, temporary: false);\n }\n }\n\n /// \n /// Adds a notification handler as part of configuring the endpoint.\n /// \n /// The notification method for which the handler is being registered.\n /// The handler being registered.\n /// \n /// if the registration can be removed later; if it cannot.\n /// If , the registration will be permanent: calling \n /// on the returned instance will not unregister the handler.\n /// \n /// \n /// An that when disposed will unregister the handler if is .\n /// \n /// \n /// Multiple handlers can be registered for the same method. When a notification for that method is received,\n /// all registered handlers will be invoked in reverse order of registration (newest first).\n /// \n public IAsyncDisposable Register(\n string method, Func handler, bool temporary = true)\n {\n // Create the new registration instance.\n Registration reg = new(this, method, handler, temporary);\n\n // Store the registration into the dictionary. If there's not currently a registration for the method,\n // then this registration instance just becomes the single value. If there is currently a registration,\n // then this new registration becomes the new head of the linked list, and the old head becomes the next\n // item in the list.\n lock (SyncObj)\n {\n if (_handlers.TryGetValue(method, out var existingHandlerHead))\n {\n reg.Next = existingHandlerHead;\n existingHandlerHead.Prev = reg;\n }\n\n _handlers[method] = reg;\n }\n\n // Return the new registration. It must be disposed of when no longer used, or it will end up being\n // leaked into the list. This is the same as with CancellationToken.Register.\n return reg;\n }\n\n /// \n /// Invokes all registered handlers for the specified notification method.\n /// \n /// The notification method name to invoke handlers for.\n /// The notification object to pass to each handler.\n /// A token that can be used to cancel the operation.\n /// \n /// Handlers are invoked in reverse order of registration (newest first).\n /// If any handler throws an exception, all handlers will still be invoked, and an \n /// containing all exceptions will be thrown after all handlers have been invoked.\n /// \n public async Task InvokeHandlers(string method, JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // If there are no handlers registered for this method, we're done.\n Registration? reg;\n lock (SyncObj)\n {\n if (!_handlers.TryGetValue(method, out reg))\n {\n return;\n }\n }\n\n // Invoke each handler in the list. We guarantee that we'll try to invoke\n // any handlers that were in the list when the list was fetched from the dictionary,\n // which is why DisposeAsync doesn't modify the Prev/Next of the registration being\n // disposed; if those were nulled out, we'd be unable to walk around it in the list\n // if we happened to be on that item when it was disposed.\n List? exceptions = null;\n while (reg is not null)\n {\n try\n {\n await reg.InvokeAsync(notification, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e)\n {\n (exceptions ??= []).Add(e);\n }\n\n lock (SyncObj)\n {\n reg = reg.Next;\n }\n }\n\n if (exceptions is not null)\n {\n throw new AggregateException(exceptions);\n }\n }\n\n /// Provides storage for a handler registration.\n private sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable) : IAsyncDisposable\n {\n /// Used to prevent deadlocks during disposal.\n /// \n /// The task returned from does not complete until all invocations of the handler\n /// have completed and no more will be performed, so that the consumer can then trust that any resources accessed\n /// by that handler are no longer in use and may be cleaned up. If were to be invoked\n /// and its task awaited from within the invocation of the handler, however, that would result in deadlock, since\n /// the task wouldn't complete until the invocation completed, and the invocation wouldn't complete until the task\n /// completed. To circument that, we track via an in-flight invocations. If\n /// detects it's being invoked from within an invocation, it will avoid waiting. For\n /// simplicity, we don't require that it's the same handler.\n /// \n private static readonly AsyncLocal s_invokingAncestor = new();\n\n /// The parent to which this registration belongs.\n private readonly NotificationHandlers _handlers = handlers;\n\n /// The method with which this registration is associated.\n private readonly string _method = method;\n \n /// The handler this registration represents.\n private readonly Func _handler = handler;\n\n /// true if this instance is temporary; false if it's permanent\n private readonly bool _temporary = unregisterable;\n\n /// Provides a task that can await to know when all in-flight invocations have completed.\n /// \n /// This will only be initialized if sees in-flight invocations, in which case it'll initialize\n /// this and then await its task. The task will be completed when the last\n /// in-flight notification completes.\n /// \n private TaskCompletionSource? _disposeTcs;\n \n /// The number of remaining references to this registration.\n /// \n /// The ref count starts life at 1 to represent the whole registration; that ref count will be subtracted when\n /// the instance is disposed. Every invocation then temporarily increases the ref count before invocation and\n /// decrements it after. When is called, it decrements the ref count. In the common\n /// case, that'll bring the count down to 0, in which case the instance will never be subsequently invoked.\n /// If, however, after that decrement the count is still positive, then there are in-flight invocations; the last\n /// one of those to complete will end up decrementing the ref count to 0.\n /// \n private int _refCount = 1;\n\n /// Tracks whether has ever been invoked.\n /// \n /// It's rare but possible is called multiple times. Only the first\n /// should decrement the initial ref count, but they all must wait until all invocations have quiesced.\n /// \n private bool _disposedCalled = false;\n\n /// The next registration in the linked list.\n public Registration? Next;\n /// \n /// The previous registration in the linked list of handlers for a specific notification method.\n /// Used to maintain the bidirectional linked list when handlers are added or removed.\n /// \n public Registration? Prev;\n\n /// Removes the registration.\n public async ValueTask DisposeAsync()\n {\n if (!_temporary)\n {\n return;\n }\n\n lock (_handlers.SyncObj)\n {\n // If DisposeAsync was previously called, we don't want to do all of the work again\n // to remove the registration from the list, and we must not do the work again to\n // decrement the ref count and possibly initialize the _disposeTcs.\n if (!_disposedCalled)\n {\n _disposedCalled = true;\n\n // If this handler is the head of the list for this method, we need to update\n // the dictionary, either to point to a different head, or if this is the only\n // item in the list, to remove the entry from the dictionary entirely.\n if (_handlers._handlers.TryGetValue(_method, out var handlers) && handlers == this)\n {\n if (Next is not null)\n {\n _handlers._handlers[_method] = Next;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n\n // Remove the registration from the linked list by routing the nodes around it\n // to point past this one. Importantly, we do not modify this node's Next or Prev.\n // We want to ensure that an enumeration through all of the registrations can still\n // progress through this one.\n if (Prev is not null)\n {\n Prev.Next = Next;\n }\n if (Next is not null)\n {\n Next.Prev = Prev;\n }\n\n // Decrement the ref count. In the common case, there's no in-flight invocation for\n // this handler. However, in the uncommon case that there is, we need to wait for\n // that invocation to complete. To do that, initialize the _disposeTcs. It's created\n // with RunContinuationsAsynchronously so that completing it doesn't run the continuation\n // under any held locks.\n if (--_refCount != 0)\n {\n Debug.Assert(_disposeTcs is null);\n _disposeTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);\n }\n }\n }\n\n // Ensure that DisposeAsync doesn't complete until all in-flight invocations have completed,\n // unless our call chain includes one of those in-flight invocations, in which case waiting\n // would deadlock.\n if (_disposeTcs is not null && s_invokingAncestor.Value == 0)\n {\n await _disposeTcs.Task.ConfigureAwait(false);\n }\n }\n\n /// Invoke the handler associated with the registration.\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // For permanent registrations, skip all the tracking overhead and just invoke the handler.\n if (!_temporary)\n {\n return _handler(notification, cancellationToken);\n }\n\n // For temporary registrations, track the invocation and coordinate with disposal.\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n\n /// Invoke the handler associated with the temporary registration.\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // Check whether we need to handle this registration. If DisposeAsync has been called,\n // then even if there are in-flight invocations for it, we avoid adding more.\n // If DisposeAsync has not been called, then we need to increment the ref count to\n // signal that there's another in-flight invocation.\n lock (_handlers.SyncObj)\n {\n Debug.Assert(_refCount != 0 || _disposedCalled, $\"Expected {nameof(_disposedCalled)} == true when {nameof(_refCount)} == 0\");\n if (_disposedCalled)\n {\n return;\n }\n\n Debug.Assert(_refCount > 0);\n _refCount++;\n }\n\n // Ensure that if DisposeAsync is called from within the handler, it won't deadlock by waiting\n // for the in-flight invocation to complete.\n s_invokingAncestor.Value++;\n\n try\n {\n // Invoke the handler.\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n // Undo the in-flight tracking.\n s_invokingAncestor.Value--;\n\n // Now decrement the ref count we previously incremented. If that brings the ref count to 0,\n // DisposeAsync must have been called while this was in-flight, which also means it's now\n // waiting on _disposeTcs; unblock it.\n lock (_handlers.SyncObj)\n {\n _refCount--;\n if (_refCount == 0)\n {\n Debug.Assert(_disposedCalled);\n Debug.Assert(_disposeTcs is not null);\n bool completed = _disposeTcs!.TrySetResult(true);\n Debug.Assert(completed);\n }\n }\n }\n }\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer server,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await server.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses depenency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await thisServer.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationHandler.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Authentication;\nusing System.Text.Encodings.Web;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Authentication handler for MCP protocol that adds resource metadata to challenge responses\n/// and handles resource metadata endpoint requests.\n/// \npublic class McpAuthenticationHandler : AuthenticationHandler, IAuthenticationRequestHandler\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationHandler(\n IOptionsMonitor options,\n ILoggerFactory logger,\n UrlEncoder encoder)\n : base(options, logger, encoder)\n {\n }\n\n /// \n public async Task HandleRequestAsync()\n {\n // Check if the request is for the resource metadata endpoint\n string requestPath = Request.Path.Value ?? string.Empty;\n\n string expectedMetadataPath = Options.ResourceMetadataUri?.ToString() ?? string.Empty;\n if (Options.ResourceMetadataUri != null && !Options.ResourceMetadataUri.IsAbsoluteUri)\n {\n // For relative URIs, it's just the path component.\n expectedMetadataPath = Options.ResourceMetadataUri.OriginalString;\n }\n\n // If the path doesn't match, let the request continue through the pipeline\n if (!string.Equals(requestPath, expectedMetadataPath, StringComparison.OrdinalIgnoreCase))\n {\n return false;\n }\n\n return await HandleResourceMetadataRequestAsync();\n }\n\n /// \n /// Gets the base URL from the current request, including scheme, host, and path base.\n /// \n private string GetBaseUrl() => $\"{Request.Scheme}://{Request.Host}{Request.PathBase}\";\n\n /// \n /// Gets the absolute URI for the resource metadata endpoint.\n /// \n private string GetAbsoluteResourceMetadataUri()\n {\n var resourceMetadataUri = Options.ResourceMetadataUri;\n\n string currentPath = resourceMetadataUri?.ToString() ?? string.Empty;\n\n if (resourceMetadataUri != null && resourceMetadataUri.IsAbsoluteUri)\n {\n return currentPath;\n }\n\n // For relative URIs, combine with the base URL\n string baseUrl = GetBaseUrl();\n string relativePath = resourceMetadataUri?.OriginalString.TrimStart('/') ?? string.Empty;\n\n if (!Uri.TryCreate($\"{baseUrl.TrimEnd('/')}/{relativePath}\", UriKind.Absolute, out var absoluteUri))\n {\n throw new InvalidOperationException($\"Could not create absolute URI for resource metadata. Base URL: {baseUrl}, Relative Path: {relativePath}\");\n }\n\n return absoluteUri.ToString();\n }\n\n private async Task HandleResourceMetadataRequestAsync()\n {\n var resourceMetadata = Options.ResourceMetadata;\n\n if (Options.Events.OnResourceMetadataRequest is not null)\n {\n var context = new ResourceMetadataRequestContext(Request.HttpContext, Scheme, Options)\n {\n ResourceMetadata = CloneResourceMetadata(resourceMetadata),\n };\n\n await Options.Events.OnResourceMetadataRequest(context);\n\n if (context.Result is not null)\n {\n if (context.Result.Handled)\n {\n return true;\n }\n else if (context.Result.Skipped)\n {\n return false;\n }\n else if (context.Result.Failure is not null)\n {\n throw new AuthenticationFailureException(\"An error occurred from the OnResourceMetadataRequest event.\", context.Result.Failure);\n }\n }\n\n resourceMetadata = context.ResourceMetadata;\n }\n\n if (resourceMetadata == null)\n {\n throw new InvalidOperationException(\n \"ResourceMetadata has not been configured. Please set McpAuthenticationOptions.ResourceMetadata or ensure context.ResourceMetadata is set inside McpAuthenticationOptions.Events.OnResourceMetadataRequest.\"\n );\n }\n\n await Results.Json(resourceMetadata, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ProtectedResourceMetadata))).ExecuteAsync(Context);\n return true;\n }\n\n /// \n // If no forwarding is configured, this handler doesn't perform authentication\n protected override async Task HandleAuthenticateAsync() => AuthenticateResult.NoResult();\n\n /// \n protected override Task HandleChallengeAsync(AuthenticationProperties properties)\n {\n // Get the absolute URI for the resource metadata\n string rawPrmDocumentUri = GetAbsoluteResourceMetadataUri();\n\n properties ??= new AuthenticationProperties();\n\n // Store the resource_metadata in properties in case other handlers need it\n properties.Items[\"resource_metadata\"] = rawPrmDocumentUri;\n\n // Add the WWW-Authenticate header with Bearer scheme and resource metadata\n string headerValue = $\"Bearer realm=\\\"{Scheme.Name}\\\", resource_metadata=\\\"{rawPrmDocumentUri}\\\"\";\n Response.Headers.Append(\"WWW-Authenticate\", headerValue);\n\n return base.HandleChallengeAsync(properties);\n }\n\n internal static ProtectedResourceMetadata? CloneResourceMetadata(ProtectedResourceMetadata? resourceMetadata)\n {\n if (resourceMetadata is null)\n {\n return null;\n }\n\n return new ProtectedResourceMetadata\n {\n Resource = resourceMetadata.Resource,\n AuthorizationServers = [.. resourceMetadata.AuthorizationServers],\n BearerMethodsSupported = [.. resourceMetadata.BearerMethodsSupported],\n ScopesSupported = [.. resourceMetadata.ScopesSupported],\n JwksUri = resourceMetadata.JwksUri,\n ResourceSigningAlgValuesSupported = resourceMetadata.ResourceSigningAlgValuesSupported is not null ? [.. resourceMetadata.ResourceSigningAlgValuesSupported] : null,\n ResourceName = resourceMetadata.ResourceName,\n ResourceDocumentation = resourceMetadata.ResourceDocumentation,\n ResourcePolicyUri = resourceMetadata.ResourcePolicyUri,\n ResourceTosUri = resourceMetadata.ResourceTosUri,\n TlsClientCertificateBoundAccessTokens = resourceMetadata.TlsClientCertificateBoundAccessTokens,\n AuthorizationDetailsTypesSupported = resourceMetadata.AuthorizationDetailsTypesSupported is not null ? [.. resourceMetadata.AuthorizationDetailsTypesSupported] : null,\n DpopSigningAlgValuesSupported = resourceMetadata.DpopSigningAlgValuesSupported is not null ? [.. resourceMetadata.DpopSigningAlgValuesSupported] : null,\n DpopBoundAccessTokensRequired = resourceMetadata.DpopBoundAccessTokensRequired\n };\n }\n\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/McpEndpointRouteBuilderExtensions.cs", "using Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Metadata;\nusing Microsoft.AspNetCore.Routing;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.AspNetCore.Builder;\n\n/// \n/// Provides extension methods for to add MCP endpoints.\n/// \npublic static class McpEndpointRouteBuilderExtensions\n{\n /// \n /// Sets up endpoints for handling MCP Streamable HTTP transport.\n /// See the 2025-06-18 protocol specification for details about the Streamable HTTP transport.\n /// Also maps legacy SSE endpoints for backward compatibility at the path \"/sse\" and \"/message\". the 2024-11-05 protocol specification for details about the HTTP with SSE transport.\n /// \n /// The web application to attach MCP HTTP endpoints.\n /// The route pattern prefix to map to.\n /// Returns a builder for configuring additional endpoint conventions like authorization policies.\n public static IEndpointConventionBuilder MapMcp(this IEndpointRouteBuilder endpoints, [StringSyntax(\"Route\")] string pattern = \"\")\n {\n var streamableHttpHandler = endpoints.ServiceProvider.GetService() ??\n throw new InvalidOperationException(\"You must call WithHttpTransport(). Unable to find required services. Call builder.Services.AddMcpServer().WithHttpTransport() in application startup code.\");\n\n var mcpGroup = endpoints.MapGroup(pattern);\n var streamableHttpGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP Streamable HTTP | {b.DisplayName}\")\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status404NotFound, typeof(JsonRpcError), contentTypes: [\"application/json\"]));\n\n streamableHttpGroup.MapPost(\"\", streamableHttpHandler.HandlePostRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n\n if (!streamableHttpHandler.HttpServerTransportOptions.Stateless)\n {\n // The GET and DELETE endpoints are not mapped in Stateless mode since there's no way to send unsolicited messages\n // for the GET to handle, and there is no server-side state for the DELETE to clean up.\n streamableHttpGroup.MapGet(\"\", streamableHttpHandler.HandleGetRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n streamableHttpGroup.MapDelete(\"\", streamableHttpHandler.HandleDeleteRequestAsync);\n\n // Map legacy HTTP with SSE endpoints only if not in Stateless mode, because we cannot guarantee the /message requests\n // will be handled by the same process as the /sse request.\n var sseHandler = endpoints.ServiceProvider.GetRequiredService();\n var sseGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP HTTP with SSE | {b.DisplayName}\");\n\n sseGroup.MapGet(\"/sse\", sseHandler.HandleSseRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n sseGroup.MapPost(\"/message\", sseHandler.HandleMessageRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n }\n\n return mcpGroup;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/UriTemplate.cs", "#if NET\nusing System.Buffers;\n#endif\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol;\n\n/// Provides basic support for parsing and formatting URI templates.\n/// \n/// This implementation should correctly handle valid URI templates, but it has undefined output for invalid templates,\n/// e.g. it may treat portions of invalid templates as literals rather than throwing.\n/// \ninternal static partial class UriTemplate\n{\n /// Regex pattern for finding URI template expressions and parsing out the operator and varname.\n private const string UriTemplateExpressionPattern = \"\"\"\n { # opening brace\n (?[+#./;?&]?) # optional operator\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}) # varchar: letter, digit, underscore, or pct-encoded\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))* # optionally dot-separated subsequent varchars\n )\n (?: :[1-9][0-9]{0,3} )? # optional prefix modifier (1–4 digits)\n \\*? # optional explode\n (?:, # comma separator, followed by the same as above\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*\n )\n (?: :[1-9][0-9]{0,3} )?\n \\*?\n )* # zero or more additional vars\n } # closing brace\n \"\"\";\n\n /// Gets a regex for finding URI template expressions and parsing out the operator and varname.\n /// \n /// This regex is for parsing a static URI template.\n /// It is not for parsing a URI according to a template.\n /// \n#if NET\n [GeneratedRegex(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace)]\n private static partial Regex UriTemplateExpression();\n#else\n private static Regex UriTemplateExpression() => s_uriTemplateExpression;\n private static readonly Regex s_uriTemplateExpression = new(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n#endif\n\n#if NET\n /// SearchValues for characters that needn't be escaped when allowing reserved characters.\n private static readonly SearchValues s_appendWhenAllowReserved = SearchValues.Create(\n \"abcdefghijklmnopqrstuvwxyz\" + // ASCII lowercase letters\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" + // ASCII uppercase letters\n \"0123456789\" + // ASCII digits\n \"-._~\" + // unreserved characters\n \":/?#[]@!$&'()*+,;=\"); // reserved characters\n#endif\n\n /// Create a for matching a URI against a URI template.\n /// The template against which to match.\n /// A regex pattern that can be used to match the specified URI template.\n public static Regex CreateParser(string uriTemplate)\n {\n DefaultInterpolatedStringHandler pattern = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n pattern.AppendFormatted('^');\n\n int lastIndex = 0;\n for (Match m = UriTemplateExpression().Match(uriTemplate); m.Success; m = m.NextMatch())\n {\n pattern.AppendFormatted(Regex.Escape(uriTemplate[lastIndex..m.Index]));\n lastIndex = m.Index + m.Length;\n\n var captures = m.Groups[\"varname\"].Captures;\n List paramNames = new(captures.Count);\n foreach (Capture c in captures)\n {\n paramNames.Add(c.Value);\n }\n\n switch (m.Groups[\"operator\"].Value)\n {\n case \"#\": AppendExpression(ref pattern, paramNames, '#', \"[^,]+\"); break;\n case \"/\": AppendExpression(ref pattern, paramNames, '/', \"[^/?]+\"); break;\n default: AppendExpression(ref pattern, paramNames, null, \"[^/?&]+\"); break;\n \n case \"?\": AppendQueryExpression(ref pattern, paramNames, '?'); break;\n case \"&\": AppendQueryExpression(ref pattern, paramNames, '&'); break;\n }\n }\n\n pattern.AppendFormatted(Regex.Escape(uriTemplate.Substring(lastIndex)));\n pattern.AppendFormatted('$');\n\n return new Regex(\n pattern.ToStringAndClear(),\n RegexOptions.IgnoreCase | RegexOptions.CultureInvariant |\n#if NET\n RegexOptions.NonBacktracking);\n#else\n RegexOptions.Compiled, TimeSpan.FromSeconds(10));\n#endif\n\n // Appends a regex fragment to `pattern` that matches an optional query string starting\n // with the given `prefix` (? or &), and up to one occurrence of each name in\n // `paramNames`. Each parameter is made optional and captured by a named group\n // of the form “paramName=value”.\n static void AppendQueryExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char prefix)\n {\n Debug.Assert(prefix is '?' or '&');\n\n pattern.AppendFormatted(\"(?:\\\\\");\n pattern.AppendFormatted(prefix);\n\n if (paramNames.Count > 0)\n {\n AppendParameter(ref pattern, paramNames[0]);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\&?\");\n AppendParameter(ref pattern, paramNames[i]);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName)\n {\n paramName = Regex.Escape(paramName);\n pattern.AppendFormatted(\"(?:\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\"=(?<\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\">[^/?&]+))?\");\n }\n }\n\n pattern.AppendFormatted(\")?\");\n }\n\n // Chooses a regex character‐class (`valueChars`) based on the initial `prefix` to define which\n // characters make up a parameter value. Then, for each name in `paramNames`, it optionally\n // appends the escaped `prefix` (only on the first parameter, then switches to ','), and\n // adds an optional named capture group `(?valueChars)` to match and capture that value.\n static void AppendExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char? prefix, string valueChars)\n {\n Debug.Assert(prefix is '#' or '/' or null);\n\n if (paramNames.Count > 0)\n {\n if (prefix is not null)\n {\n pattern.AppendFormatted('\\\\');\n pattern.AppendFormatted(prefix);\n pattern.AppendFormatted('?');\n }\n\n AppendParameter(ref pattern, paramNames[0], valueChars);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\,?\");\n AppendParameter(ref pattern, paramNames[i], valueChars);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName, string valueChars)\n {\n pattern.AppendFormatted(\"(?<\");\n pattern.AppendFormatted(Regex.Escape(paramName));\n pattern.AppendFormatted('>');\n pattern.AppendFormatted(valueChars);\n pattern.AppendFormatted(\")?\");\n }\n }\n }\n }\n\n /// \n /// Expand a URI template using the given variable values.\n /// \n public static string FormatUri(string uriTemplate, IReadOnlyDictionary arguments)\n {\n Throw.IfNull(uriTemplate);\n\n ReadOnlySpan uriTemplateSpan = uriTemplate.AsSpan();\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n while (!uriTemplateSpan.IsEmpty)\n {\n // Find the next expression.\n int openBracePos = uriTemplateSpan.IndexOf('{');\n if (openBracePos < 0)\n {\n if (uriTemplate.Length == uriTemplateSpan.Length)\n {\n return uriTemplate;\n }\n\n builder.AppendFormatted(uriTemplateSpan);\n break;\n }\n\n // Append as a literal everything before the next expression.\n builder.AppendFormatted(uriTemplateSpan.Slice(0, openBracePos));\n uriTemplateSpan = uriTemplateSpan.Slice(openBracePos + 1);\n\n int closeBracePos = uriTemplateSpan.IndexOf('}');\n if (closeBracePos < 0)\n {\n throw new FormatException($\"Unmatched '{{' in URI template '{uriTemplate}'\");\n }\n\n ReadOnlySpan expression = uriTemplateSpan.Slice(0, closeBracePos);\n uriTemplateSpan = uriTemplateSpan.Slice(closeBracePos + 1);\n if (expression.IsEmpty)\n {\n continue;\n }\n\n // The start of the expression may be a modifier; if it is, slice it off the expression.\n char modifier = expression[0];\n (string Prefix, string Separator, bool Named, bool IncludeNameIfEmpty, bool IncludeSeparatorIfEmpty, bool AllowReserved, bool PrefixEmptyExpansions, int ExpressionSlice) modifierBehavior = modifier switch\n {\n '+' => (string.Empty, \",\", false, false, true, true, false, 1),\n '#' => (\"#\", \",\", false, false, true, true, true, 1),\n '.' => (\".\", \".\", false, false, true, false, true, 1),\n '/' => (\"/\", \"/\", false, false, true, false, false, 1),\n ';' => (\";\", \";\", true, true, false, false, false, 1),\n '?' => (\"?\", \"&\", true, true, true, false, false, 1),\n '&' => (\"&\", \"&\", true, true, true, false, false, 1),\n _ => (string.Empty, \",\", false, false, true, false, false, 0),\n };\n expression = expression.Slice(modifierBehavior.ExpressionSlice);\n\n List expansions = [];\n\n // Process each varspec in the comma-delimited list in the expression (if it doesn't have any\n // commas, it will be the whole expression).\n while (!expression.IsEmpty)\n {\n // Find the next name.\n int commaPos = expression.IndexOf(',');\n ReadOnlySpan name;\n if (commaPos < 0)\n {\n name = expression;\n expression = ReadOnlySpan.Empty;\n }\n else\n {\n name = expression.Slice(0, commaPos);\n expression = expression.Slice(commaPos + 1);\n }\n\n bool explode = false;\n int prefixLength = -1;\n\n // If the name ends with a *, it means we should explode the value into separate\n // name=value pairs. If it has a colon, it means we should only take the first N characters\n // of the value. If it has both, the * takes precedence and we ignore the colon.\n if (!name.IsEmpty && name[name.Length - 1] == '*')\n {\n explode = true;\n name = name.Slice(0, name.Length - 1);\n }\n else if (name.IndexOf(':') >= 0)\n {\n int colonPos = name.IndexOf(':');\n if (colonPos < 0)\n {\n throw new FormatException($\"Invalid varspec '{name.ToString()}'\");\n }\n\n if (!int.TryParse(name.Slice(colonPos + 1)\n#if !NET\n .ToString()\n#endif\n , out prefixLength))\n {\n throw new FormatException($\"Invalid prefix length in varspec '{name.ToString()}'\");\n }\n\n name = name.Slice(0, colonPos);\n }\n\n // Look up the value for this name. If it doesn't exist, skip it.\n string nameString = name.ToString();\n if (!arguments.TryGetValue(nameString, out var value) || value is null)\n {\n continue;\n }\n\n if (value is IEnumerable list)\n {\n var items = list.Select(i => Encode(i, modifierBehavior.AllowReserved));\n if (explode)\n {\n if (modifierBehavior.Named)\n {\n foreach (var item in items)\n {\n expansions.Add($\"{nameString}={item}\");\n }\n }\n else\n {\n foreach (var item in items)\n {\n expansions.Add(item);\n }\n }\n }\n else\n {\n var joined = string.Join(\",\", items);\n expansions.Add(joined.Length > 0 && modifierBehavior.Named ?\n $\"{nameString}={joined}\" :\n joined);\n }\n }\n else if (value is IReadOnlyDictionary assoc)\n {\n var pairs = assoc.Select(kvp => (\n Encode(kvp.Key, modifierBehavior.AllowReserved),\n Encode(kvp.Value, modifierBehavior.AllowReserved)\n ));\n\n if (explode)\n {\n foreach (var (k, v) in pairs)\n {\n expansions.Add($\"{k}={v}\");\n }\n }\n else\n {\n var joined = string.Join(\",\", pairs.Select(p => $\"{p.Item1},{p.Item2}\"));\n if (joined.Length > 0)\n {\n expansions.Add(modifierBehavior.Named ? $\"{nameString}={joined}\" : joined);\n }\n }\n }\n else\n {\n string s =\n value as string ??\n (value is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) : value.ToString()) ??\n string.Empty;\n\n s = Encode((uint)prefixLength < s.Length ? s.Substring(0, prefixLength) : s, modifierBehavior.AllowReserved);\n if (!modifierBehavior.Named)\n {\n expansions.Add(s);\n }\n else if (s.Length != 0 || modifierBehavior.IncludeNameIfEmpty)\n {\n expansions.Add(\n s.Length != 0 ? $\"{nameString}={s}\" :\n modifierBehavior.IncludeSeparatorIfEmpty ? $\"{nameString}=\" :\n nameString);\n }\n }\n }\n\n if (expansions.Count > 0 && \n (modifierBehavior.PrefixEmptyExpansions || !expansions.All(string.IsNullOrEmpty)))\n {\n builder.AppendLiteral(modifierBehavior.Prefix);\n AppendJoin(ref builder, modifierBehavior.Separator, expansions);\n }\n }\n\n return builder.ToStringAndClear();\n }\n\n private static void AppendJoin(ref DefaultInterpolatedStringHandler builder, string separator, IList values)\n {\n int count = values.Count;\n if (count > 0)\n {\n builder.AppendLiteral(values[0]);\n for (int i = 1; i < count; i++)\n {\n builder.AppendLiteral(separator);\n builder.AppendLiteral(values[i]);\n }\n }\n }\n\n private static string Encode(string value, bool allowReserved)\n {\n if (!allowReserved)\n {\n return Uri.EscapeDataString(value);\n }\n\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n int i = 0;\n#if NET\n i = value.AsSpan().IndexOfAnyExcept(s_appendWhenAllowReserved);\n if (i < 0)\n {\n return value;\n }\n\n builder.AppendFormatted(value.AsSpan(0, i));\n#endif\n\n for (; i < value.Length; ++i)\n {\n char c = value[i];\n if (((uint)((c | 0x20) - 'a') <= 'z' - 'a') ||\n ((uint)(c - '0') <= '9' - '0') ||\n \"-._~:/?#[]@!$&'()*+,;=\".Contains(c))\n {\n builder.AppendFormatted(c);\n }\n else if (c == '%' && i < value.Length - 2 && Uri.IsHexDigit(value[i + 1]) && Uri.IsHexDigit(value[i + 2]))\n {\n builder.AppendFormatted(value.AsSpan(i, 3));\n i += 2;\n }\n else\n {\n AppendHex(ref builder, c);\n }\n }\n\n return builder.ToStringAndClear();\n\n static void AppendHex(ref DefaultInterpolatedStringHandler builder, char c)\n {\n ReadOnlySpan hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];\n\n if (c <= 0x7F)\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[c >> 4]);\n builder.AppendFormatted(hexDigits[c & 0xF]);\n }\n else\n {\n#if NET\n Span utf8 = stackalloc byte[Encoding.UTF8.GetMaxByteCount(1)];\n foreach (byte b in utf8.Slice(0, new Rune(c).EncodeToUtf8(utf8)))\n#else\n foreach (byte b in Encoding.UTF8.GetBytes([c]))\n#endif\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[b >> 4]);\n builder.AppendFormatted(hexDigits[b & 0xF]);\n }\n }\n }\n }\n\n /// \n /// Defines an equality comparer for Uri templates as follows:\n /// 1. Non-templated Uris use regular System.Uri equality comparison (host name is case insensitive).\n /// 2. Templated Uris use regular string equality.\n /// \n /// We do this because non-templated resources are looked up directly from the resource dictionary\n /// and we need to make sure equality is implemented correctly. Templated Uris are resolved in a\n /// fallback step using linear traversal of the resource dictionary, so their equality is only\n /// there to distinguish between different templates.\n /// \n public sealed class UriTemplateComparer : IEqualityComparer\n {\n public static IEqualityComparer Instance { get; } = new UriTemplateComparer();\n\n public bool Equals(string? uriTemplate1, string? uriTemplate2)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate1, out Uri? uri1) &&\n TryParseAsNonTemplatedUri(uriTemplate2, out Uri? uri2))\n {\n return uri1 == uri2;\n }\n\n return string.Equals(uriTemplate1, uriTemplate2, StringComparison.Ordinal);\n }\n\n public int GetHashCode([DisallowNull] string uriTemplate)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate, out Uri? uri))\n {\n return uri.GetHashCode();\n }\n else\n {\n return StringComparer.Ordinal.GetHashCode(uriTemplate);\n }\n }\n\n private static bool TryParseAsNonTemplatedUri(string? uriTemplate, [NotNullWhen(true)] out Uri? uri)\n {\n if (uriTemplate is null || uriTemplate.Contains('{'))\n {\n uri = null;\n return false;\n }\n\n return Uri.TryCreate(uriTemplate, UriKind.Absolute, out uri);\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Reference.cs", "using ModelContextProtocol.Client;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a reference to a resource or prompt in the Model Context Protocol.\n/// \n/// \n/// \n/// References are commonly used with to request completion suggestions for arguments,\n/// and with other methods that need to reference resources or prompts.\n/// \n/// \n/// See the schema for details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class Reference\n{\n /// Prevent external derivations.\n private protected Reference() \n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This can be \"ref/resource\" or \"ref/prompt\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override Reference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? name = null;\n string? title = null;\n string? uri = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n default:\n break;\n }\n }\n\n // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n\n switch (type)\n {\n case \"ref/prompt\":\n if (name is null)\n {\n throw new JsonException(\"Prompt references must have a 'name' property.\");\n }\n\n return new PromptReference { Name = name, Title = title };\n\n case \"ref/resource\":\n if (uri is null)\n {\n throw new JsonException(\"Resource references must have a 'uri' property.\");\n }\n\n return new ResourceTemplateReference { Uri = uri };\n\n default:\n throw new JsonException($\"Unknown content type: '{type}'\");\n }\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, Reference value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case PromptReference pr:\n writer.WriteString(\"name\", pr.Name);\n if (pr.Title is not null)\n {\n writer.WriteString(\"title\", pr.Title);\n }\n break;\n\n case ResourceTemplateReference rtr:\n writer.WriteString(\"uri\", rtr.Uri);\n break;\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// \n/// Represents a reference to a prompt, identified by its name.\n/// \npublic sealed class PromptReference : Reference, IBaseMetadata\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public PromptReference() => Type = \"ref/prompt\";\n\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Name}\\\"\";\n}\n\n/// \n/// Represents a reference to a resource or resource template definition.\n/// \npublic sealed class ResourceTemplateReference : Reference\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public ResourceTemplateReference() => Type = \"ref/resource\";\n\n /// \n /// Gets or sets the URI or URI template of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public required string? Uri { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Uri}\\\"\";\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/AnnotatedMessageTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AnnotatedMessageTool\n{\n public enum MessageType\n {\n Error,\n Success,\n Debug,\n }\n\n [McpServerTool(Name = \"annotatedMessage\"), Description(\"Generates an annotated message\")]\n public static IEnumerable AnnotatedMessage(MessageType messageType, bool includeImage = true)\n {\n List contents = messageType switch\n {\n MessageType.Error => [new TextContentBlock\n {\n Text = \"Error: Operation failed\",\n Annotations = new() { Audience = [Role.User, Role.Assistant], Priority = 1.0f }\n }],\n MessageType.Success => [new TextContentBlock\n {\n Text = \"Operation completed successfully\",\n Annotations = new() { Audience = [Role.User], Priority = 0.7f }\n }],\n MessageType.Debug => [new TextContentBlock\n {\n Text = \"Debug: Cache hit ratio 0.95, latency 150ms\",\n Annotations = new() { Audience = [Role.Assistant], Priority = 0.3f }\n }],\n _ => throw new ArgumentOutOfRangeException(nameof(messageType), messageType, null)\n };\n\n if (includeImage)\n {\n contents.Add(new ImageContentBlock\n {\n Data = TinyImageTool.MCP_TINY_IMAGE.Split(\",\").Last(),\n MimeType = \"image/png\",\n Annotations = new() { Audience = [Role.User], Priority = 0.5f }\n });\n }\n\n return contents;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.ObjectModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides an that calls a tool via an .\n/// \n/// \n/// \n/// The class encapsulates an along with a description of \n/// a tool available via that client, allowing it to be invoked as an . This enables integration\n/// with AI models that support function calling capabilities.\n/// \n/// \n/// Tools retrieved from an MCP server can be customized for model presentation using methods like\n/// and without changing the underlying tool functionality.\n/// \n/// \n/// Typically, you would get instances of this class by calling the \n/// or extension methods on an instance.\n/// \n/// \npublic sealed class McpClientTool : AIFunction\n{\n /// Additional properties exposed from tools.\n private static readonly ReadOnlyDictionary s_additionalProperties =\n new(new Dictionary()\n {\n [\"Strict\"] = false, // some MCP schemas may not meet \"strict\" requirements\n });\n\n private readonly IMcpClient _client;\n private readonly string _name;\n private readonly string _description;\n private readonly IProgress? _progress;\n\n internal McpClientTool(\n IMcpClient client,\n Tool tool,\n JsonSerializerOptions serializerOptions,\n string? name = null,\n string? description = null,\n IProgress? progress = null)\n {\n _client = client;\n ProtocolTool = tool;\n JsonSerializerOptions = serializerOptions;\n _name = name ?? tool.Name;\n _description = description ?? tool.Description ?? string.Empty;\n _progress = progress;\n }\n\n /// \n /// Gets the protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the tool,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// It contains the original metadata about the tool as provided by the server, including its\n /// name, description, and schema information before any customizations applied through methods\n /// like or .\n /// \n public Tool ProtocolTool { get; }\n\n /// \n public override string Name => _name;\n\n /// Gets the tool's title.\n public string? Title => ProtocolTool.Title ?? ProtocolTool.Annotations?.Title;\n\n /// \n public override string Description => _description;\n\n /// \n public override JsonElement JsonSchema => ProtocolTool.InputSchema;\n\n /// \n public override JsonElement? ReturnJsonSchema => ProtocolTool.OutputSchema;\n\n /// \n public override JsonSerializerOptions JsonSerializerOptions { get; }\n\n /// \n public override IReadOnlyDictionary AdditionalProperties => s_additionalProperties;\n\n /// \n protected async override ValueTask InvokeCoreAsync(\n AIFunctionArguments arguments, CancellationToken cancellationToken)\n {\n CallToolResult result = await CallAsync(arguments, _progress, JsonSerializerOptions, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult);\n }\n\n /// \n /// Invokes the tool on the server.\n /// \n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// \n /// The base method is overridden to invoke this method.\n /// The only difference in behavior is will serialize the resulting \"/>\n /// such that the returned is a containing the serialized .\n /// This method is intended to be called directly by user code, whereas the base \n /// is intended to be used polymorphically via the base class, typically as part of an operation.\n /// \n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// var result = await tool.CallAsync(\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public ValueTask CallAsync(\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default) =>\n _client.CallToolAsync(ProtocolTool.Name, arguments, progress, serializerOptions, cancellationToken);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified name from its property.\n /// \n /// The model-facing name to give the tool.\n /// A new instance of with the provided name.\n /// \n /// \n /// This is useful for optimizing the tool name for specific models or for prefixing the tool name \n /// with a namespace to avoid conflicts.\n /// \n /// \n /// Changing the name can help with:\n /// \n /// \n /// Making the tool name more intuitive for the model\n /// Preventing name collisions when using tools from multiple sources\n /// Creating specialized versions of a general tool for specific contexts\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool name, so no mapping is required on the server side. This new name only affects\n /// the value returned from this instance's .\n /// \n /// \n public McpClientTool WithName(string name) =>\n new(_client, ProtocolTool, JsonSerializerOptions, name, _description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified description from its property.\n /// \n /// The description to give the tool.\n /// \n /// \n /// Changing the description can help the model better understand the tool's purpose or provide more\n /// context about how the tool should be used. This is particularly useful when:\n /// \n /// \n /// The original description is too technical or lacks clarity for the model\n /// You want to add example usage scenarios to improve the model's understanding\n /// You need to tailor the tool's description for specific model requirements\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool description, so no mapping is required on the server side. This new description only affects\n /// the value returned from this instance's .\n /// \n /// \n /// A new instance of with the provided description.\n public McpClientTool WithDescription(string description) =>\n new(_client, ProtocolTool, JsonSerializerOptions, _name, description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to report progress via the specified .\n /// \n /// The to which progress notifications should be reported.\n /// \n /// \n /// Adding an to the tool does not impact how it is reported to any AI model.\n /// Rather, when the tool is invoked, the request to the MCP server will include a unique progress token,\n /// and any progress notifications issued by the server with that progress token while the operation is in\n /// flight will be reported to the instance.\n /// \n /// \n /// Only one can be specified at a time. Calling again\n /// will overwrite any previously specified progress instance.\n /// \n /// \n /// A new instance of , configured with the provided progress instance.\n public McpClientTool WithProgress(IProgress progress)\n {\n Throw.IfNull(progress);\n\n return new McpClientTool(_client, ProtocolTool, JsonSerializerOptions, _name, _description, progress);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientFactory.cs", "using Microsoft.Extensions.Logging;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides factory methods for creating Model Context Protocol (MCP) clients.\n/// \n/// \n/// This factory class is the primary way to instantiate instances\n/// that connect to MCP servers. It handles the creation and connection\n/// of appropriate implementations through the supplied transport.\n/// \npublic static partial class McpClientFactory\n{\n /// Creates an , connecting it to the specified server.\n /// The transport instance used to communicate with the server.\n /// \n /// A client configuration object which specifies client capabilities and protocol version.\n /// If , details based on the current process will be employed.\n /// \n /// A logger factory for creating loggers for clients.\n /// The to monitor for cancellation requests. The default is .\n /// An that's connected to the specified server.\n /// is .\n /// is .\n public static async Task CreateAsync(\n IClientTransport clientTransport,\n McpClientOptions? clientOptions = null,\n ILoggerFactory? loggerFactory = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(clientTransport);\n\n McpClient client = new(clientTransport, clientOptions, loggerFactory);\n try\n {\n await client.ConnectAsync(cancellationToken).ConfigureAwait(false);\n if (loggerFactory?.CreateLogger(typeof(McpClientFactory)) is ILogger logger)\n {\n logger.LogClientCreated(client.EndpointName);\n }\n }\n catch\n {\n await client.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n\n return client;\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} client created and connected.\")]\n private static partial void LogClientCreated(this ILogger logger, string endpointName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcRequest.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A request message in the JSON-RPC protocol.\n/// \n/// \n/// Requests are messages that require a response from the receiver. Each request includes a unique ID\n/// that will be included in the corresponding response message (either a success response or an error).\n/// \n/// The receiver of a request message is expected to execute the specified method with the provided parameters\n/// and return either a with the result, or a \n/// if the method execution fails.\n/// \npublic sealed class JsonRpcRequest : JsonRpcMessageWithId\n{\n /// \n /// Name of the method to invoke.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Optional parameters for the method.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n\n internal JsonRpcRequest WithId(RequestId id)\n {\n return new JsonRpcRequest\n {\n JsonRpc = JsonRpc,\n Id = id,\n Method = Method,\n Params = Params,\n RelatedTransport = RelatedTransport,\n };\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Program.cs", "using EverythingServer;\nusing EverythingServer.Prompts;\nusing EverythingServer.Resources;\nusing EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Resources;\nusing OpenTelemetry.Trace;\n\nvar builder = Host.CreateApplicationBuilder(args);\nbuilder.Logging.AddConsole(consoleLogOptions =>\n{\n // Configure all logs to go to stderr\n consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nHashSet subscriptions = [];\nvar _minimumLoggingLevel = LoggingLevel.Debug;\n\nbuilder.Services\n .AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithPrompts()\n .WithPrompts()\n .WithResources()\n .WithSubscribeToResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n\n if (uri is not null)\n {\n subscriptions.Add(uri);\n\n await ctx.Server.SampleAsync([\n new ChatMessage(ChatRole.System, \"You are a helpful test server\"),\n new ChatMessage(ChatRole.User, $\"Resource {uri}, context: A new subscription was started\"),\n ],\n options: new ChatOptions\n {\n MaxOutputTokens = 100,\n Temperature = 0.7f,\n },\n cancellationToken: ct);\n }\n\n return new EmptyResult();\n })\n .WithUnsubscribeFromResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n if (uri is not null)\n {\n subscriptions.Remove(uri);\n }\n return new EmptyResult();\n })\n .WithCompleteHandler(async (ctx, ct) =>\n {\n var exampleCompletions = new Dictionary>\n {\n { \"style\", [\"casual\", \"formal\", \"technical\", \"friendly\"] },\n { \"temperature\", [\"0\", \"0.5\", \"0.7\", \"1.0\"] },\n { \"resourceId\", [\"1\", \"2\", \"3\", \"4\", \"5\"] }\n };\n\n if (ctx.Params is not { } @params)\n {\n throw new NotSupportedException($\"Params are required.\");\n }\n\n var @ref = @params.Ref;\n var argument = @params.Argument;\n\n if (@ref is ResourceTemplateReference rtr)\n {\n var resourceId = rtr.Uri?.Split(\"/\").Last();\n\n if (resourceId is null)\n {\n return new CompleteResult();\n }\n\n var values = exampleCompletions[\"resourceId\"].Where(id => id.StartsWith(argument.Value));\n\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n if (@ref is PromptReference pr)\n {\n if (!exampleCompletions.TryGetValue(argument.Name, out IEnumerable? value))\n {\n throw new NotSupportedException($\"Unknown argument name: {argument.Name}\");\n }\n\n var values = value.Where(value => value.StartsWith(argument.Value));\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n throw new NotSupportedException($\"Unknown reference type: {@ref.Type}\");\n })\n .WithSetLoggingLevelHandler(async (ctx, ct) =>\n {\n if (ctx.Params?.Level is null)\n {\n throw new McpException(\"Missing required argument 'level'\", McpErrorCode.InvalidParams);\n }\n\n _minimumLoggingLevel = ctx.Params.Level;\n\n await ctx.Server.SendNotificationAsync(\"notifications/message\", new\n {\n Level = \"debug\",\n Logger = \"test-server\",\n Data = $\"Logging level set to {_minimumLoggingLevel}\",\n }, cancellationToken: ct);\n\n return new EmptyResult();\n });\n\nResourceBuilder resource = ResourceBuilder.CreateDefault().AddService(\"everything-server\");\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithMetrics(b => b.AddMeter(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithLogging(b => b.SetResourceBuilder(resource))\n .UseOtlpExporter();\n\nbuilder.Services.AddSingleton(subscriptions);\nbuilder.Services.AddHostedService();\nbuilder.Services.AddHostedService();\n\nbuilder.Services.AddSingleton>(_ => () => _minimumLoggingLevel);\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/IdleTrackingBackgroundService.cs", "using System.Runtime.InteropServices;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed partial class IdleTrackingBackgroundService(\n StreamableHttpHandler handler,\n IOptions options,\n IHostApplicationLifetime appLifetime,\n ILogger logger) : BackgroundService\n{\n // The compiler will complain about the parameter being unused otherwise despite the source generator.\n private readonly ILogger _logger = logger;\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n // Still run loop given infinite IdleTimeout to enforce the MaxIdleSessionCount and assist graceful shutdown.\n if (options.Value.IdleTimeout != Timeout.InfiniteTimeSpan)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.IdleTimeout, TimeSpan.Zero);\n }\n\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.MaxIdleSessionCount, 0);\n\n try\n {\n var timeProvider = options.Value.TimeProvider;\n using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);\n\n var idleTimeoutTicks = options.Value.IdleTimeout.Ticks;\n var maxIdleSessionCount = options.Value.MaxIdleSessionCount;\n\n // Create two lists that will be reused between runs.\n // This assumes that the number of idle sessions is not breached frequently.\n // If the idle sessions often breach the maximum, a priority queue could be considered.\n var idleSessionsTimestamps = new List();\n var idleSessionSessionIds = new List();\n\n while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))\n {\n var idleActivityCutoff = idleTimeoutTicks switch\n {\n < 0 => long.MinValue,\n var ticks => timeProvider.GetTimestamp() - ticks,\n };\n\n foreach (var (_, session) in handler.Sessions)\n {\n if (session.IsActive || session.SessionClosed.IsCancellationRequested)\n {\n // There's a request currently active or the session is already being closed.\n continue;\n }\n\n if (session.LastActivityTicks < idleActivityCutoff)\n {\n RemoveAndCloseSession(session.Id);\n continue;\n }\n\n // Add the timestamp and the session\n idleSessionsTimestamps.Add(session.LastActivityTicks);\n idleSessionSessionIds.Add(session.Id);\n\n // Emit critical log at most once every 5 seconds the idle count it exceeded,\n // since the IdleTimeout will no longer be respected.\n if (idleSessionsTimestamps.Count == maxIdleSessionCount + 1)\n {\n LogMaxSessionIdleCountExceeded(maxIdleSessionCount);\n }\n }\n\n if (idleSessionsTimestamps.Count > maxIdleSessionCount)\n {\n var timestamps = CollectionsMarshal.AsSpan(idleSessionsTimestamps);\n\n // Sort only if the maximum is breached and sort solely by the timestamp. Sort both collections.\n timestamps.Sort(CollectionsMarshal.AsSpan(idleSessionSessionIds));\n\n var sessionsToPrune = CollectionsMarshal.AsSpan(idleSessionSessionIds)[..^maxIdleSessionCount];\n foreach (var id in sessionsToPrune)\n {\n RemoveAndCloseSession(id);\n }\n }\n\n idleSessionsTimestamps.Clear();\n idleSessionSessionIds.Clear();\n }\n }\n catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)\n {\n }\n finally\n {\n try\n {\n List disposeSessionTasks = [];\n\n foreach (var (sessionKey, _) in handler.Sessions)\n {\n if (handler.Sessions.TryRemove(sessionKey, out var session))\n {\n disposeSessionTasks.Add(DisposeSessionAsync(session));\n }\n }\n\n await Task.WhenAll(disposeSessionTasks);\n }\n finally\n {\n if (!stoppingToken.IsCancellationRequested)\n {\n // Something went terribly wrong. A very unexpected exception must be bubbling up, but let's ensure we also stop the application,\n // so that it hopefully gets looked at and restarted. This shouldn't really be reachable.\n appLifetime.StopApplication();\n IdleTrackingBackgroundServiceStoppedUnexpectedly();\n }\n }\n }\n }\n\n private void RemoveAndCloseSession(string sessionId)\n {\n if (!handler.Sessions.TryRemove(sessionId, out var session))\n {\n return;\n }\n\n LogSessionIdle(session.Id);\n // Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown.\n _ = DisposeSessionAsync(session);\n }\n\n private async Task DisposeSessionAsync(HttpMcpSession session)\n {\n try\n {\n await session.DisposeAsync();\n }\n catch (Exception ex)\n {\n LogSessionDisposeError(session.Id, ex);\n }\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Closing idle session {sessionId}.\")]\n private partial void LogSessionIdle(string sessionId);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"Error disposing session {sessionId}.\")]\n private partial void LogSessionDisposeError(string sessionId, Exception ex);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"Exceeded maximum of {maxIdleSessionCount} idle sessions. Now closing sessions active more recently than configured IdleTimeout.\")]\n private partial void LogMaxSessionIdleCountExceeded(int maxIdleSessionCount);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"The IdleTrackingBackgroundService has stopped unexpectedly.\")]\n private partial void IdleTrackingBackgroundServiceStoppedUnexpectedly();\n}"], ["/csharp-sdk/samples/QuickstartClient/Program.cs", "using Anthropic.SDK;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Client;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Configuration\n .AddEnvironmentVariables()\n .AddUserSecrets();\n\nvar (command, arguments) = GetCommandAndArguments(args);\n\nvar clientTransport = new StdioClientTransport(new()\n{\n Name = \"Demo Server\",\n Command = command,\n Arguments = arguments,\n});\n\nawait using var mcpClient = await McpClientFactory.CreateAsync(clientTransport);\n\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\"Connected to server with tools: {tool.Name}\");\n}\n\nusing var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration[\"ANTHROPIC_API_KEY\"]))\n .Messages\n .AsBuilder()\n .UseFunctionInvocation()\n .Build();\n\nvar options = new ChatOptions\n{\n MaxOutputTokens = 1000,\n ModelId = \"claude-3-5-sonnet-20241022\",\n Tools = [.. tools]\n};\n\nConsole.ForegroundColor = ConsoleColor.Green;\nConsole.WriteLine(\"MCP Client Started!\");\nConsole.ResetColor();\n\nPromptForInput();\nwhile(Console.ReadLine() is string query && !\"exit\".Equals(query, StringComparison.OrdinalIgnoreCase))\n{\n if (string.IsNullOrWhiteSpace(query))\n {\n PromptForInput();\n continue;\n }\n\n await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))\n {\n Console.Write(message);\n }\n Console.WriteLine();\n\n PromptForInput();\n}\n\nstatic void PromptForInput()\n{\n Console.WriteLine(\"Enter a command (or 'exit' to quit):\");\n Console.ForegroundColor = ConsoleColor.Cyan;\n Console.Write(\"> \");\n Console.ResetColor();\n}\n\n/// \n/// Determines the command (executable) to run and the script/path to pass to it. This allows different\n/// languages/runtime environments to be used as the MCP server.\n/// \n/// \n/// This method uses the file extension of the first argument to determine the command, if it's py, it'll run python,\n/// if it's js, it'll run node, if it's a directory or a csproj file, it'll run dotnet.\n/// \n/// If no arguments are provided, it defaults to running the QuickstartWeatherServer project from the current repo.\n/// \n/// This method would only be required if you're creating a generic client, such as we use for the quickstart.\n/// \nstatic (string command, string[] arguments) GetCommandAndArguments(string[] args)\n{\n return args switch\n {\n [var script] when script.EndsWith(\".py\") => (\"python\", args),\n [var script] when script.EndsWith(\".js\") => (\"node\", args),\n [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(\".csproj\")) => (\"dotnet\", [\"run\", \"--project\", script]),\n _ => (\"dotnet\", [\"run\", \"--project\", Path.Combine(GetCurrentSourceDirectory(), \"../QuickstartWeatherServer\")])\n };\n}\n\nstatic string GetCurrentSourceDirectory([CallerFilePath] string? currentFile = null)\n{\n Debug.Assert(!string.IsNullOrWhiteSpace(currentFile));\n return Path.GetDirectoryName(currentFile) ?? throw new InvalidOperationException(\"Unable to determine source directory.\");\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/CustomizableJsonStringEnumConverter.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.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\n#if !NET9_0_OR_GREATER\nusing System.Reflection;\n#endif\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n#if !NET9_0_OR_GREATER\nusing ModelContextProtocol;\n#endif\n\n// NOTE:\n// This is a workaround for lack of System.Text.Json's JsonStringEnumConverter\n// 9.x support for JsonStringEnumMemberNameAttribute. Once all builds use the System.Text.Json 9.x\n// version, this whole file can be removed. Note that the type is public so that external source\n// generators can use it, so removing it is a potential breaking change.\n\nnamespace ModelContextProtocol\n{\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// The enum type to convert.\n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class CustomizableJsonStringEnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum> :\n JsonStringEnumConverter where TEnum : struct, Enum\n {\n#if !NET9_0_OR_GREATER\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The converter automatically detects any enum members decorated with \n /// and uses those values during serialization and deserialization.\n /// \n public CustomizableJsonStringEnumConverter() :\n base(namingPolicy: ResolveNamingPolicy())\n {\n }\n\n private static JsonNamingPolicy? ResolveNamingPolicy()\n {\n var map = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)\n .Select(f => (f.Name, AttributeName: f.GetCustomAttribute()?.Name))\n .Where(pair => pair.AttributeName != null)\n .ToDictionary(pair => pair.Name, pair => pair.AttributeName);\n\n return map.Count > 0 ? new EnumMemberNamingPolicy(map!) : null;\n }\n\n private sealed class EnumMemberNamingPolicy(Dictionary map) : JsonNamingPolicy\n {\n public override string ConvertName(string name) =>\n map.TryGetValue(name, out string? newName) ?\n newName :\n name;\n }\n#endif\n }\n\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n [RequiresUnreferencedCode(\"Requires unreferenced code to instantiate the generic enum converter.\")]\n [RequiresDynamicCode(\"Requires dynamic code to instantiate the generic enum converter.\")]\n public sealed class CustomizableJsonStringEnumConverter : JsonConverterFactory\n {\n /// \n public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum;\n /// \n public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)\n {\n Type converterType = typeof(CustomizableJsonStringEnumConverter<>).MakeGenericType(typeToConvert)!;\n var factory = (JsonConverterFactory)Activator.CreateInstance(converterType)!;\n return factory.CreateConverter(typeToConvert, options);\n }\n }\n}\n\n#if !NET9_0_OR_GREATER\nnamespace System.Text.Json.Serialization\n{\n /// \n /// Determines the custom string value that should be used when serializing an enum member using JSON.\n /// \n /// \n /// This attribute is a temporary workaround for lack of System.Text.Json's support for custom enum member naming\n /// in versions prior to .NET 9. It works together with \n /// to provide customized string representations of enum values during JSON serialization and deserialization.\n /// \n [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\n internal sealed class JsonStringEnumMemberNameAttribute : Attribute\n {\n /// \n /// Creates new attribute instance with a specified enum member name.\n /// \n /// The name to apply to the current enum member when serialized to JSON.\n public JsonStringEnumMemberNameAttribute(string name)\n {\n Name = name;\n }\n\n /// \n /// Gets the custom JSON name of the enum member.\n /// \n public string Name { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol/McpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring MCP servers via dependency injection.\n/// \npublic static partial class McpServerBuilderExtensions\n{\n #region WithTools\n private const string WithToolsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithTools)} and {nameof(WithToolsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithTools)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The tool type.\n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n public static IMcpServerBuilder WithTools<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TToolType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var toolMethod in typeof(TToolType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, static r => CreateTarget(r.Services, typeof(TToolType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable tools)\n {\n Throw.IfNull(builder);\n Throw.IfNull(tools);\n\n foreach (var tool in tools)\n {\n if (tool is not null)\n {\n builder.Services.AddSingleton(tool);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with -attributed methods to add as tools to the server.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable toolTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(toolTypes);\n\n foreach (var toolType in toolTypes)\n {\n if (toolType is not null)\n {\n foreach (var toolMethod in toolType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services , SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, r => CreateTarget(r.Services, toolType), new() { Services = services , SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as tools to the server.\n /// \n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the tool.\n /// \n /// \n /// Tools registered through this method can be discovered by clients using the list_tools request\n /// and invoked using the call_tool request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithToolsFromAssembly(this IMcpServerBuilder builder, Assembly? toolAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n toolAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithTools(\n from t in toolAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithPrompts\n private const string WithPromptsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithPrompts)} and {nameof(WithPromptsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithPrompts)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The prompt type.\n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n public static IMcpServerBuilder WithPrompts<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TPromptType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var promptMethod in typeof(TPromptType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, static r => CreateTarget(r.Services, typeof(TPromptType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable prompts)\n {\n Throw.IfNull(builder);\n Throw.IfNull(prompts);\n\n foreach (var prompt in prompts)\n {\n if (prompt is not null)\n {\n builder.Services.AddSingleton(prompt);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as prompts to the server.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable promptTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(promptTypes);\n\n foreach (var promptType in promptTypes)\n {\n if (promptType is not null)\n {\n foreach (var promptMethod in promptType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, r => CreateTarget(r.Services, promptType), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as prompts to the server.\n /// \n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the prompt.\n /// \n /// \n /// Prompts registered through this method can be discovered by clients using the list_prompts request\n /// and invoked using the call_prompt request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPromptsFromAssembly(this IMcpServerBuilder builder, Assembly? promptAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n promptAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithPrompts(\n from t in promptAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithResources\n private const string WithResourcesRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithResources)} and {nameof(WithResourcesFromAssembly)} methods require dynamic lookup of member metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithResources)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The resource type.\n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the members are attributed as , and adds an \n /// instance for each. For instance members, an instance will be constructed for each invocation of the resource.\n /// \n public static IMcpServerBuilder WithResources<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TResourceType>(\n this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n foreach (var resourceTemplateMethod in typeof(TResourceType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, static r => CreateTarget(r.Services, typeof(TResourceType)), new() { Services = services })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplates)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplates);\n\n foreach (var resourceTemplate in resourceTemplates)\n {\n if (resourceTemplate is not null)\n {\n builder.Services.AddSingleton(resourceTemplate);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as resources to the server.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the resource.\n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplateTypes)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplateTypes);\n\n foreach (var resourceTemplateType in resourceTemplateTypes)\n {\n if (resourceTemplateType is not null)\n {\n foreach (var resourceTemplateMethod in resourceTemplateType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, r => CreateTarget(r.Services, resourceTemplateType), new() { Services = services })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as resources to the server.\n /// \n /// The builder instance.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all members within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance members. For instance members, a new instance\n /// of the containing class will be constructed for each invocation of the resource.\n /// \n /// \n /// Resource templates registered through this method can be discovered by clients using the list_resourceTemplates request\n /// and invoked using the read_resource request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResourcesFromAssembly(this IMcpServerBuilder builder, Assembly? resourceAssembly = null)\n {\n Throw.IfNull(builder);\n\n resourceAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithResources(\n from t in resourceAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t);\n }\n #endregion\n\n #region Handlers\n /// \n /// Configures a handler for listing resource templates available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource template list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is responsible for providing clients with information about available resource templates\n /// that can be used to construct resource URIs.\n /// \n /// \n /// Resource templates describe the structure of resource URIs that the server can handle. They include\n /// URI templates (according to RFC 6570) that clients can use to construct valid resource URIs.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// resource system where templates define the URI patterns and the read handler provides the actual content.\n /// \n /// \n public static IMcpServerBuilder WithListResourceTemplatesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourceTemplatesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list tools requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available tools. It should return all tools\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// tool collections.\n /// \n /// \n /// When tools are also defined using collection, both sets of tools\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// tools and dynamically generated tools.\n /// \n /// \n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and \n /// executes them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListToolsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListToolsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for calling tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes tool calls.\n /// The builder provided in .\n /// is .\n /// \n /// The call tool handler is responsible for executing custom tools and returning their results to clients.\n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and this handler executes them.\n /// \n public static IMcpServerBuilder WithCallToolHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CallToolHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing prompts available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list prompts requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available prompts. It should return all prompts\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// prompt collections.\n /// \n /// \n /// When prompts are also defined using collection, both sets of prompts\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// prompts and dynamically generated prompts.\n /// \n /// \n /// This method is typically paired with to provide a complete prompts implementation,\n /// where advertises available prompts and \n /// produces them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListPromptsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListPromptsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for getting a prompt available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes prompt requests.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithGetPromptHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.GetPromptHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing resources available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where this handler advertises available resources and the read handler provides their content when requested.\n /// \n /// \n public static IMcpServerBuilder WithListResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for reading a resource available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource read requests.\n /// The builder provided in .\n /// is .\n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where the list handler advertises available resources and the read handler provides their content when requested.\n /// \n public static IMcpServerBuilder WithReadResourceHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ReadResourceHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for auto-completion suggestions for prompt arguments or resource references available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes completion requests.\n /// The builder provided in .\n /// is .\n /// \n /// The completion handler is invoked when clients request suggestions for argument values.\n /// This enables auto-complete functionality for both prompt arguments and resource references.\n /// \n public static IMcpServerBuilder WithCompleteHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CompleteHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource subscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource subscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The subscribe handler is responsible for registering client interest in specific resources. When a resource\n /// changes, the server can notify all subscribed clients about the change.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. Resource subscriptions allow clients to maintain up-to-date information without\n /// needing to poll resources constantly.\n /// \n /// \n /// After registering a subscription, it's the server's responsibility to track which client is subscribed to which\n /// resources and to send appropriate notifications through the connection when resources change.\n /// \n /// \n public static IMcpServerBuilder WithSubscribeToResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SubscribeToResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource unsubscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource unsubscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The unsubscribe handler is responsible for removing client interest in specific resources. When a client\n /// no longer needs to receive notifications about resource changes, it can send an unsubscribe request.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. The unsubscribe operation is idempotent, meaning it can be called multiple\n /// times for the same resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// After removing a subscription, the server should stop sending notifications to the client about changes\n /// to the specified resource.\n /// \n /// \n public static IMcpServerBuilder WithUnsubscribeFromResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.UnsubscribeFromResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for processing logging level change requests from clients.\n /// \n /// The server builder instance.\n /// The handler that processes requests to change the logging level.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// When a client sends a logging/setLevel request, this handler will be invoked to process\n /// the requested level change. The server typically adjusts its internal logging level threshold\n /// and may begin sending log messages at or above the specified level to the client.\n /// \n /// \n /// Regardless of whether a handler is provided, an should itself handle\n /// such notifications by updating its property to return the\n /// most recently set level.\n /// \n /// \n public static IMcpServerBuilder WithSetLoggingLevelHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SetLoggingLevelHandler = handler);\n return builder;\n }\n #endregion\n\n #region Transports\n /// \n /// Adds a server transport that uses standard input (stdin) and standard output (stdout) for communication.\n /// \n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method configures the server to communicate using the standard input and output streams,\n /// which is commonly used when the Model Context Protocol server is launched locally by a client process.\n /// \n /// \n /// When using this transport, the server runs as a single-session service that exits when the\n /// stdin stream is closed. This makes it suitable for scenarios where the server should terminate\n /// when the parent process disconnects.\n /// \n /// \n /// is .\n public static IMcpServerBuilder WithStdioServerTransport(this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(sp =>\n {\n var serverOptions = sp.GetRequiredService>();\n var loggerFactory = sp.GetService();\n return new StdioServerTransport(serverOptions.Value, loggerFactory);\n });\n\n return builder;\n }\n\n /// \n /// Adds a server transport that uses the specified input and output streams for communication.\n /// \n /// The builder instance.\n /// The input to use as standard input.\n /// The output to use as standard output.\n /// The builder provided in .\n /// is .\n /// is .\n /// is .\n public static IMcpServerBuilder WithStreamServerTransport(\n this IMcpServerBuilder builder,\n Stream inputStream,\n Stream outputStream)\n {\n Throw.IfNull(builder);\n Throw.IfNull(inputStream);\n Throw.IfNull(outputStream);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(new StreamServerTransport(inputStream, outputStream));\n\n return builder;\n }\n\n private static void AddSingleSessionServerDependencies(IServiceCollection services)\n {\n services.AddHostedService();\n services.TryAddSingleton(services =>\n {\n ITransport serverTransport = services.GetRequiredService();\n IOptions options = services.GetRequiredService>();\n ILoggerFactory? loggerFactory = services.GetService();\n return McpServerFactory.Create(serverTransport, options.Value, loggerFactory, services);\n });\n }\n #endregion\n\n #region Helpers\n /// Creates an instance of the target object.\n private static object CreateTarget(\n IServiceProvider? services,\n [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) =>\n services is not null ? ActivatorUtilities.CreateInstance(services, type) :\n Activator.CreateInstance(type)!;\n #endregion\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace ProtectedMCPServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n private readonly IHttpClientFactory _httpClientFactory;\n\n public WeatherTools(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public async Task GetAlerts(\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public async Task GetForecast(\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientPrompt.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named prompt that can be retrieved from an MCP server and invoked with arguments.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a prompt defined on an MCP server. It allows\n/// retrieving the prompt's content by sending a request to the server with optional arguments.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \n/// Each prompt has a name and optionally a description, and it can be invoked with arguments\n/// to produce customized prompt content from the server.\n/// \n/// \npublic sealed class McpClientPrompt\n{\n private readonly IMcpClient _client;\n\n internal McpClientPrompt(IMcpClient client, Prompt prompt)\n {\n _client = client;\n ProtocolPrompt = prompt;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the prompt,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Prompt ProtocolPrompt { get; }\n\n /// Gets the name of the prompt.\n public string Name => ProtocolPrompt.Name;\n\n /// Gets the title of the prompt.\n public string? Title => ProtocolPrompt.Title;\n\n /// Gets a description of the prompt.\n public string? Description => ProtocolPrompt.Description;\n\n /// \n /// Gets this prompt's content by sending a request to the server with optional arguments.\n /// \n /// Optional arguments to pass to the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to execute this prompt with the provided arguments.\n /// The server will process the request and return a result containing messages or other content.\n /// \n /// \n /// This is a convenience method that internally calls \n /// with this prompt's name and arguments.\n /// \n /// \n public async ValueTask GetAsync(\n IEnumerable>? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n IReadOnlyDictionary? argDict =\n arguments as IReadOnlyDictionary ??\n arguments?.ToDictionary();\n\n return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, serializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Net/Http/HttpClientExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Net.Http;\n\ninternal static class HttpClientExtensions\n{\n public static async Task ReadAsStreamAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStreamAsync();\n }\n\n public static async Task ReadAsStringAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStringAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StdioServerTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implemented via \"stdio\" (standard input/output).\n/// \npublic sealed class StdioServerTransport : StreamServerTransport\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The server options.\n /// Optional logger factory used for logging employed by the transport.\n /// is or contains a null name.\n public StdioServerTransport(McpServerOptions serverOptions, ILoggerFactory? loggerFactory = null)\n : this(GetServerName(serverOptions), loggerFactory: loggerFactory)\n {\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the server.\n /// Optional logger factory used for logging employed by the transport.\n /// is .\n public StdioServerTransport(string serverName, ILoggerFactory? loggerFactory = null)\n : base(new CancellableStdinStream(Console.OpenStandardInput()),\n new BufferedStream(Console.OpenStandardOutput()),\n serverName ?? throw new ArgumentNullException(nameof(serverName)),\n loggerFactory)\n {\n }\n\n private static string GetServerName(McpServerOptions serverOptions)\n {\n Throw.IfNull(serverOptions);\n\n return serverOptions.ServerInfo?.Name ?? McpServer.DefaultImplementation.Name;\n }\n\n // Neither WindowsConsoleStream nor UnixConsoleStream respect CancellationTokens or cancel any I/O on Dispose.\n // WindowsConsoleStream will return an EOS on Ctrl-C, but that is not the only reason the shutdownToken may fire.\n private sealed class CancellableStdinStream(Stream stdinStream) : Stream\n {\n public override bool CanRead => true;\n public override bool CanSeek => false;\n public override bool CanWrite => false;\n\n public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n => stdinStream.ReadAsync(buffer, offset, count, cancellationToken).WaitAsync(cancellationToken);\n\n#if NET\n public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)\n {\n ValueTask vt = stdinStream.ReadAsync(buffer, cancellationToken);\n return vt.IsCompletedSuccessfully ? vt : new(vt.AsTask().WaitAsync(cancellationToken));\n }\n#endif\n\n // The McpServer shouldn't call flush on the stdin Stream, but it doesn't need to throw just in case.\n public override void Flush() { }\n\n public override long Length => throw new NotSupportedException();\n\n public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }\n\n public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();\n\n public override void SetLength(long value) => throw new NotSupportedException();\n public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable prompt used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP prompt for use in the server (as opposed\n/// to , which provides the protocol representation of a prompt, and , which\n/// provides a client-side representation of a prompt). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithPromptsFromAssembly and WithPrompts. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to \n/// rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerPrompt : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerPrompt()\n {\n }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolPrompt property represents the underlying prompt definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the prompt's name,\n /// description, and acceptable arguments.\n /// \n public abstract Prompt ProtocolPrompt { get; }\n\n /// \n /// Gets the prompt, rendering it with the provided request parameters and returning the prompt result.\n /// \n /// \n /// The request context containing information about the prompt invocation, including any arguments\n /// passed to the prompt. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the prompt content and messages.\n /// \n /// is .\n /// The prompt implementation returns or an unsupported result type.\n public abstract ValueTask GetAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerPrompt Create(\n MethodInfo method, \n object? target = null,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerPrompt Create(\n AIFunction function,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(function, options);\n\n /// \n public override string ToString() => ProtocolPrompt.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolPrompt.Name;\n}\n"], ["/csharp-sdk/src/Common/CancellableStreamReader/ValueStringBuilder.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.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n#nullable enable\n\nnamespace System.Text\n{\n internal ref partial struct ValueStringBuilder\n {\n private char[]? _arrayToReturnToPool;\n private Span _chars;\n private int _pos;\n\n public ValueStringBuilder(Span initialBuffer)\n {\n _arrayToReturnToPool = null;\n _chars = initialBuffer;\n _pos = 0;\n }\n\n public ValueStringBuilder(int initialCapacity)\n {\n _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity);\n _chars = _arrayToReturnToPool;\n _pos = 0;\n }\n\n public int Length\n {\n get => _pos;\n set\n {\n Debug.Assert(value >= 0);\n Debug.Assert(value <= _chars.Length);\n _pos = value;\n }\n }\n\n public int Capacity => _chars.Length;\n\n public void EnsureCapacity(int capacity)\n {\n // This is not expected to be called this with negative capacity\n Debug.Assert(capacity >= 0);\n\n // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.\n if ((uint)capacity > (uint)_chars.Length)\n Grow(capacity - _pos);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// Does not ensure there is a null char after \n /// This overload is pattern matched in the C# 7.3+ compiler so you can omit\n /// the explicit method call, and write eg \"fixed (char* c = builder)\"\n /// \n public ref char GetPinnableReference()\n {\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// \n /// Ensures that the builder has a null char after \n public ref char GetPinnableReference(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n public ref char this[int index]\n {\n get\n {\n Debug.Assert(index < _pos);\n return ref _chars[index];\n }\n }\n\n public override string ToString()\n {\n string s = _chars.Slice(0, _pos).ToString();\n Dispose();\n return s;\n }\n\n /// Returns the underlying storage of the builder.\n public Span RawChars => _chars;\n\n /// \n /// Returns a span around the contents of the builder.\n /// \n /// Ensures that the builder has a null char after \n public ReadOnlySpan AsSpan(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return _chars.Slice(0, _pos);\n }\n\n public ReadOnlySpan AsSpan() => _chars.Slice(0, _pos);\n public ReadOnlySpan AsSpan(int start) => _chars.Slice(start, _pos - start);\n public ReadOnlySpan AsSpan(int start, int length) => _chars.Slice(start, length);\n\n public bool TryCopyTo(Span destination, out int charsWritten)\n {\n if (_chars.Slice(0, _pos).TryCopyTo(destination))\n {\n charsWritten = _pos;\n Dispose();\n return true;\n }\n else\n {\n charsWritten = 0;\n Dispose();\n return false;\n }\n }\n\n public void Insert(int index, char value, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n _chars.Slice(index, count).Fill(value);\n _pos += count;\n }\n\n public void Insert(int index, string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int count = s.Length;\n\n if (_pos > (_chars.Length - count))\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(index));\n _pos += count;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(char c)\n {\n int pos = _pos;\n Span chars = _chars;\n if ((uint)pos < (uint)chars.Length)\n {\n chars[pos] = c;\n _pos = pos + 1;\n }\n else\n {\n GrowAndAppend(c);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int pos = _pos;\n if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.\n {\n _chars[pos] = s[0];\n _pos = pos + 1;\n }\n else\n {\n AppendSlow(s);\n }\n }\n\n private void AppendSlow(string s)\n {\n int pos = _pos;\n if (pos > _chars.Length - s.Length)\n {\n Grow(s.Length);\n }\n\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(pos));\n _pos += s.Length;\n }\n\n public void Append(char c, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n Span dst = _chars.Slice(_pos, count);\n for (int i = 0; i < dst.Length; i++)\n {\n dst[i] = c;\n }\n _pos += count;\n }\n\n public void Append(scoped ReadOnlySpan value)\n {\n int pos = _pos;\n if (pos > _chars.Length - value.Length)\n {\n Grow(value.Length);\n }\n\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public Span AppendSpan(int length)\n {\n int origPos = _pos;\n if (origPos > _chars.Length - length)\n {\n Grow(length);\n }\n\n _pos = origPos + length;\n return _chars.Slice(origPos, length);\n }\n\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowAndAppend(char c)\n {\n Grow(1);\n Append(c);\n }\n\n /// \n /// Resize the internal buffer either by doubling current buffer size or\n /// by adding to\n /// whichever is greater.\n /// \n /// \n /// Number of chars requested beyond current position.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void Grow(int additionalCapacityBeyondPos)\n {\n Debug.Assert(additionalCapacityBeyondPos > 0);\n Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, \"Grow called incorrectly, no resize is needed.\");\n\n const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength\n\n // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try\n // to double the size if possible, bounding the doubling to not go beyond the max array length.\n int newCapacity = (int)Math.Max(\n (uint)(_pos + additionalCapacityBeyondPos),\n Math.Min((uint)_chars.Length * 2, ArrayMaxLength));\n\n // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.\n // This could also go negative if the actual required length wraps around.\n char[] poolArray = ArrayPool.Shared.Rent(newCapacity);\n\n _chars.Slice(0, _pos).CopyTo(poolArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = poolArray;\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Dispose()\n {\n char[]? toReturn = _arrayToReturnToPool;\n this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/IMcpEndpoint.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Represents a client or server Model Context Protocol (MCP) endpoint.\n/// \n/// \n/// \n/// The MCP endpoint provides the core communication functionality used by both clients and servers:\n/// \n/// Sending JSON-RPC requests and receiving responses.\n/// Sending notifications to the connected endpoint.\n/// Registering handlers for receiving notifications.\n/// \n/// \n/// \n/// serves as the base interface for both and \n/// interfaces, providing the common functionality needed for MCP protocol \n/// communication. Most applications will use these more specific interfaces rather than working with \n/// directly.\n/// \n/// \n/// All MCP endpoints should be properly disposed after use as they implement .\n/// \n/// \npublic interface IMcpEndpoint : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Sends a JSON-RPC request to the connected endpoint and waits for a response.\n /// \n /// The JSON-RPC request to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the endpoint's response.\n /// The transport is not connected, or another error occurs during request processing.\n /// An error occured during request processing.\n /// \n /// This method provides low-level access to send raw JSON-RPC requests. For most use cases,\n /// consider using the strongly-typed extension methods that provide a more convenient API.\n /// \n Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default);\n\n /// \n /// Sends a JSON-RPC message to the connected endpoint.\n /// \n /// \n /// The JSON-RPC message to send. This can be any type that implements JsonRpcMessage, such as\n /// JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, or JsonRpcError.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// is .\n /// \n /// \n /// This method provides low-level access to send any JSON-RPC message. For specific message types,\n /// consider using the higher-level methods such as or extension methods\n /// like ,\n /// which provide a simpler API.\n /// \n /// \n /// The method will serialize the message and transmit it using the underlying transport mechanism.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n\n /// Registers a handler to be invoked when a notification for the specified method is received.\n /// The notification method.\n /// The handler to be invoked.\n /// An that will remove the registered handler when disposed.\n IAsyncDisposable RegisterNotificationHandler(string method, Func handler);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable tool used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP tool for use in the server (as opposed\n/// to , which provides the protocol representation of a tool, and , which\n/// provides a client-side representation of a tool). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithToolsFromAssembly and WithTools. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \npublic abstract class McpServerTool : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerTool()\n {\n }\n\n /// Gets the protocol type for this instance.\n public abstract Tool ProtocolTool { get; }\n\n /// Invokes the .\n /// The request information resulting in the invocation of this tool.\n /// The to monitor for cancellation requests. The default is .\n /// The call response from invoking the tool.\n /// is .\n public abstract ValueTask InvokeAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerTool Create(\n MethodInfo method, \n object? target = null,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerTool Create(\n AIFunction function,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(function, options);\n\n /// \n public override string ToString() => ProtocolTool.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolTool.Name;\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Tasks/TaskExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class TaskExtensions\n{\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n await WaitAsync((Task)task, timeout, cancellationToken).ConfigureAwait(false);\n return task.Result;\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(task);\n\n if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan)\n {\n throw new ArgumentOutOfRangeException(nameof(timeout));\n }\n\n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n cts.CancelAfter(timeout);\n\n var cancellationTask = new TaskCompletionSource();\n using var _ = cts.Token.Register(tcs => ((TaskCompletionSource)tcs!).TrySetResult(true), cancellationTask);\n await Task.WhenAny(task, cancellationTask.Task).ConfigureAwait(false);\n \n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n throw new TimeoutException();\n }\n }\n\n await task.ConfigureAwait(false);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestId.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC request identifier, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct RequestId : IEquatable\n{\n /// The id, either a string or a boxed long or null.\n private readonly object? _id;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(string value)\n {\n Throw.IfNull(value);\n _id = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(long value)\n {\n // Box the long. Request IDs are almost always strings in practice, so this should be rare.\n _id = value;\n }\n\n /// Gets the underlying object for this id.\n /// This will either be a , a boxed , or .\n public object? Id => _id;\n\n /// \n public override string ToString() =>\n _id is string stringValue ? stringValue :\n _id is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n string.Empty;\n\n /// \n public bool Equals(RequestId other) => Equals(_id, other._id);\n\n /// \n public override bool Equals(object? obj) => obj is RequestId other && Equals(other);\n\n /// \n public override int GetHashCode() => _id?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(RequestId left, RequestId right) => left.Equals(right);\n\n /// \n public static bool operator !=(RequestId left, RequestId right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override RequestId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"requestId must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, RequestId value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._id)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpSession.cs", "using ModelContextProtocol.AspNetCore.Stateless;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Security.Claims;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed class HttpMcpSession(\n string sessionId,\n TTransport transport,\n UserIdClaim? userId,\n TimeProvider timeProvider) : IAsyncDisposable\n where TTransport : ITransport\n{\n private int _referenceCount;\n private int _getRequestStarted;\n private CancellationTokenSource _disposeCts = new();\n\n public string Id { get; } = sessionId;\n public TTransport Transport { get; } = transport;\n public UserIdClaim? UserIdClaim { get; } = userId;\n\n public CancellationToken SessionClosed => _disposeCts.Token;\n\n public bool IsActive => !SessionClosed.IsCancellationRequested && _referenceCount > 0;\n public long LastActivityTicks { get; private set; } = timeProvider.GetTimestamp();\n\n private TimeProvider TimeProvider => timeProvider;\n\n public IMcpServer? Server { get; set; }\n public Task? ServerRunTask { get; set; }\n\n public IDisposable AcquireReference()\n {\n Interlocked.Increment(ref _referenceCount);\n return new UnreferenceDisposable(this);\n }\n\n public bool TryStartGetRequest() => Interlocked.Exchange(ref _getRequestStarted, 1) == 0;\n\n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n\n if (ServerRunTask is not null)\n {\n await ServerRunTask;\n }\n }\n catch (OperationCanceledException)\n {\n }\n finally\n {\n try\n {\n if (Server is not null)\n {\n await Server.DisposeAsync();\n }\n }\n finally\n {\n await Transport.DisposeAsync();\n _disposeCts.Dispose();\n }\n }\n }\n\n public bool HasSameUserId(ClaimsPrincipal user)\n => UserIdClaim == StreamableHttpHandler.GetUserIdClaim(user);\n\n private sealed class UnreferenceDisposable(HttpMcpSession session) : IDisposable\n {\n public void Dispose()\n {\n if (Interlocked.Decrement(ref session._referenceCount) == 0)\n {\n session.LastActivityTicks = session.TimeProvider.GetTimestamp();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Tool.cs", "using System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a tool that the server is capable of calling.\n/// \npublic sealed class Tool : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the tool.\n /// \n /// \n /// \n /// This description helps the AI model understand what the tool does and when to use it.\n /// It should be clear, concise, and accurately describe the tool's purpose and functionality.\n /// \n /// \n /// The description is typically presented to AI models to help them determine when\n /// and how to use the tool based on user requests.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a JSON Schema object defining the expected parameters for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema typically defines the properties (parameters) that the tool accepts, \n /// their types, and which ones are required. This helps AI models understand\n /// how to structure their calls to the tool.\n /// \n /// \n /// If not explicitly set, a default minimal schema of {\"type\":\"object\"} is used.\n /// \n /// \n [JsonPropertyName(\"inputSchema\")]\n public JsonElement InputSchema \n { \n get => field; \n set\n {\n if (!McpJsonUtilities.IsValidMcpToolSchema(value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool input JSON schema.\", nameof(InputSchema));\n }\n\n field = value;\n }\n\n } = McpJsonUtilities.DefaultMcpToolSchema;\n\n /// \n /// Gets or sets a JSON Schema object defining the expected structured outputs for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema should describe the shape of the data as returned in .\n /// \n /// \n [JsonPropertyName(\"outputSchema\")]\n public JsonElement? OutputSchema\n {\n get => field;\n set\n {\n if (value is not null && !McpJsonUtilities.IsValidMcpToolSchema(value.Value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool output JSON schema.\", nameof(OutputSchema));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets optional additional tool information and behavior hints.\n /// \n /// \n /// These annotations provide metadata about the tool's behavior, such as whether it's read-only,\n /// destructive, idempotent, or operates in an open world. They also can include a human-readable title.\n /// Note that these are hints and should not be relied upon for security decisions.\n /// \n [JsonPropertyName(\"annotations\")]\n public ToolAnnotations? Annotations { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/dd75c45c123055baacd7aa4418f425f412797a29/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs\n// and then modified to build on netstandard2.0.\n\n#if !NET\nusing System.Buffers;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Provides a handler used by the language compiler to process interpolated strings into instances.\n internal ref struct DefaultInterpolatedStringHandler\n {\n // Implementation note:\n // As this type lives in CompilerServices and is only intended to be targeted by the compiler,\n // public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input\n // when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException.\n\n /// Expected average length of formatted data used for an individual interpolation expression result.\n /// \n /// This is inherited from string.Format, and could be changed based on further data.\n /// string.Format actually uses `format.Length + args.Length * 8`, but format.Length\n /// includes the format items themselves, e.g. \"{0}\", and since it's rare to have double-digit\n /// numbers of items, we bump the 8 up to 11 to account for the three extra characters in \"{d}\",\n /// since the compiler-provided base length won't include the equivalent character count.\n /// \n private const int GuessedLengthPerHole = 11;\n /// Minimum size array to rent from the pool.\n /// Same as stack-allocation size used today by string.Format.\n private const int MinimumArrayPoolLength = 256;\n\n /// Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.\n private readonly IFormatProvider? _provider;\n /// Array rented from the array pool and used to back .\n private char[]? _arrayToReturnToPool;\n /// The span to write into.\n private Span _chars;\n /// Position at which to write the next character.\n private int _pos;\n /// Whether provides an ICustomFormatter.\n /// \n /// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive\n /// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field\n /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider\n /// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a\n /// formatter, we pay for the extra interface call on each AppendFormatted that needs it.\n /// \n private readonly bool _hasCustomFormatter;\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)\n {\n _provider = null;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = false;\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)\n {\n _provider = provider;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer)\n {\n _provider = provider;\n _chars = initialBuffer;\n _arrayToReturnToPool = null;\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Derives a default length with which to seed the handler.\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant\n internal static int GetDefaultLength(int literalLength, int formattedCount) =>\n Math.Max(MinimumArrayPoolLength, literalLength + (formattedCount * GuessedLengthPerHole));\n\n /// Gets the built .\n /// The built string.\n public override string ToString() => Text.ToString();\n\n /// Gets the built and clears the handler.\n /// The built string.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after\n /// is called on any one of them.\n /// \n public string ToStringAndClear()\n {\n string result = Text.ToString();\n Clear();\n return result;\n }\n\n /// Clears the handler.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after \n /// is called on any one of them.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Clear()\n {\n char[]? toReturn = _arrayToReturnToPool;\n\n // Defensive clear\n _arrayToReturnToPool = null;\n _chars = default;\n _pos = 0;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n /// Gets a span of the characters appended to the handler.\n public ReadOnlySpan Text => _chars.Slice(0, _pos);\n\n /// Writes the specified string to the handler.\n /// The string to write.\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void AppendLiteral(string value)\n {\n if (value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopyString(value);\n }\n }\n\n #region AppendFormatted\n // Design note:\n // The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression;\n // if it can't find an appropriate overload, for handlers in general it'll simply fail to compile.\n // (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to\n // its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case,\n // interpolated strings will still work, but it has the downside that a developer generally won't know\n // if the fallback is happening and they're paying more.)\n //\n // At a minimum, then, we would need an overload that accepts:\n // (object value, int alignment = 0, string? format = null)\n // Such an overload would provide the same expressiveness as string.Format. However, this has several\n // shortcomings:\n // - Every value type in an interpolation expression would be boxed.\n // - ReadOnlySpan could not be used in interpolation expressions.\n // - Every AppendFormatted call would have three arguments at the call site, bloating the IL further.\n // - Every invocation would be more expensive, due to lack of specialization, every call needing to account\n // for alignment and format, etc.\n //\n // To address that, we could just have overloads for T and ReadOnlySpan:\n // (T)\n // (T, int alignment)\n // (T, string? format)\n // (T, int alignment, string? format)\n // (ReadOnlySpan)\n // (ReadOnlySpan, int alignment)\n // (ReadOnlySpan, string? format)\n // (ReadOnlySpan, int alignment, string? format)\n // but this also has shortcomings:\n // - Some expressions that would have worked with an object overload will now force a fallback to string.Format\n // (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler\n // can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully\n // be passed as an argument of type `object` but not of type `T`.\n // - Reference types get no benefit from going through the generic code paths, and actually incur some overheads\n // from doing so.\n // - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate\n // at compile time for value types but don't (currently) if the Nullable goes through the same code paths\n // (see https://github.com/dotnet/runtime/issues/50915).\n //\n // We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common handler\n // and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads for each of:\n // (T, ...) where T : struct\n // (T?, ...) where T : struct\n // (object, ...)\n // (ReadOnlySpan, ...)\n // (string, ...)\n // but this also has shortcomings, most importantly:\n // - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object overload.\n // This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, so without those\n // they'd all map to the object overloads as well.\n // - Any reference type with an implicit cast to ROS will fail to compile due to ambiguities between the overloads. string\n // is one such type, hence needing dedicated overloads for it that can be bound to more tightly.\n //\n // A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, would be the set:\n // (T, ...) with no constraint\n // (ReadOnlySpan) and (ReadOnlySpan, int)\n // (object, int alignment = 0, string? format = null)\n // (string) and (string, int)\n // This would address most of the concerns, at the expense of:\n // - Most reference types going through the generic code paths and so being a bit more expensive.\n // - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed.\n // We could choose to add a T? where T : struct set of overloads if necessary.\n // Strings don't require their own overloads here, but as they're expected to be very common and as we can\n // optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't\n // need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them.\n //\n // Hole values are formatted according to the following policy:\n // 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if the value is null).\n // 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat.\n // 3. If the type implements IFormattable, use IFormattable.ToString.\n // 4. Otherwise, use object.ToString.\n // This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this doesn't\n // apply is ReadOnlySpan, which isn't supported by either string.Format nor StringBuilder.AppendFormat, but more\n // importantly which can't be boxed to be passed to ICustomFormatter.Format.\n\n #region AppendFormatted T\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The type of the value to write.\n public void AppendFormatted(T value)\n {\n // This method could delegate to AppendFormatted with a null format, but explicitly passing\n // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined,\n // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format.\n\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n return;\n }\n\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n public void AppendFormatted(T value, string? format)\n {\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format);\n return;\n }\n\n // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter\n // requires the former. For value types, it won't matter as the type checks devolve into\n // JIT-time constants. For reference types, they're more likely to implement IFormattable\n // than they are to implement ISpanFormattable: if they don't implement either, we save an\n // interface check over first checking for ISpanFormattable and then for IFormattable, and\n // if it only implements IFormattable, we come out even: only if it implements both do we\n // end up paying for an extra interface check.\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment)\n {\n int startingPos = _pos;\n AppendFormatted(value);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment, string? format)\n {\n int startingPos = _pos;\n AppendFormatted(value, format);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n #endregion\n\n #region AppendFormatted ReadOnlySpan\n /// Writes the specified character span to the handler.\n /// The span to write.\n public void AppendFormatted(scoped ReadOnlySpan value)\n {\n // Fast path for when the value fits in the current buffer\n if (value.TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopySpan(value);\n }\n }\n\n /// Writes the specified string of chars to the handler.\n /// The span to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(scoped ReadOnlySpan value, int alignment = 0, string? format = null)\n {\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingRequired = alignment - value.Length;\n if (paddingRequired <= 0)\n {\n // The value is as large or larger than the required amount of padding,\n // so just write the value.\n AppendFormatted(value);\n return;\n }\n\n // Write the value along with the appropriate padding.\n EnsureCapacityForAdditionalChars(value.Length + paddingRequired);\n if (leftAlign)\n {\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n }\n else\n {\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n #endregion\n\n #region AppendFormatted string\n /// Writes the specified value to the handler.\n /// The value to write.\n public void AppendFormatted(string? value)\n {\n // Fast-path for no custom formatter and a non-null string that fits in the current destination buffer.\n if (!_hasCustomFormatter &&\n value is not null &&\n value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n AppendFormattedSlow(value);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// \n /// Slow path to handle a custom formatter, potentially null value,\n /// or a string that doesn't fit in the current buffer.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendFormattedSlow(string? value)\n {\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n }\n else if (value is not null)\n {\n EnsureCapacityForAdditionalChars(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>\n // Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload\n // simply to disambiguate between ROS and object, just in case someone does specify a format, as\n // string is implicitly convertible to both. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n\n #region AppendFormatted object\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>\n // This overload is expected to be used rarely, only if either a) something strongly typed as object is\n // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It\n // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n #endregion\n\n /// Gets whether the provider provides a custom formatter.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites\n internal static bool HasCustomFormatter(IFormatProvider provider)\n {\n Debug.Assert(provider is not null);\n Debug.Assert(provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, \"Expected CultureInfo to not provide a custom formatter\");\n return\n provider!.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case\n provider.GetFormat(typeof(ICustomFormatter)) != null;\n }\n\n /// Formats the value using the custom formatter from the provider.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendCustomFormatter(T value, string? format)\n {\n // This case is very rare, but we need to handle it prior to the other checks in case\n // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.\n // We do the cast here rather than in the ctor, even though this could be executed multiple times per\n // formatting, to make the cast pay for play.\n Debug.Assert(_hasCustomFormatter);\n Debug.Assert(_provider != null);\n\n ICustomFormatter? formatter = (ICustomFormatter?)_provider!.GetFormat(typeof(ICustomFormatter));\n Debug.Assert(formatter != null, \"An incorrectly written provider said it implemented ICustomFormatter, and then didn't\");\n\n if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted)\n {\n AppendLiteral(customFormatted);\n }\n }\n\n /// Handles adding any padding required for aligning a formatted value in an interpolation expression.\n /// The position at which the written value started.\n /// Non-zero minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)\n {\n Debug.Assert(startingPos >= 0 && startingPos <= _pos);\n Debug.Assert(alignment != 0);\n\n int charsWritten = _pos - startingPos;\n\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingNeeded = alignment - charsWritten;\n if (paddingNeeded > 0)\n {\n EnsureCapacityForAdditionalChars(paddingNeeded);\n\n if (leftAlign)\n {\n _chars.Slice(_pos, paddingNeeded).Fill(' ');\n }\n else\n {\n _chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded));\n _chars.Slice(startingPos, paddingNeeded).Fill(' ');\n }\n\n _pos += paddingNeeded;\n }\n }\n\n /// Ensures has the capacity to store beyond .\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void EnsureCapacityForAdditionalChars(int additionalChars)\n {\n if (_chars.Length - _pos < additionalChars)\n {\n Grow(additionalChars);\n }\n }\n\n /// Fallback for fast path in when there's not enough space in the destination.\n /// The string to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopyString(string value)\n {\n Grow(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Fallback for for when not enough space exists in the current buffer.\n /// The span to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopySpan(scoped ReadOnlySpan value)\n {\n Grow(value.Length);\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Grows to have the capacity to store at least beyond .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow(int additionalChars)\n {\n // This method is called when the remaining space (_chars.Length - _pos) is\n // insufficient to store a specific number of additional characters. Thus, we\n // need to grow to at least that new total. GrowCore will handle growing by more\n // than that if possible.\n Debug.Assert(additionalChars > _chars.Length - _pos);\n GrowCore((uint)_pos + (uint)additionalChars);\n }\n\n /// Grows the size of .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow()\n {\n // This method is called when the remaining space in _chars isn't sufficient to continue\n // the operation. Thus, we need at least one character beyond _chars.Length. GrowCore\n // will handle growing by more than that if possible.\n GrowCore((uint)_chars.Length + 1);\n }\n\n /// Grow the size of to at least the specified .\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines\n private void GrowCore(uint requiredMinCapacity)\n {\n // We want the max of how much space we actually required and doubling our capacity (without going beyond the max allowed length). We\n // also want to avoid asking for small arrays, to reduce the number of times we need to grow, and since we're working with unsigned\n // ints that could technically overflow if someone tried to, for example, append a huge string to a huge string, we also clamp to int.MaxValue.\n // Even if the array creation fails in such a case, we may later fail in ToStringAndClear.\n\n const int StringMaxLength = 0x3FFFFFDF;\n uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, StringMaxLength));\n int arraySize = (int)Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue);\n\n char[] newArray = ArrayPool.Shared.Rent(arraySize);\n _chars.Slice(0, _pos).CopyTo(newArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = newArray;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n private static uint Clamp(uint value, uint min, uint max)\n {\n Debug.Assert(min <= max);\n\n if (value < min)\n {\n return min;\n }\n else if (value > max)\n {\n return max;\n }\n\n return value;\n }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ProgressToken.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a progress token, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct ProgressToken : IEquatable\n{\n /// The token, either a string or a boxed long or null.\n private readonly object? _token;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(string value)\n {\n Throw.IfNull(value);\n _token = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(long value)\n {\n // Box the long. Progress tokens are almost always strings in practice, so this should be rare.\n _token = value;\n }\n\n /// Gets the underlying object for this token.\n /// This will either be a , a boxed , or .\n public object? Token => _token;\n\n /// \n public override string? ToString() =>\n _token is string stringValue ? stringValue :\n _token is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n null;\n\n /// \n public bool Equals(ProgressToken other) => Equals(_token, other._token);\n\n /// \n public override bool Equals(object? obj) => obj is ProgressToken other && Equals(other);\n\n /// \n public override int GetHashCode() => _token?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(ProgressToken left, ProgressToken right) => left.Equals(right);\n\n /// \n public static bool operator !=(ProgressToken left, ProgressToken right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"progressToken must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressToken value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._token)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/samples/EverythingServer/Prompts/ComplexPromptType.cs", "using EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class ComplexPromptType\n{\n [McpServerPrompt(Name = \"complex_prompt\"), Description(\"A prompt with arguments\")]\n public static IEnumerable ComplexPrompt(\n [Description(\"Temperature setting\")] int temperature,\n [Description(\"Output style\")] string? style = null)\n {\n return [\n new ChatMessage(ChatRole.User,$\"This is a complex prompt with arguments: temperature={temperature}, style={style}\"),\n new ChatMessage(ChatRole.Assistant, \"I understand. You've provided a complex prompt with temperature and style arguments. How would you like me to proceed?\"),\n new ChatMessage(ChatRole.User, [new DataContent(TinyImageTool.MCP_TINY_IMAGE)])\n ];\n }\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Program.cs", "using Microsoft.AspNetCore.Authentication.JwtBearer;\nusing Microsoft.IdentityModel.Tokens;\nusing ModelContextProtocol.AspNetCore.Authentication;\nusing ProtectedMCPServer.Tools;\nusing System.Net.Http.Headers;\nusing System.Security.Claims;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nvar serverUrl = \"http://localhost:7071/\";\nvar inMemoryOAuthServerUrl = \"https://localhost:7029\";\n\nbuilder.Services.AddAuthentication(options =>\n{\n options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;\n options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;\n})\n.AddJwtBearer(options =>\n{\n // Configure to validate tokens from our in-memory OAuth server\n options.Authority = inMemoryOAuthServerUrl;\n options.TokenValidationParameters = new TokenValidationParameters\n {\n ValidateIssuer = true,\n ValidateAudience = true,\n ValidateLifetime = true,\n ValidateIssuerSigningKey = true,\n ValidAudience = serverUrl, // Validate that the audience matches the resource metadata as suggested in RFC 8707\n ValidIssuer = inMemoryOAuthServerUrl,\n NameClaimType = \"name\",\n RoleClaimType = \"roles\"\n };\n\n options.Events = new JwtBearerEvents\n {\n OnTokenValidated = context =>\n {\n var name = context.Principal?.Identity?.Name ?? \"unknown\";\n var email = context.Principal?.FindFirstValue(\"preferred_username\") ?? \"unknown\";\n Console.WriteLine($\"Token validated for: {name} ({email})\");\n return Task.CompletedTask;\n },\n OnAuthenticationFailed = context =>\n {\n Console.WriteLine($\"Authentication failed: {context.Exception.Message}\");\n return Task.CompletedTask;\n },\n OnChallenge = context =>\n {\n Console.WriteLine($\"Challenging client to authenticate with Entra ID\");\n return Task.CompletedTask;\n }\n };\n})\n.AddMcp(options =>\n{\n options.ResourceMetadata = new()\n {\n Resource = new Uri(serverUrl),\n ResourceDocumentation = new Uri(\"https://docs.example.com/api/weather\"),\n AuthorizationServers = { new Uri(inMemoryOAuthServerUrl) },\n ScopesSupported = [\"mcp:tools\"],\n };\n});\n\nbuilder.Services.AddAuthorization();\n\nbuilder.Services.AddHttpContextAccessor();\nbuilder.Services.AddMcpServer()\n .WithTools()\n .WithHttpTransport();\n\n// Configure HttpClientFactory for weather.gov API\nbuilder.Services.AddHttpClient(\"WeatherApi\", client =>\n{\n client.BaseAddress = new Uri(\"https://api.weather.gov\");\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n});\n\nvar app = builder.Build();\n\napp.UseAuthentication();\napp.UseAuthorization();\n\n// Use the default MCP policy name that we've configured\napp.MapMcp().RequireAuthorization();\n\nConsole.WriteLine($\"Starting MCP server with authorization at {serverUrl}\");\nConsole.WriteLine($\"Using in-memory OAuth server at {inMemoryOAuthServerUrl}\");\nConsole.WriteLine($\"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource\");\nConsole.WriteLine(\"Press Ctrl+C to stop the server\");\n\napp.Run(serverUrl);\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for all request parameters.\n/// \n/// \n/// See the schema for details.\n/// \npublic abstract class RequestParams\n{\n /// Prevent external derivations.\n private protected RequestParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n [JsonIgnore]\n public ProgressToken? ProgressToken\n {\n get\n {\n if (Meta?[\"progressToken\"] is JsonValue progressToken)\n {\n if (progressToken.TryGetValue(out string? stringValue))\n {\n return new ProgressToken(stringValue);\n }\n\n if (progressToken.TryGetValue(out long longValue))\n {\n return new ProgressToken(longValue);\n }\n }\n\n return null;\n }\n set\n {\n if (value is null)\n {\n Meta?.Remove(\"progressToken\");\n }\n else\n {\n (Meta ??= [])[\"progressToken\"] = value.Value.Token switch\n {\n string s => JsonValue.Create(s),\n long l => JsonValue.Create(l),\n _ => throw new InvalidOperationException(\"ProgressToken must be a string or a long.\")\n };\n }\n }\n }\n}\n"], ["/csharp-sdk/samples/ChatWithTools/Program.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing OpenAI;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\n\nusing var tracerProvider = Sdk.CreateTracerProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddSource(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var metricsProvider = Sdk.CreateMeterProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddMeter(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var loggerFactory = LoggerFactory.Create(builder => builder.AddOpenTelemetry(opt => opt.AddOtlpExporter()));\n\n// Connect to an MCP server\nConsole.WriteLine(\"Connecting client to MCP 'everything' server\");\n\n// Create OpenAI client (or any other compatible with IChatClient)\n// Provide your own OPENAI_API_KEY via an environment variable.\nvar openAIClient = new OpenAIClient(Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")).GetChatClient(\"gpt-4o-mini\");\n\n// Create a sampling client.\nusing IChatClient samplingClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\nvar mcpClient = await McpClientFactory.CreateAsync(\n new StdioClientTransport(new()\n {\n Command = \"npx\",\n Arguments = [\"-y\", \"--verbose\", \"@modelcontextprotocol/server-everything\"],\n Name = \"Everything\",\n }),\n clientOptions: new()\n {\n Capabilities = new() { Sampling = new() { SamplingHandler = samplingClient.CreateSamplingHandler() } },\n },\n loggerFactory: loggerFactory);\n\n// Get all available tools\nConsole.WriteLine(\"Tools available:\");\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\" {tool}\");\n}\n\nConsole.WriteLine();\n\n// Create an IChatClient that can use the tools.\nusing IChatClient chatClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseFunctionInvocation()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\n// Have a conversation, making all tools available to the LLM.\nList messages = [];\nwhile (true)\n{\n Console.Write(\"Q: \");\n messages.Add(new(ChatRole.User, Console.ReadLine()));\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, new() { Tools = [.. tools] }))\n {\n Console.Write(update);\n updates.Add(update);\n }\n Console.WriteLine();\n\n messages.AddMessages(updates);\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace QuickstartWeatherServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public static async Task GetAlerts(\n HttpClient client,\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public static async Task GetForecast(\n HttpClient client,\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/IO/StreamExtensions.cs", "using ModelContextProtocol;\nusing System.Buffers;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n#if !NET\nnamespace System.IO;\n\ninternal static class StreamExtensions\n{\n public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return WriteAsyncCore(stream, buffer, cancellationToken);\n\n static async ValueTask WriteAsyncCore(Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n buffer.Span.CopyTo(array);\n await stream.WriteAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n\n public static ValueTask ReadAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.ReadAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return ReadAsyncCore(stream, buffer, cancellationToken);\n static async ValueTask ReadAsyncCore(Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n int bytesRead = await stream.ReadAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n array.AsSpan(0, bytesRead).CopyTo(buffer.Span);\n return bytesRead;\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n}\n#endif"], ["/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/Server/McpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable resource used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP resource for use in the server (as opposed\n/// to or , which provide the protocol representations of a resource). Instances of \n/// can be added into a to be picked up automatically when\n/// is used to create an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithResourcesFromAssembly and\n/// . The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the URI received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// is used to represent both direct resources (e.g. \"resource://example\") and templated\n/// resources (e.g. \"resource://example/{id}\").\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerResource : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerResource()\n {\n }\n\n /// Gets whether this resource is a URI template with parameters as opposed to a direct resource.\n public bool IsTemplated => ProtocolResourceTemplate.UriTemplate.Contains('{');\n\n /// Gets the protocol type for this instance.\n /// \n /// \n /// The property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n /// \n /// Every valid resource URI is a valid resource URI template, and thus this property always returns an instance.\n /// In contrast, the property may return if the resource template\n /// contains a parameter, in which case the resource template URI is not a valid resource URI.\n /// \n /// \n public abstract ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolResourceTemplate property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n public virtual Resource? ProtocolResource => ProtocolResourceTemplate.AsResource();\n\n /// \n /// Gets the resource, rendering it with the provided request parameters and returning the resource result.\n /// \n /// \n /// The request context containing information about the resource invocation, including any arguments\n /// passed to the resource. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the resource content and messages. If and only if this doesn't match the ,\n /// the method returns .\n /// \n /// is .\n /// The resource implementation returned or an unsupported result type.\n public abstract ValueTask ReadAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerResource Create(\n MethodInfo method, \n object? target = null,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerResource Create(\n AIFunction function,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(function, options);\n\n /// \n public override string ToString() => ProtocolResourceTemplate.UriTemplate;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolResourceTemplate.UriTemplate;\n}\n"], ["/csharp-sdk/samples/EverythingServer/LoggingUpdateMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace EverythingServer;\n\npublic class LoggingUpdateMessageSender(IMcpServer server, Func getMinLevel) : BackgroundService\n{\n readonly Dictionary _loggingLevelMap = new()\n {\n { LoggingLevel.Debug, \"Debug-level message\" },\n { LoggingLevel.Info, \"Info-level message\" },\n { LoggingLevel.Notice, \"Notice-level message\" },\n { LoggingLevel.Warning, \"Warning-level message\" },\n { LoggingLevel.Error, \"Error-level message\" },\n { LoggingLevel.Critical, \"Critical-level message\" },\n { LoggingLevel.Alert, \"Alert-level message\" },\n { LoggingLevel.Emergency, \"Emergency-level message\" }\n };\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n var newLevel = (LoggingLevel)Random.Shared.Next(_loggingLevelMap.Count);\n\n var message = new\n {\n Level = newLevel.ToString().ToLower(),\n Data = _loggingLevelMap[newLevel],\n };\n\n if (newLevel > getMinLevel())\n {\n await server.SendNotificationAsync(\"notifications/message\", message, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(15000, stoppingToken);\n }\n }\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as tools in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as tools that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to when the tool is invoked rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided when the tool is invoked rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerToolAttribute : Attribute\n{\n // Defaults based on the spec\n private const bool DestructiveDefault = true;\n private const bool IdempotentDefault = false;\n private const bool OpenWorldDefault = true;\n private const bool ReadOnlyDefault = false;\n\n // Nullable backing fields so we can distinguish\n internal bool? _destructive;\n internal bool? _idempotent;\n internal bool? _openWorld;\n internal bool? _readOnly;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerToolAttribute()\n {\n }\n\n /// Gets the name of the tool.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Destructive \n {\n get => _destructive ?? DestructiveDefault; \n set => _destructive = value; \n }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Idempotent \n {\n get => _idempotent ?? IdempotentDefault;\n set => _idempotent = value; \n }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool OpenWorld\n {\n get => _openWorld ?? OpenWorldDefault; \n set => _openWorld = value; \n }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool ReadOnly \n {\n get => _readOnly ?? ReadOnlyDefault; \n set => _readOnly = value; \n }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerHandlers.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a container for handlers used in the creation of an MCP server.\n/// \n/// \n/// \n/// This class provides a centralized collection of delegates that implement various capabilities of the Model Context Protocol.\n/// Each handler in this class corresponds to a specific endpoint in the Model Context Protocol and\n/// is responsible for processing a particular type of request. The handlers are used to customize\n/// the behavior of the MCP server by providing implementations for the various protocol operations.\n/// \n/// \n/// Handlers can be configured individually using the extension methods in \n/// such as and\n/// .\n/// \n/// \n/// When a client sends a request to the server, the appropriate handler is invoked to process the\n/// request and produce a response according to the protocol specification. Which handler is selected\n/// is done based on an ordinal, case-sensitive string comparison.\n/// \n/// \npublic sealed class McpServerHandlers\n{\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// \n /// \n /// This handler works alongside any tools defined in the collection.\n /// Tools from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the collection.\n /// The handler should implement logic to execute the requested tool and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available prompts when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more prompts.\n /// \n /// \n /// This handler works alongside any prompts defined in the collection.\n /// Prompts from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt that isn't found in the collection.\n /// The handler should implement logic to fetch or generate the requested prompt and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resource templates when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resource templates.\n /// \n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resources when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resources.\n /// \n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests the content of a specific resource identified by its URI.\n /// The handler should implement logic to locate and retrieve the requested resource.\n /// \n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler processes auto-completion requests, returning a list of suggestions based on the \n /// reference type and current argument value.\n /// \n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to receive notifications about changes to specific resources or resource patterns.\n /// The handler should implement logic to register the client's interest in the specified resources\n /// and set up the necessary infrastructure to send notifications when those resources change.\n /// \n /// \n /// After a successful subscription, the server should send resource change notifications to the client\n /// whenever a relevant resource is created, updated, or deleted.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to stop receiving notifications about previously subscribed resources.\n /// The handler should implement logic to remove the client's subscriptions to the specified resources\n /// and clean up any associated resources.\n /// \n /// \n /// After a successful unsubscription, the server should no longer send resource change notifications\n /// to the client for the specified resources.\n /// \n /// \n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler processes requests from clients. When set, it enables\n /// clients to control which log messages they receive by specifying a minimum severity threshold.\n /// \n /// \n /// After handling a level change request, the server typically begins sending log messages\n /// at or above the specified level to the client as notifications/message notifications.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n\n /// \n /// Overwrite any handlers in McpServerOptions with non-null handlers from this instance.\n /// \n /// \n /// \n internal void OverwriteWithSetHandlers(McpServerOptions options)\n {\n PromptsCapability? promptsCapability = options.Capabilities?.Prompts;\n if (ListPromptsHandler is not null || GetPromptHandler is not null)\n {\n promptsCapability ??= new();\n promptsCapability.ListPromptsHandler = ListPromptsHandler ?? promptsCapability.ListPromptsHandler;\n promptsCapability.GetPromptHandler = GetPromptHandler ?? promptsCapability.GetPromptHandler;\n }\n\n ResourcesCapability? resourcesCapability = options.Capabilities?.Resources;\n if (ListResourcesHandler is not null ||\n ReadResourceHandler is not null)\n {\n resourcesCapability ??= new();\n resourcesCapability.ListResourceTemplatesHandler = ListResourceTemplatesHandler ?? resourcesCapability.ListResourceTemplatesHandler;\n resourcesCapability.ListResourcesHandler = ListResourcesHandler ?? resourcesCapability.ListResourcesHandler;\n resourcesCapability.ReadResourceHandler = ReadResourceHandler ?? resourcesCapability.ReadResourceHandler;\n\n if (SubscribeToResourcesHandler is not null || UnsubscribeFromResourcesHandler is not null)\n {\n resourcesCapability.SubscribeToResourcesHandler = SubscribeToResourcesHandler ?? resourcesCapability.SubscribeToResourcesHandler;\n resourcesCapability.UnsubscribeFromResourcesHandler = UnsubscribeFromResourcesHandler ?? resourcesCapability.UnsubscribeFromResourcesHandler;\n resourcesCapability.Subscribe = true;\n }\n }\n\n ToolsCapability? toolsCapability = options.Capabilities?.Tools;\n if (ListToolsHandler is not null || CallToolHandler is not null)\n {\n toolsCapability ??= new();\n toolsCapability.ListToolsHandler = ListToolsHandler ?? toolsCapability.ListToolsHandler;\n toolsCapability.CallToolHandler = CallToolHandler ?? toolsCapability.CallToolHandler;\n }\n\n LoggingCapability? loggingCapability = options.Capabilities?.Logging;\n if (SetLoggingLevelHandler is not null)\n {\n loggingCapability ??= new();\n loggingCapability.SetLoggingLevelHandler = SetLoggingLevelHandler;\n }\n\n CompletionsCapability? completionsCapability = options.Capabilities?.Completions;\n if (CompleteHandler is not null)\n {\n completionsCapability ??= new();\n completionsCapability.CompleteHandler = CompleteHandler;\n }\n\n options.Capabilities ??= new();\n options.Capabilities.Prompts = promptsCapability;\n options.Capabilities.Resources = resourcesCapability;\n options.Capabilities.Tools = toolsCapability;\n options.Capabilities.Logging = loggingCapability;\n options.Capabilities.Completions = completionsCapability;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StreamClientTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides an implemented around a pair of input/output streams.\n/// \n/// \n/// This transport is useful for scenarios where you already have established streams for communication,\n/// such as custom network protocols, pipe connections, or for testing purposes. It works with any\n/// readable and writable streams.\n/// \npublic sealed class StreamClientTransport : IClientTransport\n{\n private readonly Stream _serverInput;\n private readonly Stream _serverOutput;\n private readonly ILoggerFactory? _loggerFactory;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The stream representing the connected server's input. \n /// Writes to this stream will be sent to the server.\n /// \n /// \n /// The stream representing the connected server's output.\n /// Reads from this stream will receive messages from the server.\n /// \n /// A logger factory for creating loggers.\n public StreamClientTransport(\n Stream serverInput, Stream serverOutput, ILoggerFactory? loggerFactory = null)\n {\n Throw.IfNull(serverInput);\n Throw.IfNull(serverOutput);\n\n _serverInput = serverInput;\n _serverOutput = serverOutput;\n _loggerFactory = loggerFactory;\n }\n\n /// \n public string Name => \"in-memory-stream\";\n\n /// \n public Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n return Task.FromResult(new StreamClientSessionTransport(\n _serverInput,\n _serverOutput,\n encoding: null,\n \"Client (stream)\",\n _loggerFactory));\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Channels/ChannelExtensions.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading.Channels;\n\ninternal static class ChannelExtensions\n{\n public static async IAsyncEnumerable ReadAllAsync(this ChannelReader reader, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))\n {\n while (reader.TryRead(out var item))\n {\n yield return item;\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/samples/EverythingServer/Tools/LongRunningTool.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class LongRunningTool\n{\n [McpServerTool(Name = \"longRunningOperation\"), Description(\"Demonstrates a long running operation with progress updates\")]\n public static async Task LongRunningOperation(\n IMcpServer server,\n RequestContext context,\n int duration = 10,\n int steps = 5)\n {\n var progressToken = context.Params?.ProgressToken;\n var stepDuration = duration / steps;\n\n for (int i = 1; i <= steps + 1; i++)\n {\n await Task.Delay(stepDuration * 1000);\n \n if (progressToken is not null)\n {\n await server.SendNotificationAsync(\"notifications/progress\", new\n {\n Progress = i,\n Total = steps,\n progressToken\n });\n }\n }\n\n return $\"Long running operation completed. Duration: {duration} seconds. Steps: {steps}.\";\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of tools created with\n/// . They provide control over naming, description,\n/// tool properties, and dependency injection integration.\n/// \n/// \n/// When creating tools programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerToolCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisfied from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Destructive { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Idempotent { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? OpenWorld { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? ReadOnly { get; set; }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerToolCreateOptions Clone() =>\n new McpServerToolCreateOptions\n {\n Services = Services,\n Name = Name,\n Description = Description,\n Title = Title,\n Destructive = Destructive,\n Idempotent = Idempotent,\n OpenWorld = OpenWorld,\n ReadOnly = ReadOnly,\n UseStructuredContent = UseStructuredContent,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessageWithId.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC message used in the Model Context Protocol (MCP) and that includes an ID.\n/// \n/// \n/// In the JSON-RPC protocol, messages with an ID require a response from the receiver.\n/// This includes request messages (which expect a matching response) and response messages\n/// (which include the ID of the original request they're responding to).\n/// The ID is used to correlate requests with their responses, allowing asynchronous\n/// communication where multiple requests can be sent without waiting for responses.\n/// \npublic abstract class JsonRpcMessageWithId : JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessageWithId()\n {\n }\n\n /// \n /// Gets the message identifier.\n /// \n /// \n /// Each ID is expected to be unique within the context of a given session.\n /// \n [JsonPropertyName(\"id\")]\n public RequestId Id { get; init; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/SubscriptionMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\ninternal class SubscriptionMessageSender(IMcpServer server, HashSet subscriptions) : BackgroundService\n{\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n foreach (var uri in subscriptions)\n {\n await server.SendNotificationAsync(\"notifications/resource/updated\",\n new\n {\n Uri = uri,\n }, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(5000, stoppingToken);\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpException.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents an exception that is thrown when an Model Context Protocol (MCP) error occurs.\n/// \n/// \n/// This exception is used to represent failures to do with protocol-level concerns, such as invalid JSON-RPC requests,\n/// invalid parameters, or internal errors. It is not intended to be used for application-level errors.\n/// or from a may be \n/// propagated to the remote endpoint; sensitive information should not be included. If sensitive details need\n/// to be included, a different exception type should be used.\n/// \npublic class McpException : Exception\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpException()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public McpException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n public McpException(string message, Exception? innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// A .\n public McpException(string message, McpErrorCode errorCode) : this(message, null, errorCode)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message, inner exception, and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n /// A .\n public McpException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)\n {\n ErrorCode = errorCode;\n }\n\n /// \n /// Gets the error code associated with this exception.\n /// \n /// \n /// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:\n /// \n /// -32700: Parse error - Invalid JSON received\n /// -32600: Invalid request - The JSON is not a valid Request object\n /// -32601: Method not found - The method does not exist or is not available\n /// -32602: Invalid params - Invalid method parameters\n /// -32603: Internal error - Internal JSON-RPC error\n /// \n /// \n public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;\n}"], ["/csharp-sdk/src/Common/Throw.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace ModelContextProtocol;\n\n/// Provides helper methods for throwing exceptions.\ninternal static class Throw\n{\n // NOTE: Most of these should be replaced with extension statics for the relevant extension\n // type as downlevel polyfills once the C# 14 extension everything feature is available.\n\n public static void IfNull([NotNull] object? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n }\n\n public static void IfNullOrWhiteSpace([NotNull] string? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null || arg.AsSpan().IsWhiteSpace())\n {\n ThrowArgumentNullOrWhiteSpaceException(parameterName);\n }\n }\n\n public static void IfNegative(int arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg < 0)\n {\n Throw(parameterName);\n static void Throw(string? parameterName) => throw new ArgumentOutOfRangeException(parameterName, \"must not be negative.\");\n }\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullOrWhiteSpaceException(string? parameterName)\n {\n if (parameterName is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n\n throw new ArgumentException(\"Value cannot be empty or composed entirely of whitespace.\", parameterName);\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullException(string? parameterName) => throw new ArgumentNullException(parameterName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ITransport.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Server;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a transport mechanism for MCP (Model Context Protocol) communication between clients and servers.\n/// \n/// \n/// \n/// The interface is the core abstraction for bidirectional communication.\n/// It provides methods for sending and receiving messages, abstracting away the underlying transport mechanism\n/// and allowing protocol implementations to be decoupled from communication details.\n/// \n/// \n/// Implementations of handle the serialization, transmission, and reception of\n/// messages over various channels like standard input/output streams and HTTP (Server-Sent Events).\n/// \n/// \n/// While is responsible for establishing a client's connection,\n/// represents an established session. Client implementations typically obtain an\n/// instance by calling .\n/// \n/// \npublic interface ITransport : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Gets a channel reader for receiving messages from the transport.\n /// \n /// \n /// \n /// The provides access to incoming JSON-RPC messages received by the transport.\n /// It returns a which allows consuming messages in a thread-safe manner.\n /// \n /// \n /// The reader will continue to provide messages as long as the transport is connected. When the transport\n /// is disconnected or disposed, the channel will be completed and no more messages will be available after\n /// any already transmitted messages are consumed.\n /// \n /// \n ChannelReader MessageReader { get; }\n\n /// \n /// Sends a JSON-RPC message through the transport.\n /// \n /// The JSON-RPC message to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// \n /// \n /// This method serializes and sends the provided JSON-RPC message through the transport connection.\n /// \n /// \n /// This is a core method used by higher-level abstractions in the MCP protocol implementation.\n /// Most client code should use the higher-level methods provided by ,\n /// , , or ,\n /// rather than accessing this method directly.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcResponse.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A successful response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Response messages are sent in reply to a request message and contain the result of the method execution.\n/// Each response includes the same ID as the original request, allowing the sender to match responses\n/// with their corresponding requests.\n/// \n/// \n/// This class represents a successful response with a result. For error responses, see .\n/// \n/// \npublic sealed class JsonRpcResponse : JsonRpcMessageWithId\n{\n /// \n /// Gets the result of the method invocation.\n /// \n /// \n /// This property contains the result data returned by the server in response to the JSON-RPC method request.\n /// \n [JsonPropertyName(\"result\")]\n public required JsonNode? Result { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResourceTemplate.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource template that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource template defined on an MCP server. It allows\n/// retrieving the resource template's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResourceTemplate\n{\n private readonly IMcpClient _client;\n\n internal McpClientResourceTemplate(IMcpClient client, ResourceTemplate resourceTemplate)\n {\n _client = client;\n ProtocolResourceTemplate = resourceTemplate;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource template,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the URI template of the resource template.\n public string UriTemplate => ProtocolResourceTemplate.UriTemplate;\n\n /// Gets the name of the resource template.\n public string Name => ProtocolResourceTemplate.Name;\n\n /// Gets the title of the resource template.\n public string? Title => ProtocolResourceTemplate.Title;\n\n /// Gets a description of the resource template.\n public string? Description => ProtocolResourceTemplate.Description;\n\n /// Gets a media (MIME) type of the resource template.\n public string? MimeType => ProtocolResourceTemplate.MimeType;\n\n /// \n /// Gets this resource template's content by formatting a URI from the template and supplied arguments\n /// and sending a request to the server.\n /// \n /// A dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource template's result with content and messages.\n public ValueTask ReadAsync(\n IReadOnlyDictionary arguments,\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(UriTemplate, arguments, cancellationToken);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/SseClientTransportOptions.cs", "using ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class SseClientTransportOptions\n{\n /// \n /// Gets or sets the base address of the server for SSE connections.\n /// \n public required Uri Endpoint\n {\n get;\n set\n {\n if (value is null)\n {\n throw new ArgumentNullException(nameof(value), \"Endpoint cannot be null.\");\n }\n if (!value.IsAbsoluteUri)\n {\n throw new ArgumentException(\"Endpoint must be an absolute URI.\", nameof(value));\n }\n if (value.Scheme != Uri.UriSchemeHttp && value.Scheme != Uri.UriSchemeHttps)\n {\n throw new ArgumentException(\"Endpoint must use HTTP or HTTPS scheme.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the transport mode to use for the connection. Defaults to .\n /// \n /// \n /// \n /// When set to (the default), the client will first attempt to use\n /// Streamable HTTP transport and automatically fall back to SSE transport if the server doesn't support it.\n /// \n /// \n /// Streamable HTTP transport specification.\n /// HTTP with SSE transport specification.\n /// \n /// \n public HttpTransportMode TransportMode { get; set; } = HttpTransportMode.AutoDetect;\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets a timeout used to establish the initial connection to the SSE server. Defaults to 30 seconds.\n /// \n /// \n /// This timeout controls how long the client waits for:\n /// \n /// The initial HTTP connection to be established with the SSE server\n /// The endpoint event to be received, which indicates the message endpoint URL\n /// \n /// If the timeout expires before the connection is established, a will be thrown.\n /// \n public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);\n\n /// \n /// Gets custom HTTP headers to include in requests to the SSE server.\n /// \n /// \n /// Use this property to specify custom HTTP headers that should be sent with each request to the server.\n /// \n public IDictionary? AdditionalHeaders { get; set; }\n\n /// \n /// Gets sor sets the authorization provider to use for authentication.\n /// \n public ClientOAuthOptions? OAuth { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as prompts in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as prompts that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerPromptAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPromptAttribute()\n {\n }\n\n /// Gets the name of the prompt.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the prompt.\n public string? Title { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptMessage.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message within the Model Context Protocol (MCP) system, used for communication between clients and AI models.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be\n/// text, images, audio, or embedded resources.\n/// \n/// \n/// This class is similar to , but with enhanced support for embedding resources from the MCP server.\n/// It serves as a core data structure in the MCP message exchange flow, particularly in prompt formation and model responses.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent complete conversations or prompt sequences. They can be converted to and from \n/// objects using the extension methods and\n/// .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptMessage\n{\n /// \n /// Gets or sets the content of the message, which can be text, image, audio, or an embedded resource.\n /// \n /// \n /// The object contains all the message payload, whether it's simple text,\n /// base64-encoded binary data (for images/audio), or a reference to an embedded resource.\n /// The property indicates the specific content type.\n /// \n [JsonPropertyName(\"content\")]\n public ContentBlock Content { get; set; } = new TextContentBlock { Text = \"\" };\n\n /// \n /// Gets or sets the role of the message sender, specifying whether it's from a \"user\" or an \"assistant\".\n /// \n /// \n /// In the Model Context Protocol, each message must have a clear role assignment to maintain\n /// the conversation flow. User messages represent queries or inputs from users, while assistant\n /// messages represent responses generated by AI models.\n /// \n [JsonPropertyName(\"role\")]\n public Role Role { get; set; } = Role.User;\n}\n"], ["/csharp-sdk/samples/EverythingServer/ResourceGenerator.cs", "using ModelContextProtocol.Protocol;\n\nnamespace EverythingServer;\n\nstatic class ResourceGenerator\n{\n private static readonly List _resources = Enumerable.Range(1, 100).Select(i =>\n {\n var uri = $\"test://template/resource/{i}\";\n if (i % 2 != 0)\n {\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"text/plain\",\n Description = $\"Resource {i}: This is a plaintext resource\"\n };\n }\n else\n {\n var buffer = System.Text.Encoding.UTF8.GetBytes($\"Resource {i}: This is a base64 blob\");\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"application/octet-stream\",\n Description = Convert.ToBase64String(buffer)\n };\n }\n }).ToList();\n\n public static IReadOnlyList Resources => _resources;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource defined on an MCP server. It allows\n/// retrieving the resource's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResource\n{\n private readonly IMcpClient _client;\n\n internal McpClientResource(IMcpClient client, Resource resource)\n {\n _client = client;\n ProtocolResource = resource;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Resource ProtocolResource { get; }\n\n /// Gets the URI of the resource.\n public string Uri => ProtocolResource.Uri;\n\n /// Gets the name of the resource.\n public string Name => ProtocolResource.Name;\n\n /// Gets the title of the resource.\n public string? Title => ProtocolResource.Title;\n\n /// Gets a description of the resource.\n public string? Description => ProtocolResource.Description;\n\n /// Gets a media (MIME) type of the resource.\n public string? MimeType => ProtocolResource.MimeType;\n\n /// \n /// Gets this resource's content by sending a request to the server.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource's result with content and messages.\n /// \n /// \n /// This is a convenience method that internally calls .\n /// \n /// \n public ValueTask ReadAsync(\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(Uri, cancellationToken);\n}"], ["/csharp-sdk/src/Common/Polyfills/System/PasteArguments.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/d2650b6ae7023a2d9d2c74c56116f1f18472ab04/src/libraries/System.Private.CoreLib/src/System/PasteArguments.cs\n// and changed from using ValueStringBuilder to StringBuilder.\n\n#if !NET\nusing System.Text;\n\nnamespace System;\n\ninternal static partial class PasteArguments\n{\n internal static void AppendArgument(StringBuilder stringBuilder, string argument)\n {\n if (stringBuilder.Length != 0)\n {\n stringBuilder.Append(' ');\n }\n\n // Parsing rules for non-argv[0] arguments:\n // - Backslash is a normal character except followed by a quote.\n // - 2N backslashes followed by a quote ==> N literal backslashes followed by unescaped quote\n // - 2N+1 backslashes followed by a quote ==> N literal backslashes followed by a literal quote\n // - Parsing stops at first whitespace outside of quoted region.\n // - (post 2008 rule): A closing quote followed by another quote ==> literal quote, and parsing remains in quoting mode.\n if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument))\n {\n // Simple case - no quoting or changes needed.\n stringBuilder.Append(argument);\n }\n else\n {\n stringBuilder.Append(Quote);\n int idx = 0;\n while (idx < argument.Length)\n {\n char c = argument[idx++];\n if (c == Backslash)\n {\n int numBackSlash = 1;\n while (idx < argument.Length && argument[idx] == Backslash)\n {\n idx++;\n numBackSlash++;\n }\n\n if (idx == argument.Length)\n {\n // We'll emit an end quote after this so must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2);\n }\n else if (argument[idx] == Quote)\n {\n // Backslashes will be followed by a quote. Must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2 + 1);\n stringBuilder.Append(Quote);\n idx++;\n }\n else\n {\n // Backslash will not be followed by a quote, so emit as normal characters.\n stringBuilder.Append(Backslash, numBackSlash);\n }\n\n continue;\n }\n\n if (c == Quote)\n {\n // Escape the quote so it appears as a literal. This also guarantees that we won't end up generating a closing quote followed\n // by another quote (which parses differently pre-2008 vs. post-2008.)\n stringBuilder.Append(Backslash);\n stringBuilder.Append(Quote);\n continue;\n }\n\n stringBuilder.Append(c);\n }\n\n stringBuilder.Append(Quote);\n }\n }\n\n private static bool ContainsNoWhitespaceOrQuotes(string s)\n {\n for (int i = 0; i < s.Length; i++)\n {\n char c = s[i];\n if (char.IsWhiteSpace(c) || c == Quote)\n {\n return false;\n }\n }\n\n return true;\n }\n\n private const char Quote = '\\\"';\n private const char Backslash = '\\\\';\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrimitiveCollection.cs", "using System.Collections;\nusing System.Collections.Concurrent;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their names.\n/// Specifies the type of primitive stored in the collection.\npublic class McpServerPrimitiveCollection : ICollection, IReadOnlyCollection\n where T : IMcpServerPrimitive\n{\n /// Concurrent dictionary of primitives, indexed by their names.\n private readonly ConcurrentDictionary _primitives;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPrimitiveCollection(IEqualityComparer? keyComparer = null)\n {\n _primitives = new(keyComparer ?? EqualityComparer.Default);\n }\n\n /// Occurs when the collection is changed.\n /// \n /// By default, this is raised when a primitive is added or removed. However, a derived implementation\n /// may raise this event for other reasons, such as when a primitive is modified.\n /// \n public event EventHandler? Changed;\n\n /// Gets the number of primitives in the collection.\n public int Count => _primitives.Count;\n\n /// Gets whether there are any primitives in the collection.\n public bool IsEmpty => _primitives.IsEmpty;\n\n /// Raises if there are registered handlers.\n protected void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);\n\n /// Gets the with the specified from the collection.\n /// The name of the primitive to retrieve.\n /// The with the specified name.\n /// is .\n /// An primitive with the specified name does not exist in the collection.\n public T this[string name]\n {\n get\n {\n Throw.IfNull(name);\n return _primitives[name];\n }\n }\n\n /// Clears all primitives from the collection.\n public virtual void Clear()\n {\n _primitives.Clear();\n RaiseChanged();\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// is .\n /// A primitive with the same name as already exists in the collection.\n public void Add(T primitive)\n {\n if (!TryAdd(primitive))\n {\n throw new ArgumentException($\"A primitive with the same name '{primitive.Id}' already exists in the collection.\", nameof(primitive));\n }\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// if the primitive was added; otherwise, .\n /// is .\n public virtual bool TryAdd(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool added = _primitives.TryAdd(primitive.Id, primitive);\n if (added)\n {\n RaiseChanged();\n }\n\n return added;\n }\n\n /// Removes the specified primitivefrom the collection.\n /// The primitive to be removed from the collection.\n /// \n /// if the primitive was found in the collection and removed; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool Remove(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool removed = ((ICollection>)_primitives).Remove(new(primitive.Id, primitive));\n if (removed)\n {\n RaiseChanged();\n }\n\n return removed;\n }\n\n /// Attempts to get the primitive with the specified name from the collection.\n /// The name of the primitive to retrieve.\n /// The primitive, if found; otherwise, .\n /// \n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool TryGetPrimitive(string name, [NotNullWhen(true)] out T? primitive)\n {\n Throw.IfNull(name);\n return _primitives.TryGetValue(name, out primitive);\n }\n\n /// Checks if a specific primitive is present in the collection of primitives.\n /// The primitive to search for in the collection.\n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// is .\n public virtual bool Contains(T primitive)\n {\n Throw.IfNull(primitive);\n return ((ICollection>)_primitives).Contains(new(primitive.Id, primitive));\n }\n\n /// Gets the names of all of the primitives in the collection.\n public virtual ICollection PrimitiveNames => _primitives.Keys;\n\n /// Creates an array containing all of the primitives in the collection.\n /// An array containing all of the primitives in the collection.\n public virtual T[] ToArray() => _primitives.Values.ToArray();\n\n /// \n public virtual void CopyTo(T[] array, int arrayIndex)\n {\n Throw.IfNull(array);\n\n _primitives.Values.CopyTo(array, arrayIndex);\n }\n\n /// \n public virtual IEnumerator GetEnumerator()\n {\n foreach (var entry in _primitives)\n {\n yield return entry.Value;\n }\n }\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n bool ICollection.IsReadOnly => false;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolResult.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// \n/// Any errors that originate from the tool should be reported inside the result\n/// object, with set to true, rather than as a .\n/// \n/// \n/// However, any errors in finding the tool, an error indicating that the\n/// server does not support tool calls, or any other exceptional conditions,\n/// should be reported as an MCP error response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CallToolResult : Result\n{\n /// \n /// Gets or sets the response content from the tool call.\n /// \n [JsonPropertyName(\"content\")]\n public IList Content { get; set; } = [];\n\n /// \n /// Gets or sets an optional JSON object representing the structured result of the tool call.\n /// \n [JsonPropertyName(\"structuredContent\")]\n public JsonNode? StructuredContent { get; set; }\n\n /// \n /// Gets or sets an indication of whether the tool call was unsuccessful.\n /// \n /// \n /// When set to , it signifies that the tool execution failed.\n /// Tool errors are reported with this property set to and details in the \n /// property, rather than as protocol-level errors. This allows LLMs to see that an error occurred\n /// and potentially self-correct in subsequent requests.\n /// \n [JsonPropertyName(\"isError\")]\n public bool? IsError { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingCapability.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Client;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to generate text or other content using an AI model.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to sampling requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to generate content\n/// using an AI model. The client must set a to process these requests.\n/// \n/// \npublic sealed class SamplingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to generate content\n /// using an AI model. The client must set this property for the sampling capability to work.\n /// \n /// \n /// The handler receives message parameters, a progress reporter for updates, and a \n /// cancellation token. It should return a containing the \n /// generated content.\n /// \n /// \n /// You can create a handler using the extension\n /// method with any implementation of .\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SamplingHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceTemplate.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource template that the server is capable of reading.\n/// \n/// \n/// Resource templates provide metadata about resources available on the server,\n/// including how to construct URIs for those resources.\n/// \npublic sealed class ResourceTemplate : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI template (according to RFC 6570) that can be used to construct resource URIs.\n /// \n [JsonPropertyName(\"uriTemplate\")]\n public required string UriTemplate { get; init; }\n\n /// \n /// Gets or sets a description of what this resource template represents.\n /// \n /// \n /// \n /// This description helps clients understand the purpose and content of resources\n /// that can be generated from this template. It can be used by client applications\n /// to provide context about available resource types or to display in user interfaces.\n /// \n /// \n /// For AI models, this description can serve as a hint about when and how to use\n /// the resource template, enhancing the model's ability to generate appropriate URIs.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource template, if known.\n /// \n /// \n /// \n /// Specifies the expected format of resources that can be generated from this template.\n /// This helps clients understand what type of content to expect when accessing resources\n /// created using this template.\n /// \n /// \n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, or \"application/json\" for JSON data.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource template.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource template. Clients can use this information to filter\n /// or prioritize resource templates for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n\n /// Gets whether contains any template expressions.\n [JsonIgnore]\n public bool IsTemplated => UriTemplate.Contains('{');\n\n /// Converts the into a .\n /// A if is ; otherwise, .\n public Resource? AsResource()\n {\n if (IsTemplated)\n {\n return null;\n }\n\n return new()\n {\n Uri = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n Annotations = Annotations,\n Meta = Meta,\n };\n }\n}"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/SampleLlmTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses dependency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n ChatOptions options = new()\n {\n Instructions = \"You are a helpful test server.\",\n MaxOutputTokens = maxTokens,\n Temperature = 0.7f,\n };\n\n var samplingResponse = await thisServer.AsSamplingChatClient().GetResponseAsync(prompt, options, cancellationToken);\n\n return $\"LLM sampling result: {samplingResponse}\";\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcError.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an error response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Error responses are sent when a request cannot be fulfilled or encounters an error during processing.\n/// Like successful responses, error messages include the same ID as the original request, allowing the\n/// sender to match errors with their corresponding requests.\n/// \n/// \n/// Each error response contains a structured error detail object with a numeric code, descriptive message,\n/// and optional additional data to provide more context about the error.\n/// \n/// \npublic sealed class JsonRpcError : JsonRpcMessageWithId\n{\n /// \n /// Gets detailed error information for the failed request, containing an error code, \n /// message, and optional additional data\n /// \n [JsonPropertyName(\"error\")]\n public required JsonRpcErrorDetail Error { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building resources that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner resource instance.\n/// \npublic abstract class DelegatingMcpServerResource : McpServerResource\n{\n private readonly McpServerResource _innerResource;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner resource wrapped by this delegating resource.\n protected DelegatingMcpServerResource(McpServerResource innerResource)\n {\n Throw.IfNull(innerResource);\n _innerResource = innerResource;\n }\n\n /// \n public override Resource? ProtocolResource => _innerResource.ProtocolResource;\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate => _innerResource.ProtocolResourceTemplate;\n\n /// \n public override ValueTask ReadAsync(RequestContext request, CancellationToken cancellationToken = default) => \n _innerResource.ReadAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerResource.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of prompts created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating prompts programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerPromptCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerPromptCreateOptions Clone() =>\n new McpServerPromptCreateOptions\n {\n Services = Services,\n Name = Name,\n Title = Title,\n Description = Description,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerTool.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building tools that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner tool instance.\n/// \npublic abstract class DelegatingMcpServerTool : McpServerTool\n{\n private readonly McpServerTool _innerTool;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner tool wrapped by this delegating tool.\n protected DelegatingMcpServerTool(McpServerTool innerTool)\n {\n Throw.IfNull(innerTool);\n _innerTool = innerTool;\n }\n\n /// \n public override Tool ProtocolTool => _innerTool.ProtocolTool;\n\n /// \n public override ValueTask InvokeAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerTool.InvokeAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerTool.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerFactory.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a factory for creating instances.\n/// \n/// \n/// This is the recommended way to create instances.\n/// The factory handles proper initialization of server instances with the required dependencies.\n/// \npublic static class McpServerFactory\n{\n /// \n /// Creates a new instance of an .\n /// \n /// Transport to use for the server representing an already-established MCP session.\n /// Configuration options for this server, including capabilities. \n /// Logger factory to use for logging. If null, logging will be disabled.\n /// Optional service provider to create new instances of tools and other dependencies.\n /// An instance that should be disposed when no longer needed.\n /// is .\n /// is .\n public static IMcpServer Create(\n ITransport transport,\n McpServerOptions serverOptions,\n ILoggerFactory? loggerFactory = null,\n IServiceProvider? serviceProvider = null)\n {\n Throw.IfNull(transport);\n Throw.IfNull(serverOptions);\n\n return new McpServer(transport, serverOptions, loggerFactory, serviceProvider);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerPrompt.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building prompts that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner prompt instance.\n/// \npublic abstract class DelegatingMcpServerPrompt : McpServerPrompt\n{\n private readonly McpServerPrompt _innerPrompt;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner prompt wrapped by this delegating prompt.\n protected DelegatingMcpServerPrompt(McpServerPrompt innerPrompt)\n {\n Throw.IfNull(innerPrompt);\n _innerPrompt = innerPrompt;\n }\n\n /// \n public override Prompt ProtocolPrompt => _innerPrompt.ProtocolPrompt;\n\n /// \n public override ValueTask GetAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerPrompt.GetAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerPrompt.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/SingleSessionMcpServerHostedService.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Hosted service for a single-session (e.g. stdio) MCP server.\n/// \n/// The server representing the session being hosted.\n/// \n/// The host's application lifetime. If available, it will have termination requested when the session's run completes.\n/// \ninternal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime? lifetime = null) : BackgroundService\n{\n /// \n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n try\n {\n await session.RunAsync(stoppingToken).ConfigureAwait(false);\n }\n finally\n {\n lifetime?.StopApplication();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcNotification.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification message in the JSON-RPC protocol.\n/// \n/// \n/// Notifications are messages that do not require a response and are not matched with a response message.\n/// They are useful for one-way communication, such as log notifications and progress updates.\n/// Unlike requests, notifications do not include an ID field, since there will be no response to match with it.\n/// \npublic sealed class JsonRpcNotification : JsonRpcMessage\n{\n /// \n /// Gets or sets the name of the notification method.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Gets or sets optional parameters for the notification.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of resources created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating resources programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerResourceCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the URI template of the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the from the attribute will be used. If that's not present,\n /// a URI template will be inferred from the member's signature.\n /// \n public string? UriTemplate { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the name from the attribute will be used. If that's not present, a name based on the members's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the member,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the MIME (media) type of the .\n /// \n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerResourceCreateOptions Clone() =>\n new McpServerResourceCreateOptions\n {\n Services = Services,\n UriTemplate = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/samples/EverythingServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test://direct/text/resource\", Name = \"Direct Text Resource\", MimeType = \"text/plain\")]\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n\n [McpServerResource(UriTemplate = \"test://template/resource/{id}\", Name = \"Template Resource\")]\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id)\n {\n int index = id - 1;\n if ((uint)index >= ResourceGenerator.Resources.Count)\n {\n throw new NotSupportedException($\"Unknown resource: {requestContext.Params?.Uri}\");\n }\n\n var resource = ResourceGenerator.Resources[index];\n return resource.MimeType == \"text/plain\" ?\n new TextResourceContents\n {\n Text = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n } :\n new BlobResourceContents\n {\n Blob = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationExtensions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.AspNetCore.Authentication;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Extension methods for adding MCP authorization support to ASP.NET Core applications.\n/// \npublic static class McpAuthenticationExtensions\n{\n /// \n /// Adds MCP authorization support to the application.\n /// \n /// The authentication builder.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n Action? configureOptions = null)\n {\n return AddMcp(\n builder,\n McpAuthenticationDefaults.AuthenticationScheme,\n McpAuthenticationDefaults.DisplayName,\n configureOptions);\n }\n\n /// \n /// Adds MCP authorization support to the application with a custom scheme name.\n /// \n /// The authentication builder.\n /// The authentication scheme name to use.\n /// The display name for the authentication scheme.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n string authenticationScheme,\n string displayName,\n Action? configureOptions = null)\n {\n return builder.AddScheme(\n authenticationScheme,\n displayName,\n configureOptions);\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Serilog;\nusing TestServerWithHosting.Tools;\n\nLog.Logger = new LoggerConfiguration()\n .MinimumLevel.Verbose() // Capture all log levels\n .WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"logs\", \"TestServer_.log\"),\n rollingInterval: RollingInterval.Day,\n outputTemplate: \"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}\")\n .WriteTo.Debug()\n .WriteTo.Console(standardErrorFromLevel: Serilog.Events.LogEventLevel.Verbose)\n .CreateLogger();\n\ntry\n{\n Log.Information(\"Starting server...\");\n\n var builder = Host.CreateApplicationBuilder(args);\n builder.Services.AddSerilog();\n builder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools();\n\n var app = builder.Build();\n\n await app.RunAsync();\n return 0;\n}\ncatch (Exception ex)\n{\n Log.Fatal(ex, \"Host terminated unexpectedly\");\n return 1;\n}\nfinally\n{\n Log.CloseAndFlush();\n}"], ["/csharp-sdk/src/ModelContextProtocol/McpServerOptionsSetup.cs", "using Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Configures the McpServerOptions using addition services from DI.\n/// \n/// The server handlers configuration options.\n/// Tools individually registered.\n/// Prompts individually registered.\n/// Resources individually registered.\ninternal sealed class McpServerOptionsSetup(\n IOptions serverHandlers,\n IEnumerable serverTools,\n IEnumerable serverPrompts,\n IEnumerable serverResources) : IConfigureOptions\n{\n /// \n /// Configures the given McpServerOptions instance by setting server information\n /// and applying custom server handlers and tools.\n /// \n /// The options instance to be configured.\n public void Configure(McpServerOptions options)\n {\n Throw.IfNull(options);\n\n // Collect all of the provided tools into a tools collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection toolCollection = options.Capabilities?.Tools?.ToolCollection ?? [];\n foreach (var tool in serverTools)\n {\n toolCollection.TryAdd(tool);\n }\n\n if (!toolCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Tools ??= new();\n options.Capabilities.Tools.ToolCollection = toolCollection;\n }\n\n // Collect all of the provided prompts into a prompts collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection promptCollection = options.Capabilities?.Prompts?.PromptCollection ?? [];\n foreach (var prompt in serverPrompts)\n {\n promptCollection.TryAdd(prompt);\n }\n\n if (!promptCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Prompts ??= new();\n options.Capabilities.Prompts.PromptCollection = promptCollection;\n }\n\n // Collect all of the provided resources into a resources collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerResourceCollection resourceCollection = options.Capabilities?.Resources?.ResourceCollection ?? [];\n foreach (var resource in serverResources)\n {\n resourceCollection.TryAdd(resource);\n }\n\n if (!resourceCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Resources ??= new();\n options.Capabilities.Resources.ResourceCollection = resourceCollection;\n }\n\n // Apply custom server handlers.\n serverHandlers.Value.OverwriteWithSetHandlers(options);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerServiceCollectionExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides extension methods for configuring MCP servers with dependency injection.\n/// \npublic static class McpServerServiceCollectionExtensions\n{\n /// \n /// Adds the Model Context Protocol (MCP) server to the service collection with default options.\n /// \n /// The to add the server to.\n /// Optional callback to configure the .\n /// An that can be used to further configure the MCP server.\n\n public static IMcpServerBuilder AddMcpServer(this IServiceCollection services, Action? configureOptions = null)\n {\n services.AddOptions();\n services.TryAddEnumerable(ServiceDescriptor.Transient, McpServerOptionsSetup>());\n if (configureOptions is not null)\n {\n services.Configure(configureOptions);\n }\n\n return new DefaultMcpServerBuilder(services);\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/UnconditionalSuppressMessageAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a\n/// single code artifact.\n/// \n/// \n/// is different than\n/// in that it doesn't have a\n/// . So it is always preserved in the compiled assembly.\n/// \n[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\ninternal sealed class UnconditionalSuppressMessageAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the \n /// class, specifying the category of the tool and the identifier for an analysis rule.\n /// \n /// The category for the attribute.\n /// The identifier of the analysis rule the attribute applies to.\n public UnconditionalSuppressMessageAttribute(string category, string checkId)\n {\n Category = category;\n CheckId = checkId;\n }\n\n /// \n /// Gets the category identifying the classification of the attribute.\n /// \n /// \n /// The property describes the tool or tool analysis category\n /// for which a message suppression attribute applies.\n /// \n public string Category { get; }\n\n /// \n /// Gets the identifier of the analysis tool rule to be suppressed.\n /// \n /// \n /// Concatenated together, the and \n /// properties form a unique check identifier.\n /// \n public string CheckId { get; }\n\n /// \n /// Gets or sets the scope of the code that is relevant for the attribute.\n /// \n /// \n /// The Scope property is an optional argument that specifies the metadata scope for which\n /// the attribute is relevant.\n /// \n public string? Scope { get; set; }\n\n /// \n /// Gets or sets a fully qualified path that represents the target of the attribute.\n /// \n /// \n /// The property is an optional argument identifying the analysis target\n /// of the attribute. An example value is \"System.IO.Stream.ctor():System.Void\".\n /// Because it is fully qualified, it can be long, particularly for targets such as parameters.\n /// The analysis tool user interface should be capable of automatically formatting the parameter.\n /// \n public string? Target { get; set; }\n\n /// \n /// Gets or sets an optional argument expanding on exclusion criteria.\n /// \n /// \n /// The property is an optional argument that specifies additional\n /// exclusion where the literal metadata target is not sufficiently precise. For example,\n /// the cannot be applied within a method,\n /// and it may be desirable to suppress a violation against a statement in the method that will\n /// give a rule violation, but not against all statements in the method.\n /// \n public string? MessageId { get; set; }\n\n /// \n /// Gets or sets the justification for suppressing the code analysis message.\n /// \n public string? Justification { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AugmentedServiceProvider.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Augments a service provider with additional request-related services.\ninternal sealed class RequestServiceProvider(\n RequestContext request, IServiceProvider? innerServices) :\n IServiceProvider, IKeyedServiceProvider,\n IServiceProviderIsService, IServiceProviderIsKeyedService,\n IDisposable, IAsyncDisposable\n where TRequestParams : RequestParams\n{\n /// Gets the request associated with this instance.\n public RequestContext Request => request;\n\n /// Gets whether the specified type is in the list of additional types this service provider wraps around the one in a provided request's services.\n public static bool IsAugmentedWith(Type serviceType) =>\n serviceType == typeof(RequestContext) ||\n serviceType == typeof(IMcpServer) ||\n serviceType == typeof(IProgress);\n\n /// \n public object? GetService(Type serviceType) =>\n serviceType == typeof(RequestContext) ? request :\n serviceType == typeof(IMcpServer) ? request.Server :\n serviceType == typeof(IProgress) ?\n (request.Params?.ProgressToken is { } progressToken ? new TokenProgress(request.Server, progressToken) : NullProgress.Instance) :\n innerServices?.GetService(serviceType);\n\n /// \n public bool IsService(Type serviceType) =>\n IsAugmentedWith(serviceType) ||\n (innerServices as IServiceProviderIsService)?.IsService(serviceType) is true;\n\n /// \n public bool IsKeyedService(Type serviceType, object? serviceKey) =>\n (serviceKey is null && IsService(serviceType)) ||\n (innerServices as IServiceProviderIsKeyedService)?.IsKeyedService(serviceType, serviceKey) is true;\n\n /// \n public object? GetKeyedService(Type serviceType, object? serviceKey) =>\n serviceKey is null ? GetService(serviceType) :\n (innerServices as IKeyedServiceProvider)?.GetKeyedService(serviceType, serviceKey);\n\n /// \n public object GetRequiredKeyedService(Type serviceType, object? serviceKey) =>\n GetKeyedService(serviceType, serviceKey) ??\n throw new InvalidOperationException($\"No service of type '{serviceType}' with key '{serviceKey}' is registered.\");\n\n /// \n public void Dispose() =>\n (innerServices as IDisposable)?.Dispose();\n\n /// \n public ValueTask DisposeAsync() =>\n innerServices is IAsyncDisposable asyncDisposable ? asyncDisposable.DisposeAsync() : default;\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/NullableAttributes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n /// Specifies that null is allowed as an input even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class AllowNullAttribute : Attribute;\n\n /// Specifies that null is disallowed as an input even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class DisallowNullAttribute : Attribute;\n\n /// Specifies that an output may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class MaybeNullAttribute : Attribute;\n\n /// Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class NotNullAttribute : Attribute;\n\n /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class MaybeNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter may be null.\n /// \n public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class NotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter will not be null.\n /// \n public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that the output will be non-null if the named parameter is non-null.\n [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]\n internal sealed class NotNullIfNotNullAttribute : Attribute\n {\n /// Initializes the attribute with the associated parameter name.\n /// \n /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.\n /// \n public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;\n\n /// Gets the associated parameter name.\n public string ParameterName { get; }\n }\n\n /// Applied to a method that will never return under any circumstance.\n [AttributeUsage(AttributeTargets.Method, Inherited = false)]\n internal sealed class DoesNotReturnAttribute : Attribute;\n\n /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class DoesNotReturnIfAttribute : Attribute\n {\n /// Initializes the attribute with the specified parameter value.\n /// \n /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to\n /// the associated parameter matches this value.\n /// \n public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;\n\n /// Gets the condition parameter value.\n public bool ParameterValue { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullAttribute : Attribute\n {\n /// Initializes the attribute with a field or property member.\n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullAttribute(string member) => Members = [member];\n\n /// Initializes the attribute with the list of field and property members.\n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullAttribute(params string[] members) => Members = members;\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition and a field or property member.\n /// \n /// The return value condition. If the method returns this value, the associated field or property member will not be null.\n /// \n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, string member)\n {\n ReturnValue = returnValue;\n Members = [member];\n }\n\n /// Initializes the attribute with the specified return value condition and list of field and property members.\n /// \n /// The return value condition. If the method returns this value, the associated field and property members will not be null.\n /// \n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, params string[] members)\n {\n ReturnValue = returnValue;\n Members = members;\n }\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring HTTP MCP servers via dependency injection.\n/// \npublic static class HttpMcpServerBuilderExtensions\n{\n /// \n /// Adds the services necessary for \n /// to handle MCP requests and sessions using the MCP Streamable HTTP transport. For more information on configuring the underlying HTTP server\n /// to control things like port binding custom TLS certificates, see the Minimal APIs quick reference.\n /// \n /// The builder instance.\n /// Configures options for the Streamable HTTP transport. This allows configuring per-session\n /// and running logic before and after a session.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithHttpTransport(this IMcpServerBuilder builder, Action? configureOptions = null)\n {\n ArgumentNullException.ThrowIfNull(builder);\n\n builder.Services.TryAddSingleton();\n builder.Services.TryAddSingleton();\n builder.Services.AddHostedService();\n builder.Services.AddDataProtection();\n\n if (configureOptions is not null)\n {\n builder.Services.Configure(configureOptions);\n }\n\n return builder;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method or property should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods or properties that should be exposed as resources in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods or properties become available as resources that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerResourceAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerResourceAttribute()\n {\n }\n\n /// Gets or sets the URI template of the resource.\n /// \n /// If , a URI will be derived from and the method's parameter names.\n /// This template may, but doesn't have to, include parameters; if it does, this \n /// will be considered a \"resource template\", and if it doesn't, it will be considered a \"direct resource\".\n /// The former will be listed with requests and the latter\n /// with requests.\n /// \n public string? UriTemplate { get; set; }\n\n /// Gets or sets the name of the resource.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the resource.\n public string? Title { get; set; }\n\n /// Gets or sets the MIME (media) type of the resource.\n public string? MimeType { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// request from a server to sample an LLM via the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageRequestParams : RequestParams\n{\n /// \n /// Gets or sets an indication as to which server contexts should be included in the prompt.\n /// \n /// \n /// The client may ignore this request.\n /// \n [JsonPropertyName(\"includeContext\")]\n public ContextInclusion? IncludeContext { get; init; }\n\n /// \n /// Gets or sets the maximum number of tokens to generate in the LLM response, as requested by the server.\n /// \n /// \n /// A token is generally a word or part of a word in the text. Setting this value helps control \n /// response length and computation time. The client may choose to sample fewer tokens than requested.\n /// \n [JsonPropertyName(\"maxTokens\")]\n public int? MaxTokens { get; init; }\n\n /// \n /// Gets or sets the messages requested by the server to be included in the prompt.\n /// \n [JsonPropertyName(\"messages\")]\n public required IReadOnlyList Messages { get; init; }\n\n /// \n /// Gets or sets optional metadata to pass through to the LLM provider.\n /// \n /// \n /// The format of this metadata is provider-specific and can include model-specific settings or\n /// configuration that isn't covered by standard parameters. This allows for passing custom parameters \n /// that are specific to certain AI models or providers.\n /// \n [JsonPropertyName(\"metadata\")]\n public JsonElement? Metadata { get; init; }\n\n /// \n /// Gets or sets the server's preferences for which model to select.\n /// \n /// \n /// \n /// The client may ignore these preferences.\n /// \n /// \n /// These preferences help the client make an appropriate model selection based on the server's priorities\n /// for cost, speed, intelligence, and specific model hints.\n /// \n /// \n /// When multiple dimensions are specified (cost, speed, intelligence), the client should balance these\n /// based on their relative values. If specific model hints are provided, the client should evaluate them\n /// in order and prioritize them over numeric priorities.\n /// \n /// \n [JsonPropertyName(\"modelPreferences\")]\n public ModelPreferences? ModelPreferences { get; init; }\n\n /// \n /// Gets or sets optional sequences of characters that signal the LLM to stop generating text when encountered.\n /// \n /// \n /// \n /// When the model generates any of these sequences during sampling, text generation stops immediately,\n /// even if the maximum token limit hasn't been reached. This is useful for controlling generation \n /// endings or preventing the model from continuing beyond certain points.\n /// \n /// \n /// Stop sequences are typically case-sensitive, and typically the LLM will only stop generation when a produced\n /// sequence exactly matches one of the provided sequences. Common uses include ending markers like \"END\", punctuation\n /// like \".\", or special delimiter sequences like \"###\".\n /// \n /// \n [JsonPropertyName(\"stopSequences\")]\n public IReadOnlyList? StopSequences { get; init; }\n\n /// \n /// Gets or sets an optional system prompt the server wants to use for sampling.\n /// \n /// \n /// The client may modify or omit this prompt.\n /// \n [JsonPropertyName(\"systemPrompt\")]\n public string? SystemPrompt { get; init; }\n\n /// \n /// Gets or sets the temperature to use for sampling, as requested by the server.\n /// \n [JsonPropertyName(\"temperature\")]\n public float? Temperature { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/SemaphoreSlimExtensions.cs", "namespace ModelContextProtocol;\n\ninternal static class SynchronizationExtensions\n{\n /// \n /// Asynchronously acquires a lock on the semaphore and returns a disposable object that releases the lock when disposed.\n /// \n /// The semaphore to acquire a lock on.\n /// A cancellation token to observe while waiting for the semaphore.\n /// A disposable that releases the semaphore when disposed.\n /// \n /// This extension method provides a convenient pattern for using a semaphore in asynchronous code,\n /// similar to how the `lock` statement is used in synchronous code.\n /// \n /// The was canceled.\n public static async ValueTask LockAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)\n {\n await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);\n return new(semaphore);\n }\n\n /// \n /// A disposable struct that releases a semaphore when disposed.\n /// \n /// \n /// This struct is used with the extension method to provide\n /// a using-pattern for semaphore locking, similar to lock statements.\n /// \n public readonly struct Releaser(SemaphoreSlim semaphore) : IDisposable\n {\n /// \n /// Releases the semaphore.\n /// \n /// \n /// This method is called automatically when the goes out of scope\n /// in a using statement or expression.\n /// \n public void Dispose() => semaphore.Release();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptResult.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// \n/// For integration with AI client libraries, can be converted to\n/// a collection of objects using the extension method.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class GetPromptResult : Result\n{\n /// \n /// Gets or sets an optional description for the prompt.\n /// \n /// \n /// \n /// This description provides contextual information about the prompt's purpose and use cases.\n /// It helps developers understand what the prompt is designed for and how it should be used.\n /// \n /// \n /// When returned from a server in response to a request,\n /// this description can be used by client applications to provide context about the prompt or to\n /// display in user interfaces.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets the prompt that the server offers.\n /// \n [JsonPropertyName(\"messages\")]\n public IList Messages { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingMessageNotificationParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a log message is generated.\n/// \n/// \n/// \n/// Logging notifications allow servers to communicate diagnostic information to clients with varying severity levels.\n/// Clients can filter these messages based on the and properties.\n/// \n/// \n/// If no request has been sent from the client, the server may decide which\n/// messages to send automatically.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class LoggingMessageNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the severity of this log message.\n /// \n [JsonPropertyName(\"level\")]\n public LoggingLevel Level { get; init; }\n\n /// \n /// Gets or sets an optional name of the logger issuing this message.\n /// \n /// \n /// \n /// typically represents a category or component in the server's logging system.\n /// The logger name is useful for filtering and routing log messages in client applications.\n /// \n /// \n /// When implementing custom servers, choose clear, hierarchical logger names to help\n /// clients understand the source of log messages.\n /// \n /// \n [JsonPropertyName(\"logger\")]\n public string? Logger { get; init; }\n\n /// \n /// Gets or sets the data to be logged, such as a string message.\n /// \n [JsonPropertyName(\"data\")]\n public JsonElement? Data { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/ResourceMetadataRequestContext.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Context for resource metadata request events.\n/// \npublic class ResourceMetadataRequestContext : HandleRequestContext\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The HTTP context.\n /// The authentication scheme.\n /// The authentication options.\n public ResourceMetadataRequestContext(\n HttpContext context,\n AuthenticationScheme scheme,\n McpAuthenticationOptions options)\n : base(context, scheme, options)\n {\n }\n\n /// \n /// Gets or sets the protected resource metadata for the current request.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/CancellationTokenSourceExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class CancellationTokenSourceExtensions\n{\n public static Task CancelAsync(this CancellationTokenSource cancellationTokenSource)\n {\n Throw.IfNull(cancellationTokenSource);\n\n cancellationTokenSource.Cancel();\n return Task.CompletedTask;\n }\n}\n#endif"], ["/csharp-sdk/src/Common/CancellableStreamReader/TextReaderExtensions.cs", "namespace System.IO;\n\ninternal static class TextReaderExtensions\n{\n public static ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n {\n if (reader is CancellableStreamReader cancellableReader)\n {\n return cancellableReader.ReadLineAsync(cancellationToken)!;\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n return new ValueTask(reader.ReadLineAsync());\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/RequestContext.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Provides a context container that provides access to the client request parameters and resources for the request.\n/// \n/// Type of the request parameters specific to each MCP operation.\n/// \n/// The encapsulates all contextual information for handling an MCP request.\n/// This type is typically received as a parameter in handler delegates registered with IMcpServerBuilder,\n/// and may be injected as parameters into s.\n/// \npublic sealed class RequestContext\n{\n /// The server with which this instance is associated.\n private IMcpServer _server;\n\n /// \n /// Initializes a new instance of the class with the specified server.\n /// \n /// The server with which this instance is associated.\n public RequestContext(IMcpServer server)\n {\n Throw.IfNull(server);\n\n _server = server;\n Services = server.Services;\n }\n\n /// Gets or sets the server with which this instance is associated.\n public IMcpServer Server \n {\n get => _server;\n set\n {\n Throw.IfNull(value);\n _server = value;\n }\n }\n\n /// Gets or sets the services associated with this request.\n /// \n /// This may not be the same instance stored in \n /// if was true, in which case this\n /// might be a scoped derived from the server's\n /// .\n /// \n public IServiceProvider? Services { get; set; }\n\n /// Gets or sets the parameters associated with this request.\n public TParams? Params { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingMessage.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued to or received from an LLM API within the Model Context Protocol.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be text or images.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent prompts or queries for LLM sampling. They form the core data structure for text generation requests\n/// within the Model Context Protocol.\n/// \n/// \n/// While similar to , the is focused on direct LLM sampling\n/// operations rather than the enhanced resource embedding capabilities provided by .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class SamplingMessage\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the role of the message sender, indicating whether it's from a \"user\" or an \"assistant\".\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcErrorDetail.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents detailed error information for JSON-RPC error responses.\n/// \n/// \n/// This class is used as part of the message to provide structured \n/// error information when a request cannot be fulfilled. The JSON-RPC 2.0 specification defines\n/// a standard format for error responses that includes a numeric code, a human-readable message,\n/// and optional additional data.\n/// \npublic sealed class JsonRpcErrorDetail\n{\n /// \n /// Gets an integer error code according to the JSON-RPC specification.\n /// \n [JsonPropertyName(\"code\")]\n public required int Code { get; init; }\n\n /// \n /// Gets a short description of the error.\n /// \n /// \n /// This is expected to be a brief, human-readable explanation of what went wrong.\n /// For standard error codes, it's recommended to use the descriptions defined \n /// in the JSON-RPC 2.0 specification.\n /// \n [JsonPropertyName(\"message\")]\n public required string Message { get; init; }\n\n /// \n /// Gets optional additional error data.\n /// \n /// \n /// This property can contain any additional information that might help the client\n /// understand or resolve the error. Common examples include validation errors,\n /// stack traces (in development environments), or contextual information about\n /// the error condition.\n /// \n [JsonPropertyName(\"data\")]\n public object? Data { get; init; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/StringSyntaxAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// Specifies the syntax used in a string.\n[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\ninternal sealed class StringSyntaxAttribute : Attribute\n{\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n public StringSyntaxAttribute(string syntax)\n {\n Syntax = syntax;\n Arguments = Array.Empty();\n }\n\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n /// Optional arguments associated with the specific syntax employed.\n public StringSyntaxAttribute(string syntax, params object?[] arguments)\n {\n Syntax = syntax;\n Arguments = arguments;\n }\n\n /// Gets the identifier of the syntax used.\n public string Syntax { get; }\n\n /// Optional arguments associated with the specific syntax employed.\n public object?[] Arguments { get; }\n\n /// The syntax identifier for strings containing composite formats for string formatting.\n public const string CompositeFormat = nameof(CompositeFormat);\n\n /// The syntax identifier for strings containing date format specifiers.\n public const string DateOnlyFormat = nameof(DateOnlyFormat);\n\n /// The syntax identifier for strings containing date and time format specifiers.\n public const string DateTimeFormat = nameof(DateTimeFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string EnumFormat = nameof(EnumFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string GuidFormat = nameof(GuidFormat);\n\n /// The syntax identifier for strings containing JavaScript Object Notation (JSON).\n public const string Json = nameof(Json);\n\n /// The syntax identifier for strings containing numeric format specifiers.\n public const string NumericFormat = nameof(NumericFormat);\n\n /// The syntax identifier for strings containing regular expressions.\n public const string Regex = nameof(Regex);\n\n /// The syntax identifier for strings containing time format specifiers.\n public const string TimeOnlyFormat = nameof(TimeOnlyFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string TimeSpanFormat = nameof(TimeSpanFormat);\n\n /// The syntax identifier for strings containing URIs.\n public const string Uri = nameof(Uri);\n\n /// The syntax identifier for strings containing XML.\n public const string Xml = nameof(Xml);\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationOptions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Options for the MCP authentication handler.\n/// \npublic class McpAuthenticationOptions : AuthenticationSchemeOptions\n{\n private static readonly Uri DefaultResourceMetadataUri = new(\"/.well-known/oauth-protected-resource\", UriKind.Relative);\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationOptions()\n {\n // \"Bearer\" is JwtBearerDefaults.AuthenticationScheme, but we don't have a reference to the JwtBearer package here.\n ForwardAuthenticate = \"Bearer\";\n ResourceMetadataUri = DefaultResourceMetadataUri;\n Events = new McpAuthenticationEvents();\n }\n\n /// \n /// Gets or sets the events used to handle authentication events.\n /// \n public new McpAuthenticationEvents Events\n {\n get { return (McpAuthenticationEvents)base.Events!; }\n set { base.Events = value; }\n }\n\n /// \n /// The URI to the resource metadata document.\n /// \n /// \n /// This URI will be included in the WWW-Authenticate header when a 401 response is returned.\n /// \n public Uri ResourceMetadataUri { get; set; }\n\n /// \n /// Gets or sets the protected resource metadata.\n /// \n /// \n /// This contains the OAuth metadata for the protected resource, including authorization servers,\n /// supported scopes, and other information needed for clients to authenticate.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Collections/Generic/CollectionExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Collections.Generic;\n\ninternal static class CollectionExtensions\n{\n public static TValue? GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key)\n {\n return dictionary.GetValueOrDefault(key, default!);\n }\n\n public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key, TValue defaultValue)\n {\n Throw.IfNull(dictionary);\n\n return dictionary.TryGetValue(key, out TValue? value) ? value : defaultValue;\n }\n\n public static Dictionary ToDictionary(this IEnumerable> source) =>\n source.ToDictionary(kv => kv.Key, kv => kv.Value);\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/IO/TextWriterExtensions.cs", "#if !NET\nnamespace System.IO;\n\ninternal static class TextWriterExtensions\n{\n public static async Task FlushAsync(this TextWriter writer, CancellationToken cancellationToken)\n {\n cancellationToken.ThrowIfCancellationRequested();\n await writer.FlushAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMembersAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that certain members on a specified are accessed dynamically,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which members are being accessed during the execution\n/// of a program.\n///\n/// This attribute is valid on members whose type is or .\n///\n/// When this attribute is applied to a location of type , the assumption is\n/// that the string represents a fully qualified type name.\n///\n/// When this attribute is applied to a class, interface, or struct, the members specified\n/// can be accessed dynamically on instances returned from calling\n/// on instances of that class, interface, or struct.\n///\n/// If the attribute is applied to a method it's treated as a special case and it implies\n/// the attribute should be applied to the \"this\" parameter of the method. As such the attribute\n/// should only be used on instance methods of types assignable to System.Type (or string, but no methods\n/// will use it there).\n/// \n[AttributeUsage(\n AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |\n AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |\n AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,\n Inherited = false)]\ninternal sealed class DynamicallyAccessedMembersAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified member types.\n /// \n /// The types of members dynamically accessed.\n public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)\n {\n MemberTypes = memberTypes;\n }\n\n /// \n /// Gets the which specifies the type\n /// of members dynamically accessed.\n /// \n public DynamicallyAccessedMemberTypes MemberTypes { get; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a from the server.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageResult : Result\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the name of the model that generated the message.\n /// \n /// \n /// \n /// This should contain the specific model identifier such as \"claude-3-5-sonnet-20241022\" or \"o3-mini\".\n /// \n /// \n /// This property allows the server to know which model was used to generate the response,\n /// enabling appropriate handling based on the model's capabilities and characteristics.\n /// \n /// \n [JsonPropertyName(\"model\")]\n public required string Model { get; init; }\n\n /// \n /// Gets or sets the reason why message generation (sampling) stopped, if known.\n /// \n /// \n /// Common values include:\n /// \n /// endTurnThe model naturally completed its response.\n /// maxTokensThe response was truncated due to reaching token limits.\n /// stopSequenceA specific stop sequence was encountered during generation.\n /// \n /// \n [JsonPropertyName(\"stopReason\")]\n public string? StopReason { get; init; }\n\n /// \n /// Gets or sets the role of the user who generated the message.\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/PrintEnvTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class PrintEnvTool\n{\n private static readonly JsonSerializerOptions options = new()\n {\n WriteIndented = true\n };\n\n [McpServerTool(Name = \"printEnv\"), Description(\"Prints all environment variables, helpful for debugging MCP server configuration\")]\n public static string PrintEnv() =>\n JsonSerializer.Serialize(Environment.GetEnvironmentVariables(), options);\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CompilerFeatureRequiredAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Indicates that compiler support for a particular feature is required for the location where this attribute is applied.\n /// \n [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]\n internal sealed class CompilerFeatureRequiredAttribute : Attribute\n {\n public CompilerFeatureRequiredAttribute(string featureName)\n {\n FeatureName = featureName;\n }\n\n /// \n /// The name of the compiler feature.\n /// \n public string FeatureName { get; }\n\n /// \n /// If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand .\n /// \n public bool IsOptional { get; init; }\n\n /// \n /// The used for the required members C# feature.\n /// \n public const string RequiredMembers = nameof(RequiredMembers);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourcesCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the resources capability configuration.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ResourcesCapability\n{\n /// \n /// Gets or sets whether this server supports subscribing to resource updates.\n /// \n [JsonPropertyName(\"subscribe\")]\n public bool? Subscribe { get; set; }\n\n /// \n /// Gets or sets whether this server supports notifications for changes to the resource list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when resources are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their resource cache.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is called when clients request available resource templates that can be used\n /// to create resources within the Model Context Protocol server.\n /// Resource templates define the structure and URI patterns for resources accessible in the system,\n /// allowing clients to discover available resource types and their access patterns.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler responds to client requests for available resources and returns information about resources accessible through the server.\n /// The implementation should return a with the matching resources.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is responsible for retrieving the content of a specific resource identified by its URI in the Model Context Protocol.\n /// When a client sends a resources/read request, this handler is invoked with the resource URI.\n /// The handler should implement logic to locate and retrieve the requested resource, then return\n /// its contents in a ReadResourceResult object.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be subscribed to. The implementation should register the client's interest in receiving updates\n /// for the specified resource.\n /// Subscriptions allow clients to receive real-time notifications when resources change, without\n /// requiring polling.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be unsubscribed from. The implementation should remove the client's registration for receiving updates\n /// about the specified resource.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets a collection of resources served by the server.\n /// \n /// \n /// \n /// Resources specified via augment the , \n /// and handlers, if provided. Resources with template expressions in their URI templates are considered resource templates\n /// and are listed via ListResourceTemplate, whereas resources without template parameters are considered static resources and are listed with ListResources.\n /// \n /// \n /// ReadResource requests will first check the for the exact resource being requested. If no match is found, they'll proceed to\n /// try to match the resource against each resource template in . If no match is still found, the request will fall back to\n /// any handler registered for .\n /// \n /// \n [JsonIgnore]\n public McpServerResourceCollection? ResourceCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientTransportOptions.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class StdioClientTransportOptions\n{\n /// \n /// Gets or sets the command to execute to start the server process.\n /// \n public required string Command\n {\n get;\n set\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Command cannot be null or empty.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the arguments to pass to the server process when it is started.\n /// \n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the working directory for the server process.\n /// \n public string? WorkingDirectory { get; set; }\n\n /// \n /// Gets or sets environment variables to set for the server process.\n /// \n /// \n /// \n /// This property allows you to specify environment variables that will be set in the server process's\n /// environment. This is useful for passing configuration, authentication information, or runtime flags\n /// to the server without modifying its code.\n /// \n /// \n /// By default, when starting the server process, the server process will inherit the current environment's variables,\n /// as discovered via . After those variables are found, the entries\n /// in this dictionary are used to augment and overwrite the entries read from the environment.\n /// That includes removing the variables for any of this collection's entries with a null value.\n /// \n /// \n public IDictionary? EnvironmentVariables { get; set; }\n\n /// \n /// Gets or sets the timeout to wait for the server to shut down gracefully.\n /// \n /// \n /// \n /// This property dictates how long the client should wait for the server process to exit cleanly during shutdown\n /// before forcibly terminating it. This balances between giving the server enough time to clean up \n /// resources and not hanging indefinitely if a server process becomes unresponsive.\n /// \n /// \n /// The default is five seconds.\n /// \n /// \n public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5);\n\n /// \n /// Gets or sets a callback that is invoked for each line of stderr received from the server process.\n /// \n public Action? StandardErrorLines { get; set; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresUnreferencedCode.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires dynamic access to code that is not referenced\n/// statically, for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when removing unreferenced\n/// code from an application.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresUnreferencedCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of unreferenced code.\n /// \n public RequiresUnreferencedCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of unreferenced code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires unreferenced code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresDynamicCodeAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires the ability to generate new code at runtime,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when compiling ahead of time.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresDynamicCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of dynamic code.\n /// \n public RequiresDynamicCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of dynamic code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires dynamic code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpServerTransportOptions.cs", "using Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\n/// \n/// Configuration options for .\n/// which implements the Streaming HTTP transport for the Model Context Protocol.\n/// See the protocol specification for details on the Streamable HTTP transport. \n/// \npublic class HttpServerTransportOptions\n{\n /// \n /// Gets or sets an optional asynchronous callback to configure per-session \n /// with access to the of the request that initiated the session.\n /// \n public Func? ConfigureSessionOptions { get; set; }\n\n /// \n /// Gets or sets an optional asynchronous callback for running new MCP sessions manually.\n /// This is useful for running logic before a sessions starts and after it completes.\n /// \n public Func? RunSessionHandler { get; set; }\n\n /// \n /// Gets or sets whether the server should run in a stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process.\n /// \n /// \n /// If , the \"/sse\" endpoint will be disabled, and client information will be round-tripped as part\n /// of the \"MCP-Session-Id\" header instead of stored in memory. Unsolicited server-to-client messages and all server-to-client\n /// requests are also unsupported, because any responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// Defaults to .\n /// \n public bool Stateless { get; set; }\n\n /// \n /// Gets or sets whether the server should use a single execution context for the entire session.\n /// If , handlers like tools get called with the \n /// belonging to the corresponding HTTP request which can change throughout the MCP session.\n /// If , handlers will get called with the same \n /// used to call and .\n /// \n /// \n /// Enabling a per-session can be useful for setting variables\n /// that persist for the entire session, but it prevents you from using IHttpContextAccessor in handlers.\n /// Defaults to .\n /// \n public bool PerSessionExecutionContext { get; set; }\n\n /// \n /// Gets or sets the duration of time the server will wait between any active requests before timing out an MCP session.\n /// \n /// \n /// This is checked in background every 5 seconds. A client trying to resume a session will receive a 404 status code\n /// and should restart their session. A client can keep their session open by keeping a GET request open.\n /// Defaults to 2 hours.\n /// \n public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromHours(2);\n\n /// \n /// Gets or sets maximum number of idle sessions to track in memory. This is used to limit the number of sessions that can be idle at once.\n /// \n /// \n /// Past this limit, the server will log a critical error and terminate the oldest idle sessions even if they have not reached\n /// their until the idle session count is below this limit. Clients that keep their session open by\n /// keeping a GET request open will not count towards this limit.\n /// Defaults to 100,000 sessions.\n /// \n public int MaxIdleSessionCount { get; set; } = 100_000;\n\n /// \n /// Used for testing the .\n /// \n public TimeProvider TimeProvider { get; set; } = TimeProvider.System;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Resource.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource that the server is capable of reading.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Resource : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource. Clients can use this information to filter or prioritize resources for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's capability to provide predefined prompt templates that clients can use.\n/// \n/// \n/// \n/// The prompts capability allows a server to expose a collection of predefined prompt templates that clients\n/// can discover and use. These prompts can be static (defined in the ) or\n/// dynamically generated through handlers.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the prompt list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when prompts are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their prompt cache. This capability enables clients to stay synchronized with server-side changes \n /// to available prompts.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests a list of available prompts from the server\n /// via a request. Results from this handler are returned\n /// along with any prompts defined in .\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt by name and provides arguments \n /// for the prompt if needed. The handler receives the request context containing the prompt name and any arguments, \n /// and should return a with the prompt messages and other details.\n /// \n /// \n /// This handler will be invoked if the requested prompt name is not found in the ,\n /// allowing for dynamic prompt generation or retrieval from external sources.\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets a collection of prompts that will be served by the server.\n /// \n /// \n /// \n /// The contains the predefined prompts that clients can request from the server.\n /// This collection works in conjunction with and \n /// when those are provided:\n /// \n /// \n /// - For requests: The server returns all prompts from this collection \n /// plus any additional prompts provided by the if it's set.\n /// \n /// \n /// - For requests: The server first checks this collection for the requested prompt.\n /// If not found, it will invoke the as a fallback if one is set.\n /// \n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? PromptCollection { get; set; }\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing QuickstartWeatherServer.Tools;\nusing System.Net.Http.Headers;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools();\n\nbuilder.Logging.AddConsole(options =>\n{\n options.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nbuilder.Services.AddSingleton(_ =>\n{\n var client = new HttpClient { BaseAddress = new Uri(\"https://api.weather.gov\") };\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n return client;\n});\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the tools capability configuration.\n/// See the schema for details.\n/// \npublic sealed class ToolsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the tool list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when tools are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their tool cache. This capability enables clients to stay synchronized with server-side \n /// changes to available tools.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// When used in conjunction with , both the tools from this handler\n /// and the tools from the collection will be combined to form the complete list of available tools.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the .\n /// The handler should implement logic to execute the requested tool and return appropriate results. \n /// It receives a containing information about the tool \n /// being called and its arguments, and should return a with the execution results.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets a collection of tools served by the server.\n /// \n /// \n /// Tools will specified via augment the and\n /// , if provided. ListTools requests will output information about every tool\n /// in and then also any tools output by , if it's\n /// non-. CallTool requests will first check for the tool\n /// being requested, and if the tool is not found in the , any specified \n /// will be invoked as a fallback.\n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? ToolCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ClientCapabilities.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a client may support.\n/// \n/// \n/// \n/// Capabilities define the features and functionality that a client can handle when communicating with an MCP server.\n/// These are advertised to the server during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ClientCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the client supports.\n /// \n /// \n /// \n /// The dictionary allows clients to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Servers should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets the client's roots capability, which are entry points for resource navigation.\n /// \n /// \n /// \n /// When is non-, the client indicates that it can respond to \n /// server requests for listing root URIs. Root URIs serve as entry points for resource navigation in the protocol.\n /// \n /// \n /// The server can use to request the list of\n /// available roots from the client, which will trigger the client's .\n /// \n /// \n [JsonPropertyName(\"roots\")]\n public RootsCapability? Roots { get; set; }\n\n /// \n /// Gets or sets the client's sampling capability, which indicates whether the client \n /// supports issuing requests to an LLM on behalf of the server.\n /// \n [JsonPropertyName(\"sampling\")]\n public SamplingCapability? Sampling { get; set; }\n\n /// \n /// Gets or sets the client's elicitation capability, which indicates whether the client \n /// supports elicitation of additional information from the user on behalf of the server.\n /// \n [JsonPropertyName(\"elicitation\")]\n public ElicitationCapability? Elicitation { get; set; }\n\n /// Gets or sets notification handlers to register with the client.\n /// \n /// \n /// When constructed, the client will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The client will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the client to respond to server-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the client for the lifetime of the client.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompletionsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the completions capability for providing auto-completion suggestions\n/// for prompt arguments and resource references.\n/// \n/// \n/// \n/// When enabled, this capability allows a Model Context Protocol server to provide \n/// auto-completion suggestions. This capability is advertised to clients during the initialize handshake.\n/// \n/// \n/// The primary function of this capability is to improve the user experience by offering\n/// contextual suggestions for argument values or resource identifiers based on partial input.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompletionsCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for completion requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler receives a reference type (e.g., \"ref/prompt\" or \"ref/resource\") and the current argument value,\n /// and should return appropriate completion suggestions.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/TokenProgress.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides an tied to a specific progress token and that will issue\n/// progress notifications on the supplied endpoint.\n/// \ninternal sealed class TokenProgress(IMcpEndpoint endpoint, ProgressToken progressToken) : IProgress\n{\n /// \n public void Report(ProgressNotificationValue value)\n {\n _ = endpoint.NotifyProgressAsync(progressToken, value, CancellationToken.None);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingLevel.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Indicates the severity of a log message.\n/// \n/// \n/// These map to syslog message severities, as specified in RFC-5424.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum LoggingLevel\n{\n /// Detailed debug information, typically only valuable to developers.\n [JsonStringEnumMemberName(\"debug\")]\n Debug,\n\n /// Normal operational messages that require no action.\n [JsonStringEnumMemberName(\"info\")]\n Info,\n\n /// Normal but significant events that might deserve attention.\n [JsonStringEnumMemberName(\"notice\")]\n Notice,\n\n /// Warning conditions that don't represent an error but indicate potential issues.\n [JsonStringEnumMemberName(\"warning\")]\n Warning,\n\n /// Error conditions that should be addressed but don't require immediate action.\n [JsonStringEnumMemberName(\"error\")]\n Error,\n\n /// Critical conditions that require immediate attention.\n [JsonStringEnumMemberName(\"critical\")]\n Critical,\n\n /// Action must be taken immediately to address the condition.\n [JsonStringEnumMemberName(\"alert\")]\n Alert,\n\n /// System is unusable and requires immediate attention.\n [JsonStringEnumMemberName(\"emergency\")]\n Emergency\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides configuration options for the MCP server.\n/// \npublic sealed class McpServerOptions\n{\n /// \n /// Gets or sets information about this server implementation, including its name and version.\n /// \n /// \n /// This information is sent to the client during initialization to identify the server.\n /// It's displayed in client logs and can be used for debugging and compatibility checks.\n /// \n public Implementation? ServerInfo { get; set; }\n\n /// \n /// Gets or sets server capabilities to advertise to the client.\n /// \n /// \n /// These determine which features will be available when a client connects.\n /// Capabilities can include \"tools\", \"prompts\", \"resources\", \"logging\", and other \n /// protocol-specific functionality.\n /// \n public ServerCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version supported by this server, using a date-based versioning scheme.\n /// \n /// \n /// The protocol version defines which features and message formats this server supports.\n /// This uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// If , the server will advertize to the client the version requested\n /// by the client if that version is known to be supported, and otherwise will advertize the latest\n /// version supported by the server.\n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout used for the client-server initialization handshake sequence.\n /// \n /// \n /// This timeout determines how long the server will wait for client responses during\n /// the initialization protocol handshake. If the client doesn't respond within this timeframe,\n /// the initialization process will be aborted.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n\n /// \n /// Gets or sets optional server instructions to send to clients.\n /// \n /// \n /// These instructions are sent to clients during the initialization handshake and provide\n /// guidance on how to effectively use the server's capabilities. They can include details\n /// about available tools, expected input formats, limitations, or other helpful information.\n /// Client applications typically use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n public string? ServerInstructions { get; set; }\n\n /// \n /// Gets or sets whether to create a new service provider scope for each handled request.\n /// \n /// \n /// The default is . When , each invocation of a request\n /// handler will be invoked within a new service scope.\n /// \n public bool ScopeRequests { get; set; } = true;\n\n /// \n /// Gets or sets preexisting knowledge about the client including its name and version to help support\n /// stateless Streamable HTTP servers that encode this knowledge in the mcp-session-id header.\n /// \n /// \n /// \n /// When not specified, this information is sourced from the client's initialize request.\n /// \n /// \n public Implementation? KnownClientInfo { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common notification methods used in the MCP protocol.\n/// \npublic static class NotificationMethods\n{\n /// \n /// The name of notification sent by a server when the list of available tools changes.\n /// \n /// \n /// This notification informs clients that the set of available tools has been modified.\n /// Changes may include tools being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their tool list by calling the appropriate \n /// method to get the updated list of tools.\n /// \n public const string ToolListChangedNotification = \"notifications/tools/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available prompts changes.\n /// \n /// \n /// This notification informs clients that the set of available prompts has been modified.\n /// Changes may include prompts being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their prompt list by calling the appropriate \n /// method to get the updated list of prompts.\n /// \n public const string PromptListChangedNotification = \"notifications/prompts/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available resources changes.\n /// \n /// \n /// This notification informs clients that the set of available resources has been modified.\n /// Changes may include resources being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their resource list by calling the appropriate \n /// method to get the updated list of resources.\n /// \n public const string ResourceListChangedNotification = \"notifications/resources/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a resource is updated.\n /// \n /// \n /// This notification is used to inform clients about changes to a specific resource they have subscribed to.\n /// When a resource is updated, the server sends this notification to all clients that have subscribed to that resource.\n /// \n public const string ResourceUpdatedNotification = \"notifications/resources/updated\";\n\n /// \n /// The name of the notification sent by the client when roots have been updated.\n /// \n /// \n /// \n /// This notification informs the server that the client's \"roots\" have changed. \n /// Roots define the boundaries of where servers can operate within the filesystem, \n /// allowing them to understand which directories and files they have access to. Servers \n /// can request the list of roots from supporting clients and receive notifications when that list changes.\n /// \n /// \n /// After receiving this notification, servers may refresh their knowledge of roots by calling the appropriate \n /// method to get the updated list of roots from the client.\n /// \n /// \n public const string RootsListChangedNotification = \"notifications/roots/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a log message is generated.\n /// \n /// \n /// \n /// This notification is used by the server to send log messages to clients. Log messages can include\n /// different severity levels, such as debug, info, warning, or error, and an optional logger name to\n /// identify the source component.\n /// \n /// \n /// The minimum logging level that triggers notifications can be controlled by clients using the\n /// request. If no level has been set by a client, \n /// the server may determine which messages to send based on its own configuration.\n /// \n /// \n public const string LoggingMessageNotification = \"notifications/message\";\n\n /// \n /// The name of the notification sent from the client to the server after initialization has finished.\n /// \n /// \n /// \n /// This notification is sent by the client after it has received and processed the server's response to the \n /// request. It signals that the client is ready to begin normal operation \n /// and that the initialization phase is complete.\n /// \n /// \n /// After receiving this notification, the server can begin sending notifications and processing\n /// further requests from the client.\n /// \n /// \n public const string InitializedNotification = \"notifications/initialized\";\n\n /// \n /// The name of the notification sent to inform the receiver of a progress update for a long-running request.\n /// \n /// \n /// \n /// This notification provides updates on the progress of long-running operations. It includes\n /// a progress token that associates the notification with a specific request, the current progress value,\n /// and optionally, a total value and a descriptive message.\n /// \n /// \n /// Progress notifications may be sent by either the client or the server, depending on the context.\n /// Progress notifications enable clients to display progress indicators for operations that might take\n /// significant time to complete, such as large file uploads, complex computations, or resource-intensive\n /// processing tasks.\n /// \n /// \n public const string ProgressNotification = \"notifications/progress\";\n\n /// \n /// The name of the notification sent to indicate that a previously-issued request should be canceled.\n /// \n /// \n /// \n /// From the issuer's perspective, the request should still be in-flight. However, due to communication latency,\n /// it is always possible that this notification may arrive after the request has already finished.\n /// \n /// \n /// This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n /// \n /// \n /// A client must not attempt to cancel its `initialize` request.\n /// \n /// \n public const string CancelledNotification = \"notifications/cancelled\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common request methods used in the MCP protocol.\n/// \npublic static class RequestMethods\n{\n /// \n /// The name of the request method sent from the client to request a list of the server's tools.\n /// \n public const string ToolsList = \"tools/list\";\n\n /// \n /// The name of the request method sent from the client to request that the server invoke a specific tool.\n /// \n public const string ToolsCall = \"tools/call\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's prompts.\n /// \n public const string PromptsList = \"prompts/list\";\n\n /// \n /// The name of the request method sent by the client to get a prompt provided by the server.\n /// \n public const string PromptsGet = \"prompts/get\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resources.\n /// \n public const string ResourcesList = \"resources/list\";\n\n /// \n /// The name of the request method sent from the client to read a specific server resource.\n /// \n public const string ResourcesRead = \"resources/read\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resource templates.\n /// \n public const string ResourcesTemplatesList = \"resources/templates/list\";\n\n /// \n /// The name of the request method sent from the client to request \n /// notifications from the server whenever a particular resource changes.\n /// \n public const string ResourcesSubscribe = \"resources/subscribe\";\n\n /// \n /// The name of the request method sent from the client to request unsubscribing from \n /// notifications from the server.\n /// \n public const string ResourcesUnsubscribe = \"resources/unsubscribe\";\n\n /// \n /// The name of the request method sent from the server to request a list of the client's roots.\n /// \n public const string RootsList = \"roots/list\";\n\n /// \n /// The name of the request method sent by either endpoint to check that the connected endpoint is still alive.\n /// \n public const string Ping = \"ping\";\n\n /// \n /// The name of the request method sent from the client to the server to adjust the logging level.\n /// \n /// \n /// This request allows clients to control which log messages they receive from the server\n /// by setting a minimum severity threshold. After processing this request, the server will\n /// send log messages with severity at or above the specified level to the client as\n /// notifications.\n /// \n public const string LoggingSetLevel = \"logging/setLevel\";\n\n /// \n /// The name of the request method sent from the client to the server to ask for completion suggestions.\n /// \n /// \n /// This is used to provide autocompletion-like functionality for arguments in a resource reference or a prompt template.\n /// The client provides a reference (resource or prompt), argument name, and partial value, and the server \n /// responds with matching completion options.\n /// \n public const string CompletionComplete = \"completion/complete\";\n\n /// \n /// The name of the request method sent from the server to sample an large language model (LLM) via the client.\n /// \n /// \n /// This request allows servers to utilize an LLM available on the client side to generate text or image responses\n /// based on provided messages. It is part of the sampling capability in the Model Context Protocol and enables servers to access\n /// client-side AI models without needing direct API access to those models.\n /// \n public const string SamplingCreateMessage = \"sampling/createMessage\";\n\n /// \n /// The name of the request method sent from the client to the server to elicit additional information from the user via the client.\n /// \n /// \n /// This request is used when the server needs more information from the client to proceed with a task or interaction.\n /// Servers can request structured data from users, with optional JSON schemas to validate responses.\n /// \n public const string ElicitationCreate = \"elicitation/create\";\n\n /// \n /// The name of the request method sent from the client to the server when it first connects, asking it initialize.\n /// \n /// \n /// The initialize request is the first request sent by the client to the server. It provides client information\n /// and capabilities to the server during connection establishment. The server responds with its own capabilities\n /// and information, establishing the protocol version and available features for the session.\n /// \n public const string Initialize = \"initialize\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides configuration options for creating instances.\n/// \n/// \n/// These options are typically passed to when creating a client.\n/// They define client capabilities, protocol version, and other client-specific settings.\n/// \npublic sealed class McpClientOptions\n{\n /// \n /// Gets or sets information about this client implementation, including its name and version.\n /// \n /// \n /// \n /// This information is sent to the server during initialization to identify the client.\n /// It's often displayed in server logs and can be used for debugging and compatibility checks.\n /// \n /// \n /// When not specified, information sourced from the current process will be used.\n /// \n /// \n public Implementation? ClientInfo { get; set; }\n\n /// \n /// Gets or sets the client capabilities to advertise to the server.\n /// \n public ClientCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version to request from the server, using a date-based versioning scheme.\n /// \n /// \n /// \n /// The protocol version is a key part of the initialization handshake. The client and server must \n /// agree on a compatible protocol version to communicate successfully.\n /// \n /// \n /// If non-, this version will be sent to the server, and the handshake\n /// will fail if the version in the server's response does not match this version.\n /// If , the client will request the latest version supported by the server\n /// but will allow any supported version that the server advertizes in its response.\n /// \n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout for the client-server initialization handshake sequence.\n /// \n /// \n /// \n /// This timeout determines how long the client will wait for the server to respond during\n /// the initialization protocol handshake. If the server doesn't respond within this timeframe,\n /// an exception will be thrown.\n /// \n /// \n /// Setting an appropriate timeout prevents the client from hanging indefinitely when\n /// connecting to unresponsive servers.\n /// \n /// The default value is 60 seconds.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitationCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to provide server-requested additional information during interactions.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to elicitation requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to provide additional information\n/// during interactions. The client must set a to process these requests.\n/// \n/// \npublic sealed class ElicitationCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to provide additional\n /// information during interactions. The client must set this property for the elicitation capability to work.\n /// \n /// \n /// The handler receives message parameters and a cancellation token.\n /// It should return a containing the response to the elicitation request.\n /// \n /// \n [JsonIgnore]\n public Func>? ElicitationHandler { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/ForceYielding.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading;\n\n/// \n/// await default(ForceYielding) to provide the same behavior as\n/// await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding).\n/// \ninternal readonly struct ForceYielding : INotifyCompletion, ICriticalNotifyCompletion\n{\n public ForceYielding GetAwaiter() => this;\n\n public bool IsCompleted => false;\n public void OnCompleted(Action continuation) => ThreadPool.QueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void UnsafeOnCompleted(Action continuation) => ThreadPool.UnsafeQueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void GetResult() { }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the client's response to an elicitation request.\n/// \npublic sealed class ElicitResult : Result\n{\n /// \n /// Gets or sets the user action in response to the elicitation.\n /// \n /// \n /// \n /// \n /// \"accept\"\n /// User submitted the form/confirmed the action\n /// \n /// \n /// \"decline\"\n /// User explicitly declined the action\n /// \n /// \n /// \"cancel\"\n /// User dismissed without making an explicit choice\n /// \n /// \n /// \n [JsonPropertyName(\"action\")]\n public string Action { get; set; } = \"cancel\";\n\n /// \n /// Gets or sets the submitted form data.\n /// \n /// \n /// \n /// This is typically omitted if the action is \"cancel\" or \"decline\".\n /// \n /// \n /// Values in the dictionary should be of types , ,\n /// , or .\n /// \n /// \n [JsonPropertyName(\"content\")]\n public IDictionary? Content { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request sent to the server during connection establishment.\n/// \n/// \n/// \n/// The is sent by the server in response to an \n/// message from the client. It contains information about the server, its capabilities, and the protocol version\n/// that will be used for the session.\n/// \n/// \n/// After receiving this response, the client should send an \n/// notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeResult : Result\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the server will use for this session.\n /// \n /// \n /// \n /// This is the protocol version the server has agreed to use, which should match the client's \n /// requested version. If there's a mismatch, the client should throw an exception to prevent \n /// communication issues due to incompatible protocol versions.\n /// \n /// \n /// The protocol uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the server's capabilities.\n /// \n /// \n /// This defines the features the server supports, such as \"tools\", \"prompts\", \"resources\", or \"logging\", \n /// and other protocol-specific functionality.\n /// \n [JsonPropertyName(\"capabilities\")]\n public required ServerCapabilities Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the server implementation, including its name and version.\n /// \n /// \n /// This information identifies the server during the initialization handshake.\n /// Clients may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"serverInfo\")]\n public required Implementation ServerInfo { get; init; }\n\n /// \n /// Gets or sets optional instructions for using the server and its features.\n /// \n /// \n /// \n /// These instructions provide guidance to clients on how to effectively use the server's capabilities.\n /// They can include details about available tools, expected input formats, limitations,\n /// or any other information that helps clients interact with the server properly.\n /// \n /// \n /// Client applications often use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n /// \n [JsonPropertyName(\"instructions\")]\n public string? Instructions { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices;\n\n[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]\ninternal sealed class CallerArgumentExpressionAttribute : Attribute\n{\n public CallerArgumentExpressionAttribute(string parameterName)\n {\n ParameterName = parameterName;\n }\n\n public string ParameterName { get; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request sent by a client to a server during the protocol handshake.\n/// \n/// \n/// \n/// The is the first message sent in the Model Context Protocol\n/// communication flow. It establishes the connection between client and server, negotiates the protocol\n/// version, and declares the client's capabilities.\n/// \n/// \n/// After sending this request, the client should wait for an response\n/// before sending an notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the client wants to use.\n /// \n /// \n /// \n /// Protocol version is specified using a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// The client and server must agree on a protocol version to communicate successfully.\n /// \n /// \n /// During initialization, the server will check if it supports this requested version. If there's a \n /// mismatch, the server will reject the connection with a version mismatch error.\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the client's capabilities.\n /// \n /// \n /// Capabilities define the features the client supports, such as \"sampling\" or \"roots\".\n /// \n [JsonPropertyName(\"capabilities\")]\n public ClientCapabilities? Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the client implementation, including its name and version.\n /// \n /// \n /// This information is required during the initialization handshake to identify the client.\n /// Servers may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"clientInfo\")]\n public required Implementation ClientInfo { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/DefaultMcpServerBuilder.cs", "using ModelContextProtocol;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Default implementation of that enables fluent configuration\n/// of the Model Context Protocol (MCP) server. This builder is returned by the\n/// extension method and\n/// provides access to the service collection for registering additional MCP components.\n/// \ninternal sealed class DefaultMcpServerBuilder : IMcpServerBuilder\n{\n /// \n public IServiceCollection Services { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service collection to which MCP server services will be added. This collection\n /// is exposed through the property to allow additional configuration.\n /// Thrown when is null.\n public DefaultMcpServerBuilder(IServiceCollection services)\n {\n Throw.IfNull(services);\n\n Services = services;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ServerCapabilities.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a server may support.\n/// \n/// \n/// \n/// Server capabilities define the features and functionality available when clients connect.\n/// These capabilities are advertised to clients during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ServerCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the server supports.\n /// \n /// \n /// \n /// The dictionary allows servers to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Clients should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets a server's logging capability, supporting sending log messages to the client.\n /// \n [JsonPropertyName(\"logging\")]\n public LoggingCapability? Logging { get; set; }\n\n /// \n /// Gets or sets a server's prompts capability for serving predefined prompt templates that clients can discover and use.\n /// \n [JsonPropertyName(\"prompts\")]\n public PromptsCapability? Prompts { get; set; }\n\n /// \n /// Gets or sets a server's resources capability for serving predefined resources that clients can discover and use.\n /// \n [JsonPropertyName(\"resources\")]\n public ResourcesCapability? Resources { get; set; }\n\n /// \n /// Gets or sets a server's tools capability for listing tools that a client is able to invoke.\n /// \n [JsonPropertyName(\"tools\")]\n public ToolsCapability? Tools { get; set; }\n\n /// \n /// Gets or sets a server's completions capability for supporting argument auto-completion suggestions.\n /// \n [JsonPropertyName(\"completions\")]\n public CompletionsCapability? Completions { get; set; }\n\n /// Gets or sets notification handlers to register with the server.\n /// \n /// \n /// When constructed, the server will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The server will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the server to respond to client-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the server for the lifetime of the server.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for paginated requests.\n/// \n/// \n/// See the schema for details\n/// \npublic abstract class PaginatedRequestParams : RequestParams\n{\n /// Prevent external derivations.\n private protected PaginatedRequestParams()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the current pagination position.\n /// \n /// \n /// If provided, the server should return results starting after this cursor.\n /// This value should be obtained from the \n /// property of a previous request's response.\n /// \n [JsonPropertyName(\"cursor\")]\n public string? Cursor { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IClientTransport.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a transport mechanism for Model Context Protocol (MCP) client-to-server communication.\n/// \n/// \n/// \n/// The interface abstracts the communication layer between MCP clients\n/// and servers, allowing different transport protocols to be used interchangeably.\n/// \n/// \n/// When creating an , is typically used, and is\n/// provided with the based on expected server configuration.\n/// \n/// \npublic interface IClientTransport\n{\n /// \n /// Gets a transport identifier, used for logging purposes.\n /// \n string Name { get; }\n\n /// \n /// Asynchronously establishes a transport session with an MCP server and returns a transport for the duplex message stream.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// Returns an interface for the duplex message stream.\n /// \n /// \n /// This method is responsible for initializing the connection to the server using the specific transport \n /// mechanism implemented by the derived class. The returned interface \n /// provides methods to send and receive messages over the established connection.\n /// \n /// \n /// The lifetime of the returned instance is typically managed by the \n /// that uses this transport. When the client is disposed, it will dispose\n /// the transport session as well.\n /// \n /// \n /// This method is used by to initialize the connection.\n /// \n /// \n /// The transport connection could not be established.\n Task ConnectAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ClientOAuthOptions.cs", "namespace ModelContextProtocol.Authentication;\n\n/// \n/// Provides configuration options for the .\n/// \npublic sealed class ClientOAuthOptions\n{\n /// \n /// Gets or sets the OAuth redirect URI.\n /// \n public required Uri RedirectUri { get; set; }\n\n /// \n /// Gets or sets the OAuth client ID. If not provided, the client will attempt to register dynamically.\n /// \n public string? ClientId { get; set; }\n\n /// \n /// Gets or sets the OAuth client secret.\n /// \n /// \n /// This is optional for public clients or when using PKCE without client authentication.\n /// \n public string? ClientSecret { get; set; }\n\n /// \n /// Gets or sets the OAuth scopes to request.\n /// \n /// \n /// \n /// When specified, these scopes will be used instead of the scopes advertised by the protected resource.\n /// If not specified, the provider will use the scopes from the protected resource metadata.\n /// \n /// \n /// Common OAuth scopes include \"openid\", \"profile\", \"email\", etc.\n /// \n /// \n public IEnumerable? Scopes { get; set; }\n\n /// \n /// Gets or sets the authorization redirect delegate for handling the OAuth authorization flow.\n /// \n /// \n /// \n /// This delegate is responsible for handling the OAuth authorization URL and obtaining the authorization code.\n /// If not specified, a default implementation will be used that prompts the user to enter the code manually.\n /// \n /// \n /// Custom implementations might open a browser, start an HTTP listener, or use other mechanisms to capture\n /// the authorization code from the OAuth redirect.\n /// \n /// \n public AuthorizationRedirectDelegate? AuthorizationRedirectDelegate { get; set; }\n\n /// \n /// Gets or sets the authorization server selector function.\n /// \n /// \n /// \n /// This function is used to select which authorization server to use when multiple servers are available.\n /// If not specified, the first available server will be selected.\n /// \n /// \n /// The function receives a list of available authorization server URIs and should return the selected server,\n /// or null if no suitable server is found.\n /// \n /// \n public Func, Uri?>? AuthServerSelector { get; set; }\n\n /// \n /// Gets or sets the client name to use during dynamic client registration.\n /// \n /// \n /// This is a human-readable name for the client that may be displayed to users during authorization.\n /// Only used when a is not specified.\n /// \n public string? ClientName { get; set; }\n\n /// \n /// Gets or sets the client URI to use during dynamic client registration.\n /// \n /// \n /// This should be a URL pointing to the client's home page or information page.\n /// Only used when a is not specified.\n /// \n public Uri? ClientUri { get; set; }\n\n /// \n /// Gets or sets additional parameters to include in the query string of the OAuth authorization request\n /// providing extra information or fulfilling specific requirements of the OAuth provider.\n /// \n /// \n /// \n /// Parameters specified cannot override or append to any automatically set parameters like the \"redirect_uri\"\n /// which should instead be configured via .\n /// \n /// \n public IDictionary AdditionalAuthorizationParameters { get; set; } = new Dictionary();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContextInclusion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Specifies the context inclusion options for a request in the Model Context Protocol (MCP).\n/// \n/// \n/// See the schema for details.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum ContextInclusion\n{\n /// \n /// Indicates that no context should be included.\n /// \n [JsonStringEnumMemberName(\"none\")]\n None,\n\n /// \n /// Indicates that context from the server that sent the request should be included.\n /// \n [JsonStringEnumMemberName(\"thisServer\")]\n ThisServer,\n\n /// \n /// Indicates that context from all servers that the client is connected to should be included.\n /// \n [JsonStringEnumMemberName(\"allServers\")]\n AllServers\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client capability that enables root resource discovery in the Model Context Protocol.\n/// \n/// \n/// \n/// When present in , it indicates that the client supports listing\n/// root URIs that serve as entry points for resource navigation.\n/// \n/// \n/// The roots capability establishes a mechanism for servers to discover and access the hierarchical \n/// structure of resources provided by a client. Root URIs represent top-level entry points from which\n/// servers can navigate to access specific resources.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsCapability\n{\n /// \n /// Gets or sets whether the client supports notifications for changes to the roots list.\n /// \n /// \n /// When set to , the client can notify servers when roots are added, \n /// removed, or modified, allowing servers to refresh their roots cache accordingly.\n /// This enables servers to stay synchronized with client-side changes to available roots.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client sends a request to retrieve available roots.\n /// The handler receives request parameters and should return a containing the collection of available roots.\n /// \n [JsonIgnore]\n public Func>? RootsHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the logging capability configuration for a Model Context Protocol server.\n/// \n/// \n/// This capability allows clients to set the logging level and receive log messages from the server.\n/// See the schema for details.\n/// \npublic sealed class LoggingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for set logging level requests from clients.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/UnsubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Sent from the client to cancel resource update notifications from the server for a specific resource.\n/// \n/// \n/// \n/// After a client has subscribed to resource updates using , \n/// this message can be sent to stop receiving notifications for a specific resource. \n/// This is useful for conserving resources and network bandwidth when \n/// the client no longer needs to track changes to a particular resource.\n/// \n/// \n/// The unsubscribe operation is idempotent, meaning it can be called multiple times \n/// for the same resource without causing errors, even if there is no active subscription.\n/// \n/// \npublic sealed class UnsubscribeRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to unsubscribe from. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Annotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents annotations that can be attached to content, resources, and resource templates.\n/// \n/// \n/// Annotations enable filtering and prioritization of content for different audiences.\n/// See the schema for details.\n/// \npublic sealed class Annotations\n{\n /// \n /// Gets or sets the intended audience for this content as an array of values.\n /// \n [JsonPropertyName(\"audience\")]\n public IList? Audience { get; init; }\n\n /// \n /// Gets or sets a value indicating how important this data is for operating the server.\n /// \n /// \n /// The value is a floating-point number between 0 and 1, where 0 represents the lowest priority\n /// 1 represents highest priority.\n /// \n [JsonPropertyName(\"priority\")]\n public float? Priority { get; init; }\n\n /// \n /// Gets or sets the moment the resource was last modified.\n /// \n /// \n /// The corresponding JSON should be an ISO 8601 formatted string (e.g., \\\"2025-01-12T15:00:58Z\\\").\n /// Examples: last activity timestamp in an open file, timestamp when the resource was attached, etc.\n /// \n [JsonPropertyName(\"lastModified\")]\n public DateTimeOffset? LastModified { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Completion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a completion object in the server's response to a request.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Completion\n{\n /// \n /// Gets or sets an array of completion values (auto-suggestions) for the requested input.\n /// \n /// \n /// This collection contains the actual text strings to be presented to users as completion suggestions.\n /// The array will be empty if no suggestions are available for the current input.\n /// Per the specification, this should not exceed 100 items.\n /// \n [JsonPropertyName(\"values\")]\n public IList Values { get; set; } = [];\n\n /// \n /// Gets or sets the total number of completion options available.\n /// \n /// \n /// This can exceed the number of values actually sent in the response.\n /// \n [JsonPropertyName(\"total\")]\n public int? Total { get; set; }\n\n /// \n /// Gets or sets an indicator as to whether there are additional completion options beyond \n /// those provided in the current response, even if the exact total is unknown.\n /// \n [JsonPropertyName(\"hasMore\")]\n public bool? HasMore { get; set; }\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Program.cs", "using OpenTelemetry;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\nusing TestServerWithHosting.Tools;\nusing TestServerWithHosting.Resources;\n\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Services.AddMcpServer()\n .WithHttpTransport()\n .WithTools()\n .WithTools()\n .WithResources();\n\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithMetrics(b => b.AddMeter(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithLogging()\n .UseOtlpExporter();\n\nvar app = builder.Build();\n\napp.MapMcp();\n\napp.Run();\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/IsExternalInit.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Reserved to be used by the compiler for tracking metadata.\n /// This class should not be used by developers in source code.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n internal static class IsExternalInit;\n}\n#else\n// The compiler emits a reference to the internal copy of this type in the non-.NET builds,\n// so we must include a forward to be compatible.\n[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExternalInit))]\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a prompt provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting prompt.\n/// See the schema for details.\n/// \npublic sealed class GetPromptRequestParams : RequestParams\n{\n /// \n /// Gets or sets the name of the prompt.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets arguments to use for templating the prompt when retrieving it from the server.\n /// \n /// \n /// Typically, these arguments are used to replace placeholders in prompt templates. The keys in this dictionary\n /// should match the names defined in the prompt's list. However, the server may\n /// choose to use these arguments in any way it deems appropriate to generate the prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to request real-time notifications from the server whenever a particular resource changes.\n/// \n/// \n/// \n/// The subscription mechanism allows clients to be notified about changes to specific resources\n/// identified by their URI. When a subscribed resource changes, the server sends a notification\n/// to the client with the updated resource information.\n/// \n/// \n/// Subscriptions remain active until explicitly canceled using \n/// or until the connection is terminated.\n/// \n/// \n/// The server may refuse or limit subscriptions based on its capabilities or resource constraints.\n/// \n/// \npublic sealed class SubscribeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the URI of the resource to subscribe to.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// The server will respond with a containing the result of the tool invocation.\n/// See the schema for details.\n/// \npublic sealed class CallToolRequestParams : RequestParams\n{\n /// Gets or sets the name of the tool to invoke.\n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets optional arguments to pass to the tool when invoking it on the server.\n /// \n /// \n /// This dictionary contains the parameter values to be passed to the tool. Each key-value pair represents \n /// a parameter name and its corresponding argument value.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ProtectedResourceMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the resource metadata for OAuth authorization as defined in RFC 9396.\n/// Defined by RFC 9728.\n/// \npublic sealed class ProtectedResourceMetadata\n{\n /// \n /// The resource URI.\n /// \n /// \n /// REQUIRED. The protected resource's resource identifier.\n /// \n [JsonPropertyName(\"resource\")]\n public required Uri Resource { get; set; }\n\n /// \n /// The list of authorization server URIs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of OAuth authorization server issuer identifiers\n /// for authorization servers that can be used with this protected resource.\n /// \n [JsonPropertyName(\"authorization_servers\")]\n public List AuthorizationServers { get; set; } = [];\n\n /// \n /// The supported bearer token methods.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the supported methods of sending an OAuth 2.0 bearer token\n /// to the protected resource. Defined values are [\"header\", \"body\", \"query\"].\n /// \n [JsonPropertyName(\"bearer_methods_supported\")]\n public List BearerMethodsSupported { get; set; } = [\"header\"];\n\n /// \n /// The supported scopes.\n /// \n /// \n /// RECOMMENDED. JSON array containing a list of scope values that are used in authorization\n /// requests to request access to this protected resource.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List ScopesSupported { get; set; } = [];\n\n /// \n /// URL of the protected resource's JSON Web Key (JWK) Set document.\n /// \n /// \n /// OPTIONAL. This contains public keys belonging to the protected resource, such as signing key(s)\n /// that the resource server uses to sign resource responses. This URL MUST use the https scheme.\n /// \n [JsonPropertyName(\"jwks_uri\")]\n public Uri? JwksUri { get; set; }\n\n /// \n /// List of the JWS signing algorithms supported by the protected resource for signing resource responses.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS signing algorithms (alg values) supported by the protected resource\n /// for signing resource responses. No default algorithms are implied if this entry is omitted. The value none MUST NOT be used.\n /// \n [JsonPropertyName(\"resource_signing_alg_values_supported\")]\n public List? ResourceSigningAlgValuesSupported { get; set; }\n\n /// \n /// Human-readable name of the protected resource intended for display to the end user.\n /// \n /// \n /// RECOMMENDED. It is recommended that protected resource metadata include this field.\n /// The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_name\")]\n public string? ResourceName { get; set; }\n\n /// \n /// The URI to the resource documentation.\n /// \n /// \n /// OPTIONAL. URL of a page containing human-readable information that developers might want or need to know\n /// when using the protected resource.\n /// \n [JsonPropertyName(\"resource_documentation\")]\n public Uri? ResourceDocumentation { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's requirements.\n /// \n /// \n /// OPTIONAL. Information about how the client can use the data provided by the protected resource.\n /// \n [JsonPropertyName(\"resource_policy_uri\")]\n public Uri? ResourcePolicyUri { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's terms of service.\n /// \n /// \n /// OPTIONAL. The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_tos_uri\")]\n public Uri? ResourceTosUri { get; set; }\n\n /// \n /// Boolean value indicating protected resource support for mutual-TLS client certificate-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"tls_client_certificate_bound_access_tokens\")]\n public bool? TlsClientCertificateBoundAccessTokens { get; set; }\n\n /// \n /// List of the authorization details type values supported by the resource server.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the authorization details type values supported by the resource server\n /// when the authorization_details request parameter is used.\n /// \n [JsonPropertyName(\"authorization_details_types_supported\")]\n public List? AuthorizationDetailsTypesSupported { get; set; }\n\n /// \n /// List of the JWS algorithm values supported by the resource server for validating DPoP proof JWTs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS alg values supported by the resource server\n /// for validating Demonstrating Proof of Possession (DPoP) proof JWTs.\n /// \n [JsonPropertyName(\"dpop_signing_alg_values_supported\")]\n public List? DpopSigningAlgValuesSupported { get; set; }\n\n /// \n /// Boolean value specifying whether the protected resource always requires the use of DPoP-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"dpop_bound_access_tokens_required\")]\n public bool? DpopBoundAccessTokensRequired { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServer.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) server that connects to and communicates with an MCP client.\n/// \npublic interface IMcpServer : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the client.\n /// \n /// \n /// \n /// These capabilities are established during the initialization handshake and indicate\n /// which features the client supports, such as sampling, roots, and other\n /// protocol-specific functionality.\n /// \n /// \n /// Server implementations can check these capabilities to determine which features\n /// are available when interacting with the client.\n /// \n /// \n ClientCapabilities? ClientCapabilities { get; }\n\n /// \n /// Gets the version and implementation information of the connected client.\n /// \n /// \n /// \n /// This property contains identification information about the client that has connected to this server,\n /// including its name and version. This information is provided by the client during initialization.\n /// \n /// \n /// Server implementations can use this information for logging, tracking client versions, \n /// or implementing client-specific behaviors.\n /// \n /// \n Implementation? ClientInfo { get; }\n\n /// \n /// Gets the options used to construct this server.\n /// \n /// \n /// These options define the server's capabilities, protocol version, and other configuration\n /// settings that were used to initialize the server.\n /// \n McpServerOptions ServerOptions { get; }\n\n /// \n /// Gets the service provider for the server.\n /// \n IServiceProvider? Services { get; }\n\n /// Gets the last logging level set by the client, or if it's never been set.\n LoggingLevel? LoggingLevel { get; }\n\n /// \n /// Runs the server, listening for and handling client requests.\n /// \n Task RunAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptArgument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument that a prompt can accept for templating and customization.\n/// \n/// \n/// \n/// The class defines metadata for arguments that can be provided\n/// to a prompt. These arguments are used to customize or parameterize prompts when they are \n/// retrieved using requests.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptArgument : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the argument's purpose and expected values.\n /// \n /// \n /// This description helps developers understand what information should be provided\n /// for this argument and how it will affect the generated prompt.\n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets an indication as to whether this argument must be provided when requesting the prompt.\n /// \n /// \n /// When set to , the client must include this argument when making a request.\n /// If a required argument is missing, the server should respond with an error.\n /// \n [JsonPropertyName(\"required\")]\n public bool? Required { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Root.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a root URI and its metadata in the Model Context Protocol.\n/// \n/// \n/// Root URIs serve as entry points for resource navigation, typically representing\n/// top-level directories or container resources that can be accessed and traversed.\n/// Roots provide a hierarchical structure for organizing and accessing resources within the protocol.\n/// Each root has a URI that uniquely identifies it and optional metadata like a human-readable name.\n/// \npublic sealed class Root\n{\n /// \n /// Gets or sets the URI of the root.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for the root.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n\n /// \n /// Gets or sets additional metadata for the root.\n /// \n /// \n /// This is reserved by the protocol for future use.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonElement? Meta { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's response to a request, \n/// containing suggested values for a given argument.\n/// \n/// \n/// \n/// is returned by the server in response to a \n/// request from the client. It provides suggested completions or valid values for a specific argument in a tool or resource reference.\n/// \n/// \n/// The result contains a object with suggested values, pagination information,\n/// and the total number of available completions. This is similar to auto-completion functionality in code editors.\n/// \n/// \n/// Clients typically use this to implement auto-suggestion features when users are inputting parameters\n/// for tool calls or resource references.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteResult : Result\n{\n /// \n /// Gets or sets the completion object containing the suggested values and pagination information.\n /// \n /// \n /// If no completions are available for the given input, the \n /// collection will be empty.\n /// \n [JsonPropertyName(\"completion\")]\n public Completion Completion { get; set; } = new Completion();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ReadResourceResult : Result\n{\n /// \n /// Gets or sets a list of objects that this resource contains.\n /// \n /// \n /// This property contains the actual content of the requested resource, which can be\n /// either text-based () or binary ().\n /// The type of content included depends on the resource being accessed.\n /// \n [JsonPropertyName(\"contents\")]\n public IList Contents { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Prompt.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a prompt that the server offers.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Prompt : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets an optional description of what this prompt provides.\n /// \n /// \n /// \n /// This description helps developers understand the purpose and use cases for the prompt.\n /// It should explain what the prompt is designed to accomplish and any important context.\n /// \n /// \n /// The description is typically used in documentation, UI displays, and for providing context\n /// to client applications that may need to choose between multiple available prompts.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a list of arguments that this prompt accepts for templating and customization.\n /// \n /// \n /// \n /// This list defines the arguments that can be provided when requesting the prompt.\n /// Each argument specifies metadata like name, description, and whether it's required.\n /// \n /// \n /// When a client makes a request, it can provide values for these arguments\n /// which will be substituted into the prompt template or otherwise used to render the prompt.\n /// \n /// \n [JsonPropertyName(\"arguments\")]\n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/TinyImageTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class TinyImageTool\n{\n [McpServerTool(Name = \"getTinyImage\"), Description(\"Get a tiny image from the server\")]\n public static IEnumerable GetTinyImage() => [\n new TextContent(\"This is a tiny image:\"),\n new DataContent(MCP_TINY_IMAGE),\n new TextContent(\"The image above is the MCP tiny image.\")\n ];\n\n internal const string MCP_TINY_IMAGE =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAKsGlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgOfe9JDQEiIgJfQmSCeAlBBaAAXpYCMkAUKJMRBU7MriClZURLCs6KqIgo0idizYFsWC3QVZBNR1sWDDlXeBQ9jdd9575805c+a7c+efmf+e/z9nLgCdKZDJMlF1gCxpjjwyyI8dn5DIJvUABRiY0kBdIMyWcSMiwgCTUft3+dgGyJC9YzuU69/f/1fREImzhQBIBMbJomxhFsbHMe0TyuQ5ALg9mN9kbo5siK9gzJRjDWL8ZIhTR7hviJOHGY8fjomO5GGsDUCmCQTyVACaKeZn5wpTsTw0f4ztpSKJFGPsGbyzsmaLMMbqgiUWI8N4KD8n+S95Uv+WM1mZUyBIVfLIXoaF7C/JlmUK5v+fn+N/S1amYrSGOaa0NHlwJGaxvpAHGbNDlSxNnhI+yhLRcPwwpymCY0ZZmM1LHGWRwD9UuTZzStgop0gC+co8OfzoURZnB0SNsnx2pLJWipzHHWWBfKyuIiNG6U8T85X589Ki40Y5VxI7ZZSzM6JCx2J4Sr9cEansXywN8hurG6jce1b2X/Yr4SvX5qRFByv3LhjrXyzljuXMjlf2JhL7B4zFxCjjZTl+ylqyzAhlvDgzSOnPzo1Srs3BDuTY2gjlN0wXhESMMoRBELAhBjIhB+QggECQgBTEOeJ5Q2cUeLNl8+WS1LQcNhe7ZWI2Xyq0m8B2tHd0Bhi6syNH4j1r+C4irGtjvhWVAF4nBgcHT475Qm4BHEkCoNaO+SxnAKh3A1w5JVTIc0d8Q9cJCEAFNWCCDhiACViCLTiCK3iCLwRACIRDNCTATBBCGmRhnc+FhbAMCqAI1sNmKIOdsBv2wyE4CvVwCs7DZbgOt+AePIZ26IJX0AcfYQBBEBJCRxiIDmKImCE2iCPCQbyRACQMiUQSkCQkFZEiCmQhsgIpQoqRMmQXUokcQU4g55GrSCvyEOlAepF3yFcUh9JQJqqPmqMTUQ7KRUPRaHQGmorOQfPQfHQtWopWoAfROvQ8eh29h7ajr9B+HOBUcCycEc4Wx8HxcOG4RFwKTo5bjCvEleAqcNW4Rlwz7g6uHfca9wVPxDPwbLwt3hMfjI/BC/Fz8Ivxq/Fl+P34OvxF/B18B74P/51AJ+gRbAgeBD4hnpBKmEsoIJQQ9hJqCZcI9whdhI9EIpFFtCC6EYOJCcR04gLiauJ2Yg3xHLGV2EnsJ5FIOiQbkhcpnCQg5ZAKSFtJB0lnSbdJXaTPZBWyIdmRHEhOJEvJy8kl5APkM+Tb5G7yAEWdYkbxoIRTRJT5lHWUPZRGyk1KF2WAqkG1oHpRo6np1GXUUmo19RL1CfW9ioqKsYq7ylQVicpSlVKVwypXVDpUvtA0adY0Hm06TUFbS9tHO0d7SHtPp9PN6b70RHoOfS29kn6B/oz+WZWhaqfKVxWpLlEtV61Tva36Ro2iZqbGVZuplqdWonZM7abaa3WKurk6T12gvli9XP2E+n31fg2GhoNGuEaWxmqNAxpXNXo0SZrmmgGaIs18zd2aFzQ7GTiGCYPHEDJWMPYwLjG6mESmBZPPTGcWMQ8xW5h9WppazlqxWvO0yrVOa7WzcCxzFp+VyVrHOspqY30dpz+OO048btW46nG3x33SHq/tqy3WLtSu0b6n/VWHrROgk6GzQade56kuXtdad6ruXN0dupd0X49njvccLxxfOP7o+Ed6qJ61XqTeAr3dejf0+vUN9IP0Zfpb9S/ovzZgGfgapBtsMjhj0GvIMPQ2lBhuMjxr+JKtxeayM9ml7IvsPiM9o2AjhdEuoxajAWML4xjj5cY1xk9NqCYckxSTTSZNJn2mhqaTTReaVpk+MqOYcczSzLaYNZt9MrcwjzNfaV5v3mOhbcG3yLOosnhiSbf0sZxjWWF514poxbHKsNpudcsatXaxTrMut75pg9q42khsttu0TiBMcJ8gnVAx4b4tzZZrm2tbZdthx7ILs1tuV2/3ZqLpxMSJGyY2T/xu72Kfab/H/rGDpkOIw3KHRod3jtaOQsdyx7tOdKdApyVODU5vnW2cxc47nB+4MFwmu6x0aXL509XNVe5a7drrZuqW5LbN7T6HyYngrOZccSe4+7kvcT/l/sXD1SPH46jHH562nhmeBzx7JllMEk/aM6nTy9hL4LXLq92b7Z3k/ZN3u4+Rj8Cnwue5r4mvyHevbzfXipvOPch942fvJ/er9fvE8+At4p3zx/kH+Rf6twRoBsQElAU8CzQOTA2sCuwLcglaEHQumBAcGrwh+D5fny/kV/L7QtxCFoVcDKWFRoWWhT4Psw6ThzVORieHTN44+ckUsynSKfXhEM4P3xj+NMIiYk7EyanEqRFTy6e+iHSIXBjZHMWImhV1IOpjtF/0uujHMZYxipimWLXY6bGVsZ/i/OOK49rjJ8Yvir+eoJsgSWhIJCXGJu5N7J8WMG3ztK7pLtMLprfNsJgxb8bVmbozM2eenqU2SzDrWBIhKS7pQNI3QbigQtCfzE/eltwn5Am3CF+JfEWbRL1iL3GxuDvFK6U4pSfVK3Vjam+aT1pJ2msJT1ImeZsenL4z/VNGeMa+jMHMuMyaLHJWUtYJqaY0Q3pxtsHsebNbZTayAln7HI85m+f0yUPle7OR7BnZDTlMbDi6obBU/KDoyPXOLc/9PDd27rF5GvOk827Mt56/an53XmDezwvwC4QLmhYaLVy2sGMRd9Guxcji5MVNS0yW5C/pWhq0dP8y6rKMZb8st19evPzDirgVjfn6+UvzO38I+qGqQLVAXnB/pefKnT/if5T82LLKadXWVd8LRYXXiuyLSoq+rRauvrbGYU3pmsG1KWtb1rmu27GeuF66vm2Dz4b9xRrFecWdGydvrNvE3lS46cPmWZuvljiX7NxC3aLY0l4aVtqw1XTr+q3fytLK7pX7ldds09u2atun7aLtt3f47qjeqb+zaOfXnyQ/PdgVtKuuwryiZDdxd+7uF3ti9zT/zPm5cq/u3qK9f+6T7mvfH7n/YqVbZeUBvQPrqtAqRVXvwekHbx3yP9RQbVu9q4ZVU3QYDisOvzySdKTtaOjRpmOcY9XHzY5vq2XUFtYhdfPr+urT6tsbEhpaT4ScaGr0bKw9aXdy3ymjU+WntU6vO0M9k39m8Gze2f5zsnOvz6ee72ya1fT4QvyFuxenXmy5FHrpyuXAyxeauc1nr3hdOXXV4+qJa5xr9dddr9fdcLlR+4vLL7Utri11N91uNtzyv9XYOqn1zG2f2+fv+N+5fJd/9/q9Kfda22LaHtyffr/9gehBz8PMh28f5T4aeLz0CeFJ4VP1pyXP9J5V/Gr1a027a/vpDv+OG8+jnj/uFHa++i37t29d+S/oL0q6Dbsrexx7TvUG9t56Oe1l1yvZq4HXBb9r/L7tjeWb43/4/nGjL76v66387eC71e913u/74PyhqT+i/9nHrI8Dnwo/63ze/4Xzpflr3NfugbnfSN9K/7T6s/F76Pcng1mDgzKBXDA8CuAwRVNSAN7tA6AnADCwGYI6bWSmHhZk5D9gmOA/8cjcPSyuANWYGRqNeOcADmNqvhRAzRdgaCyK9gXUyUmpo/Pv8Kw+JAbYv8K0HECi2x6tebQU/iEjc/xf+v6nBWXWv9l/AV0EC6JTIblRAAAAeGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAJAAAAABAAAAkAAAAAEAAqACAAQAAAABAAAAFKADAAQAAAABAAAAFAAAAAAXNii1AAAACXBIWXMAABYlAAAWJQFJUiTwAAAB82lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOllSZXNvbHV0aW9uPjE0NDwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+MTQ0PC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KReh49gAAAjRJREFUOBGFlD2vMUEUx2clvoNCcW8hCqFAo1dKhEQpvsF9KrWEBh/ALbQ0KkInBI3SWyGPCCJEQliXgsTLefaca/bBWjvJzs6cOf/fnDkzOQJIjWm06/XKBEGgD8c6nU5VIWgBtQDPZPWtJE8O63a7LBgMMo/Hw0ql0jPjcY4RvmqXy4XMjUYDUwLtdhtmsxnYbDbI5/O0djqdFFKmsEiGZ9jP9gem0yn0ej2Yz+fg9XpfycimAD7DttstQTDKfr8Po9GIIg6Hw1Cr1RTgB+A72GAwgMPhQLBMJgNSXsFqtUI2myUo18pA6QJogefsPrLBX4QdCVatViklw+EQRFGEj88P2O12pEUGATmsXq+TaLPZ0AXgMRF2vMEqlQoJTSYTpNNpApvNZliv1/+BHDaZTAi2Wq1A3Ig0xmMej7+RcZjdbodUKkWAaDQK+GHjHPnImB88JrZIJAKFQgH2+z2BOczhcMiwRCIBgUAA+NN5BP6mj2DYff35gk6nA61WCzBn2JxO5wPM7/fLz4vD0E+OECfn8xl/0Gw2KbLxeAyLxQIsFgt8p75pDSO7h/HbpUWpewCike9WLpfB7XaDy+WCYrFI/slk8i0MnRRAUt46hPMI4vE4+Hw+ec7t9/44VgWigEeby+UgFArJWjUYOqhWG6x50rpcSfR6PVUfNOgEVRlTX0HhrZBKz4MZjUYWi8VoA+lc9H/VaRZYjBKrtXR8tlwumcFgeMWRbZpA9ORQWfVm8A/FsrLaxebd5wAAAABJRU5ErkJggg==\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a request from the server,\n/// containing available roots.\n/// \n/// \n/// \n/// This result is returned when a server sends a request to discover \n/// available roots on the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListRootsResult : Result\n{\n /// \n /// Gets or sets the list of root URIs provided by the client.\n /// \n /// \n /// This collection contains all available root URIs and their associated metadata.\n /// Each root serves as an entry point for resource navigation in the Model Context Protocol.\n /// \n [JsonPropertyName(\"roots\")]\n public required IReadOnlyList Roots { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationEvents.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Represents the authentication events for Model Context Protocol.\n/// \npublic class McpAuthenticationEvents\n{\n /// \n /// Gets or sets the function that is invoked when resource metadata is requested.\n /// \n /// \n /// This function is called when a resource metadata request is made to the protected resource metadata endpoint.\n /// The implementer should set the property\n /// to provide the appropriate metadata for the current request.\n /// \n public Func OnResourceMetadataRequest { get; set; } = context => Task.CompletedTask;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CancelledNotificationParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification indicating that a request has been cancelled by the client,\n/// and that any associated processing should cease immediately.\n/// \n/// \n/// This class is typically used in conjunction with the \n/// method identifier. When a client sends this notification, the server should attempt to\n/// cancel any ongoing operations associated with the specified request ID.\n/// \npublic sealed class CancelledNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the ID of the request to cancel.\n /// \n /// \n /// This must match the ID of an in-flight request that the sender wishes to cancel.\n /// \n [JsonPropertyName(\"requestId\")]\n public RequestId RequestId { get; set; }\n\n /// \n /// Gets or sets an optional string describing the reason for the cancellation request.\n /// \n [JsonPropertyName(\"reason\")]\n public string? Reason { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/IBaseMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// Provides a base interface for metadata with name (identifier) and title (display name) properties.\npublic interface IBaseMetadata\n{\n /// \n /// Gets or sets the unique identifier for this item.\n /// \n [JsonPropertyName(\"name\")]\n string Name { get; set; }\n\n /// \n /// Gets or sets a title.\n /// \n /// \n /// This is intended for UI and end-user contexts. It is optimized to be human-readable and easily understood,\n /// even by those unfamiliar with domain-specific terminology.\n /// If not provided, may be used for display (except for tools, where , if present, \n /// should be given precedence over using ).\n /// \n [JsonPropertyName(\"title\")]\n string? Title { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpErrorCode.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents standard JSON-RPC error codes as defined in the MCP specification.\n/// \npublic enum McpErrorCode\n{\n /// \n /// Indicates that the JSON received could not be parsed.\n /// \n /// \n /// This error occurs when the input contains malformed JSON or incorrect syntax.\n /// \n ParseError = -32700,\n\n /// \n /// Indicates that the JSON payload does not conform to the expected Request object structure.\n /// \n /// \n /// The request is considered invalid if it lacks required fields or fails to follow the JSON-RPC protocol.\n /// \n InvalidRequest = -32600,\n\n /// \n /// Indicates that the requested method does not exist or is not available on the server.\n /// \n /// \n /// This error is returned when the method name specified in the request cannot be found.\n /// \n MethodNotFound = -32601,\n\n /// \n /// Indicates that one or more parameters provided in the request are invalid.\n /// \n /// \n /// This error is returned when the parameters do not match the expected method signature or constraints.\n /// This includes cases where required parameters are missing or not understood, such as when a name for\n /// a tool or prompt is not recognized.\n /// \n InvalidParams = -32602,\n\n /// \n /// Indicates that an internal error occurred while processing the request.\n /// \n /// \n /// This error is used when the endpoint encounters an unexpected condition that prevents it from fulfilling the request.\n /// \n InternalError = -32603,\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationRedirectDelegate.cs", "\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a method that handles the OAuth authorization URL and returns the authorization code.\n/// \n/// The authorization URL that the user needs to visit.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// A task that represents the asynchronous operation. The task result contains the authorization code if successful, or null if the operation failed or was cancelled.\n/// \n/// \n/// This delegate provides SDK consumers with full control over how the OAuth authorization flow is handled.\n/// Implementers can choose to:\n/// \n/// \n/// Start a local HTTP server and open a browser (default behavior)\n/// Display the authorization URL to the user for manual handling\n/// Integrate with a custom UI or authentication flow\n/// Use a different redirect mechanism altogether\n/// \n/// \n/// The implementation should handle user interaction to visit the authorization URL and extract\n/// the authorization code from the callback. The authorization code is typically provided as\n/// a query parameter in the redirect URI callback.\n/// \n/// \npublic delegate Task AuthorizationRedirectDelegate(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken);"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceUpdatedNotificationParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a subscribed resource changes.\n/// \n/// \n/// \n/// When a client subscribes to resource updates using , the server will\n/// send notifications with this payload whenever the subscribed resource is modified. These notifications\n/// allow clients to maintain synchronized state without needing to poll the server for changes.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceUpdatedNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the URI of the resource that was updated.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from \n/// a client to ask a server for auto-completion suggestions.\n/// \n/// \n/// \n/// is used in the Model Context Protocol completion workflow\n/// to provide intelligent suggestions for partial inputs related to resources, prompts, or other referenceable entities.\n/// The completion mechanism in MCP allows clients to request suggestions based on partial inputs.\n/// The server will respond with a containing matching values.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteRequestParams : RequestParams\n{\n /// \n /// Gets or sets the reference's information.\n /// \n [JsonPropertyName(\"ref\")]\n public required Reference Ref { get; init; }\n\n /// \n /// Gets or sets the argument information for the completion request, specifying what is being completed\n /// and the current partial input.\n /// \n [JsonPropertyName(\"argument\")]\n public required Argument Argument { get; init; }\n\n /// \n /// Gets or sets additional, optional context for completions.\n /// \n [JsonPropertyName(\"context\")]\n public CompleteContext? Context { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/BlobResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the binary contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when binary data needs to be exchanged through\n/// the Model Context Protocol. The binary data is represented as a base64-encoded string\n/// in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for text-based resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class BlobResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the base64-encoded string representing the binary data of the item.\n /// \n [JsonPropertyName(\"blob\")]\n public string Blob { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/TextResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents text-based contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when textual data needs to be exchanged through\n/// the Model Context Protocol. The text is stored directly in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for binary resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class TextResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the text of the item.\n /// \n [JsonPropertyName(\"text\")]\n public string Text { get; set; } = string.Empty;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolAnnotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional properties describing a to clients.\n/// \n/// \n/// All properties in are hints.\n/// They are not guaranteed to provide a faithful description of tool behavior (including descriptive properties like `title`).\n/// Clients should never make tool use decisions based on received from untrusted servers.\n/// \npublic sealed class ToolAnnotations\n{\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"destructiveHint\")]\n public bool? DestructiveHint { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"idempotentHint\")]\n public bool? IdempotentHint { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"openWorldHint\")]\n public bool? OpenWorldHint { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"readOnlyHint\")]\n public bool? ReadOnlyHint { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Result.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads.\n/// \npublic abstract class Result\n{\n /// Prevent external derivations.\n private protected Result()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for notification parameters.\n/// \npublic abstract class NotificationParams\n{\n /// Prevent external derivations.\n private protected NotificationParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a resource provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting resource data.\n/// See the schema for details.\n/// \npublic sealed class ReadResourceRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available tools.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available tools on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many tools.\n/// The server can provide the property to indicate there are more\n/// tools available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListToolsResult : PaginatedResult\n{\n /// \n /// The server's response to a tools/list request from the client.\n /// \n [JsonPropertyName(\"tools\")]\n public IList Tools { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionId.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed class StatelessSessionId\n{\n [JsonPropertyName(\"clientInfo\")]\n public Implementation? ClientInfo { get; init; }\n\n [JsonPropertyName(\"userIdClaim\")]\n public UserIdClaim? UserIdClaim { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionIdJsonContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\n[JsonSerializable(typeof(StatelessSessionId))]\ninternal sealed partial class StatelessSessionIdJsonContext : JsonSerializerContext;\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/RequiredMemberAttribute.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Specifies that a type has required members or that a member is required.\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\n [EditorBrowsable(EditorBrowsableState.Never)]\n internal sealed class RequiredMemberAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/SetsRequiredMembersAttribute.cs", "#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]\n internal sealed class SetsRequiredMembersAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing members that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing members that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithResourcesFromAssembly, it enables automatic registration of resources without explicitly listing each\n/// resource class. The attribute is not necessary when a reference to the type is provided directly to a method\n/// like McpServerBuilderExtensions.WithResources.\n/// \n/// \n/// Within a class marked with this attribute, individual members that should be exposed as\n/// resources must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerResourceTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/TokenContainer.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a token response from the OAuth server.\n/// \ninternal sealed class TokenContainer\n{\n /// \n /// Gets or sets the access token.\n /// \n [JsonPropertyName(\"access_token\")]\n public string AccessToken { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the refresh token.\n /// \n [JsonPropertyName(\"refresh_token\")]\n public string? RefreshToken { get; set; }\n\n /// \n /// Gets or sets the number of seconds until the access token expires.\n /// \n [JsonPropertyName(\"expires_in\")]\n public int ExpiresIn { get; set; }\n\n /// \n /// Gets or sets the extended expiration time in seconds.\n /// \n [JsonPropertyName(\"ext_expires_in\")]\n public int ExtExpiresIn { get; set; }\n\n /// \n /// Gets or sets the token type (typically \"Bearer\").\n /// \n [JsonPropertyName(\"token_type\")]\n public string TokenType { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the scope of the access token.\n /// \n [JsonPropertyName(\"scope\")]\n public string Scope { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the timestamp when the token was obtained.\n /// \n [JsonIgnore]\n public DateTimeOffset ObtainedAt { get; set; }\n\n /// \n /// Gets the timestamp when the token expires, calculated from ObtainedAt and ExpiresIn.\n /// \n [JsonIgnore]\n public DateTimeOffset ExpiresAt => ObtainedAt.AddSeconds(ExpiresIn);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client,\n/// containing available resource templates.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover \n/// available resource templates on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resource templates.\n/// The server can provide the property to indicate there are more\n/// resource templates available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourceTemplatesResult : PaginatedResult\n{\n /// \n /// Gets or sets a list of resource templates that the server offers.\n /// \n /// \n /// This collection contains all the resource templates returned in the current page of results.\n /// Each provides metadata about resources available on the server,\n /// including URI templates, names, descriptions, and MIME types.\n /// \n [JsonPropertyName(\"resourceTemplates\")]\n public IList ResourceTemplates { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available resources.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available resources on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resources.\n/// The server can provide the property to indicate there are more\n/// resources available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourcesResult : PaginatedResult\n{\n /// \n /// A list of resources that the server offers.\n /// \n [JsonPropertyName(\"resources\")]\n public IList Resources { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Argument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument used in completion requests to provide context for auto-completion functionality.\n/// \n/// \n/// This class is used when requesting completion suggestions for a particular field or parameter.\n/// See the schema for details.\n/// \npublic sealed class Argument\n{\n /// \n /// Gets or sets the name of the argument being completed.\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the current partial text value for which completion suggestions are requested.\n /// \n /// \n /// This represents the text that has been entered so far and for which completion\n /// options should be generated.\n /// \n [JsonPropertyName(\"value\")]\n public string Value { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParamsMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides metadata related to the request that provides additional protocol-level information.\n/// \n/// \n/// This class contains properties that are used by the Model Context Protocol\n/// for features like progress tracking and other protocol-specific capabilities.\n/// \npublic sealed class RequestParamsMetadata\n{\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n /// \n /// The receiver is not obligated to provide these notifications.\n /// \n [JsonPropertyName(\"progressToken\")]\n public ProgressToken? ProgressToken { get; set; } = default!;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/ProgressNotificationValue.cs", "namespace ModelContextProtocol;\n\n/// Provides a progress value that can be sent using .\npublic sealed class ProgressNotificationValue\n{\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// \n /// This value typically represents either a percentage (0-100) or the number of items processed so far (when used with the property).\n /// \n /// \n /// When reporting progress, this value should increase monotonically as the operation proceeds.\n /// Values are typically between 0 and 100 when representing percentages, or can be any positive number\n /// when representing completed items in combination with the property.\n /// \n /// \n public required float Progress { get; init; }\n\n /// Gets or sets the total number of items to process (or total progress required), if known.\n public float? Total { get; init; }\n\n /// Gets or sets an optional message describing the current progress.\n public string? Message { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration request for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationRequest\n{\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public required string[] RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the human-readable name of the client.\n /// \n [JsonPropertyName(\"client_name\")]\n public string? ClientName { get; init; }\n\n /// \n /// Gets or sets the URL of the client's home page.\n /// \n [JsonPropertyName(\"client_uri\")]\n public string? ClientUri { get; init; }\n\n /// \n /// Gets or sets the scope values that the client will use.\n /// \n [JsonPropertyName(\"scope\")]\n public string? Scope { get; init; }\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class EchoTool\n{\n [McpServerTool(Name = \"echo\"), Description(\"Echoes the message back to the client.\")]\n public static string Echo(string message) => $\"Echo: {message}\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads that support cursor-based pagination.\n/// \n/// \n/// \n/// Pagination allows API responses to be broken into smaller, manageable chunks when\n/// there are potentially many results to return or when dynamically-computed results\n/// may incur measurable latency.\n/// \n/// \n/// Classes that inherit from implement cursor-based pagination,\n/// where the property serves as an opaque token pointing to the next \n/// set of results.\n/// \n/// \npublic abstract class PaginatedResult : Result\n{\n private protected PaginatedResult()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the pagination position after the last returned result.\n /// \n /// \n /// When a paginated result has more data available, the \n /// property will contain a non- token that can be used in subsequent requests\n /// to fetch the next page. When there are no more results to return, the property\n /// will be .\n /// \n public string? NextCursor { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available prompts.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available prompts on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many prompts.\n/// The server can provide the property to indicate there are more\n/// prompts available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListPromptsResult : PaginatedResult\n{\n /// \n /// A list of prompts or prompt templates that the server offers.\n /// \n [JsonPropertyName(\"prompts\")]\n public IList Prompts { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelPreferences.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's preferences for model selection, requested of the client during sampling.\n/// \n/// \n/// \n/// Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n/// rarely straightforward. Different models excel in different areas—some are\n/// faster but less capable, others are more capable but more expensive, and so\n/// on. This class allows servers to express their priorities across multiple\n/// dimensions to help clients make an appropriate selection for their use case.\n/// \n/// \n/// These preferences are always advisory. The client may ignore them. It is also\n/// up to the client to decide how to interpret these preferences and how to\n/// balance them against other considerations.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelPreferences\n{\n /// \n /// Gets or sets how much to prioritize cost when selecting a model.\n /// \n /// \n /// A value of 0 means cost is not important, while a value of 1 means cost is the most important factor.\n /// \n [JsonPropertyName(\"costPriority\")]\n public float? CostPriority { get; init; }\n\n /// \n /// Gets or sets optional hints to use for model selection.\n /// \n [JsonPropertyName(\"hints\")]\n public IReadOnlyList? Hints { get; init; }\n\n /// \n /// Gets or sets how much to prioritize sampling speed (latency) when selecting a model.\n /// \n /// \n /// A value of 0 means speed is not important, while a value of 1 means speed is the most important factor.\n /// \n [JsonPropertyName(\"speedPriority\")]\n public float? SpeedPriority { get; init; }\n\n /// \n /// Gets or sets how much to prioritize intelligence and capabilities when selecting a model.\n /// \n /// \n /// A value of 0 means intelligence is not important, while a value of 1 means intelligence is the most important factor.\n /// \n [JsonPropertyName(\"intelligencePriority\")]\n public float? IntelligencePriority { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithToolsFromAssembly, it enables automatic registration of tools without explicitly listing each tool\n/// class. The attribute is not necessary when a reference to the type is provided directly to a method like WithTools.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// tools must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerToolTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithPromptsFromAssembly, it enables automatic registration of prompts without explicitly listing each prompt class.\n/// The attribute is not necessary when a reference to the type is provided directly to a method like WithPrompts.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// prompts must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerPromptTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationServerMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the metadata about an OAuth authorization server.\n/// \ninternal sealed class AuthorizationServerMetadata\n{\n /// \n /// The authorization endpoint URI.\n /// \n [JsonPropertyName(\"authorization_endpoint\")]\n public Uri AuthorizationEndpoint { get; set; } = null!;\n\n /// \n /// The token endpoint URI.\n /// \n [JsonPropertyName(\"token_endpoint\")]\n public Uri TokenEndpoint { get; set; } = null!;\n\n /// \n /// The registration endpoint URI.\n /// \n [JsonPropertyName(\"registration_endpoint\")]\n public Uri? RegistrationEndpoint { get; set; }\n\n /// \n /// The revocation endpoint URI.\n /// \n [JsonPropertyName(\"revocation_endpoint\")]\n public Uri? RevocationEndpoint { get; set; }\n\n /// \n /// The response types supported by the authorization server.\n /// \n [JsonPropertyName(\"response_types_supported\")]\n public List? ResponseTypesSupported { get; set; }\n\n /// \n /// The grant types supported by the authorization server.\n /// \n [JsonPropertyName(\"grant_types_supported\")]\n public List? GrantTypesSupported { get; set; }\n\n /// \n /// The token endpoint authentication methods supported by the authorization server.\n /// \n [JsonPropertyName(\"token_endpoint_auth_methods_supported\")]\n public List? TokenEndpointAuthMethodsSupported { get; set; }\n\n /// \n /// The code challenge methods supported by the authorization server.\n /// \n [JsonPropertyName(\"code_challenge_methods_supported\")]\n public List? CodeChallengeMethodsSupported { get; set; }\n\n /// \n /// The issuer URI of the authorization server.\n /// \n [JsonPropertyName(\"issuer\")]\n public Uri? Issuer { get; set; }\n\n /// \n /// The scopes supported by the authorization server.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List? ScopesSupported { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/EmptyResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an empty result object for operations that need to indicate successful completion \n/// but don't need to return any specific data.\n/// \npublic sealed class EmptyResult : Result\n{\n [JsonIgnore]\n internal static EmptyResult Instance { get; } = new();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SetLevelRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to enable or adjust logging.\n/// \n/// \n/// This request allows clients to configure the level of logging information they want to receive from the server.\n/// The server will send notifications for log events at the specified level and all higher (more severe) levels.\n/// \npublic sealed class SetLevelRequestParams : RequestParams\n{\n /// \n /// Gets or sets the level of logging that the client wants to receive from the server. \n /// \n [JsonPropertyName(\"level\")]\n public required LoggingLevel Level { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelHint.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides hints to use for model selection.\n/// \n/// \n/// \n/// When multiple hints are specified in , they are evaluated in order,\n/// with the first match taking precedence. Clients should prioritize these hints over numeric priorities.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelHint\n{\n /// \n /// Gets or sets a hint for a model name.\n /// \n /// \n /// The specified string can be a partial or full model name. Clients may also \n /// map hints to equivalent models from different providers. Clients make the final model\n /// selection based on these preferences and their available models.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IMcpClient.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) client that connects to and communicates with an MCP server.\n/// \npublic interface IMcpClient : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the connected server.\n /// \n /// The client is not connected.\n ServerCapabilities ServerCapabilities { get; }\n\n /// \n /// Gets the implementation information of the connected server.\n /// \n /// \n /// \n /// This property provides identification details about the connected server, including its name and version.\n /// It is populated during the initialization handshake and is available after a successful connection.\n /// \n /// \n /// This information can be useful for logging, debugging, compatibility checks, and displaying server\n /// information to users.\n /// \n /// \n /// The client is not connected.\n Implementation ServerInfo { get; }\n\n /// \n /// Gets any instructions describing how to use the connected server and its features.\n /// \n /// \n /// \n /// This property contains instructions provided by the server during initialization that explain\n /// how to effectively use its capabilities. These instructions can include details about available\n /// tools, expected input formats, limitations, or any other helpful information.\n /// \n /// \n /// This can be used by clients to improve an LLM's understanding of available tools, prompts, and resources. \n /// It can be thought of like a \"hint\" to the model and may be added to a system prompt.\n /// \n /// \n string? ServerInstructions { get; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional context information for completion requests.\n/// \n/// \n/// This context provides information that helps the server generate more relevant \n/// completion suggestions, such as previously resolved variables in a template.\n/// \npublic sealed class CompleteContext\n{\n /// \n /// Gets or sets previously-resolved variables in a URI template or prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Implementation.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides the name and version of an MCP implementation.\n/// \n/// \n/// \n/// The class is used to identify MCP clients and servers during the initialization handshake.\n/// It provides version and name information that can be used for compatibility checks, logging, and debugging.\n/// \n/// \n/// Both clients and servers provide this information during connection establishment.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class Implementation : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the version of the implementation.\n /// \n /// \n /// The version is used during client-server handshake to identify implementation versions,\n /// which can be important for troubleshooting compatibility issues or when reporting bugs.\n /// \n [JsonPropertyName(\"version\")]\n public required string Version { get; set; }\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/AddTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AddTool\n{\n [McpServerTool(Name = \"add\"), Description(\"Adds two numbers.\")]\n public static string Add(int a, int b) => $\"The sum of {a} and {b} is {a + b}\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/HttpTransportMode.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Specifies the transport mode for HTTP client connections.\n/// \npublic enum HttpTransportMode\n{\n /// \n /// Automatically detect the appropriate transport by trying Streamable HTTP first, then falling back to SSE if that fails.\n /// This is the recommended mode for maximum compatibility.\n /// \n AutoDetect,\n\n /// \n /// Use only the Streamable HTTP transport.\n /// \n StreamableHttp,\n\n /// \n /// Use only the HTTP with SSE transport.\n /// \n Sse\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Role.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the type of role in the Model Context Protocol conversation.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum Role\n{\n /// \n /// Corresponds to a human user in the conversation.\n /// \n [JsonStringEnumMemberName(\"user\")]\n User,\n\n /// \n /// Corresponds to the AI assistant in the conversation.\n /// \n [JsonStringEnumMemberName(\"assistant\")]\n Assistant\n}"], ["/csharp-sdk/samples/AspNetCoreSseServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource, Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationResponse.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration response for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationResponse\n{\n /// \n /// Gets or sets the client identifier.\n /// \n [JsonPropertyName(\"client_id\")]\n public required string ClientId { get; init; }\n\n /// \n /// Gets or sets the client secret.\n /// \n [JsonPropertyName(\"client_secret\")]\n public string? ClientSecret { get; init; }\n\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public string[]? RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the client ID issued timestamp.\n /// \n [JsonPropertyName(\"client_id_issued_at\")]\n public long? ClientIdIssuedAt { get; init; }\n\n /// \n /// Gets or sets the client secret expiration time.\n /// \n [JsonPropertyName(\"client_secret_expires_at\")]\n public long? ClientSecretExpiresAt { get; init; }\n}"], ["/csharp-sdk/samples/EverythingServer/Prompts/SimplePromptType.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class SimplePromptType\n{\n [McpServerPrompt(Name = \"simple_prompt\"), Description(\"A prompt without arguments\")]\n public static string SimplePrompt() => \"This is a simple prompt without arguments\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PingResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request in the Model Context Protocol.\n/// \n/// \n/// \n/// The is returned in response to a request, \n/// which is used to verify that the connection between client and server is still alive and responsive. \n/// Since this is a simple connectivity check, the result is an empty object containing no data.\n/// \n/// \n/// Ping requests can be initiated by either the client or the server to check if the other party\n/// is still responsive.\n/// \n/// \npublic sealed class PingResult : Result;"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationDefaults.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Default values used by MCP authentication.\n/// \npublic static class McpAuthenticationDefaults\n{\n /// \n /// The default value used for authentication scheme name.\n /// \n public const string AuthenticationScheme = \"McpAuth\";\n\n /// \n /// The default value used for authentication scheme display name.\n /// \n public const string DisplayName = \"MCP Authentication\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/NopProgress.cs", "namespace ModelContextProtocol;\n\n/// Provides an that's a nop.\ninternal sealed class NullProgress : IProgress\n{\n /// \n /// Gets the singleton instance of the class that performs no operations when progress is reported.\n /// \n /// \n /// Use this property when you need to provide an implementation \n /// but don't need to track or report actual progress.\n /// \n public static NullProgress Instance { get; } = new();\n\n /// \n public void Report(ProgressNotificationValue value)\n {\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMemberTypes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Specifies the types of members that are dynamically accessed.\n///\n/// This enumeration has a attribute that allows a\n/// bitwise combination of its member values.\n/// \n[Flags]\ninternal enum DynamicallyAccessedMemberTypes\n{\n /// \n /// Specifies no members.\n /// \n None = 0,\n\n /// \n /// Specifies the default, parameterless public constructor.\n /// \n PublicParameterlessConstructor = 0x0001,\n\n /// \n /// Specifies all public constructors.\n /// \n PublicConstructors = 0x0002 | PublicParameterlessConstructor,\n\n /// \n /// Specifies all non-public constructors.\n /// \n NonPublicConstructors = 0x0004,\n\n /// \n /// Specifies all public methods.\n /// \n PublicMethods = 0x0008,\n\n /// \n /// Specifies all non-public methods.\n /// \n NonPublicMethods = 0x0010,\n\n /// \n /// Specifies all public fields.\n /// \n PublicFields = 0x0020,\n\n /// \n /// Specifies all non-public fields.\n /// \n NonPublicFields = 0x0040,\n\n /// \n /// Specifies all public nested types.\n /// \n PublicNestedTypes = 0x0080,\n\n /// \n /// Specifies all non-public nested types.\n /// \n NonPublicNestedTypes = 0x0100,\n\n /// \n /// Specifies all public properties.\n /// \n PublicProperties = 0x0200,\n\n /// \n /// Specifies all non-public properties.\n /// \n NonPublicProperties = 0x0400,\n\n /// \n /// Specifies all public events.\n /// \n PublicEvents = 0x0800,\n\n /// \n /// Specifies all non-public events.\n /// \n NonPublicEvents = 0x1000,\n\n /// \n /// Specifies all interfaces implemented by the type.\n /// \n Interfaces = 0x2000,\n\n /// \n /// Specifies all non-public constructors, including those inherited from base classes.\n /// \n NonPublicConstructorsWithInherited = NonPublicConstructors | 0x4000,\n\n /// \n /// Specifies all non-public methods, including those inherited from base classes.\n /// \n NonPublicMethodsWithInherited = NonPublicMethods | 0x8000,\n\n /// \n /// Specifies all non-public fields, including those inherited from base classes.\n /// \n NonPublicFieldsWithInherited = NonPublicFields | 0x10000,\n\n /// \n /// Specifies all non-public nested types, including those inherited from base classes.\n /// \n NonPublicNestedTypesWithInherited = NonPublicNestedTypes | 0x20000,\n\n /// \n /// Specifies all non-public properties, including those inherited from base classes.\n /// \n NonPublicPropertiesWithInherited = NonPublicProperties | 0x40000,\n\n /// \n /// Specifies all non-public events, including those inherited from base classes.\n /// \n NonPublicEventsWithInherited = NonPublicEvents | 0x80000,\n\n /// \n /// Specifies all public constructors, including those inherited from base classes.\n /// \n PublicConstructorsWithInherited = PublicConstructors | 0x100000,\n\n /// \n /// Specifies all public nested types, including those inherited from base classes.\n /// \n PublicNestedTypesWithInherited = PublicNestedTypes | 0x200000,\n\n /// \n /// Specifies all constructors, including those inherited from base classes.\n /// \n AllConstructors = PublicConstructorsWithInherited | NonPublicConstructorsWithInherited,\n\n /// \n /// Specifies all methods, including those inherited from base classes.\n /// \n AllMethods = PublicMethods | NonPublicMethodsWithInherited,\n\n /// \n /// Specifies all fields, including those inherited from base classes.\n /// \n AllFields = PublicFields | NonPublicFieldsWithInherited,\n\n /// \n /// Specifies all nested types, including those inherited from base classes.\n /// \n AllNestedTypes = PublicNestedTypesWithInherited | NonPublicNestedTypesWithInherited,\n\n /// \n /// Specifies all properties, including those inherited from base classes.\n /// \n AllProperties = PublicProperties | NonPublicPropertiesWithInherited,\n\n /// \n /// Specifies all events, including those inherited from base classes.\n /// \n AllEvents = PublicEvents | NonPublicEventsWithInherited,\n\n /// \n /// Specifies all members.\n /// \n All = ~None\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol/IMcpServerBuilder.cs", "using ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides a builder for configuring instances.\n/// \n/// \n/// \n/// The interface provides a fluent API for configuring Model Context Protocol (MCP) servers\n/// when using dependency injection. It exposes methods for registering tools, prompts, custom request handlers,\n/// and server transports, allowing for comprehensive server configuration through a chain of method calls.\n/// \n/// \n/// The builder is obtained from the extension\n/// method and provides access to the underlying service collection via the property.\n/// \n/// \npublic interface IMcpServerBuilder\n{\n /// \n /// Gets the associated service collection.\n /// \n IServiceCollection Services { get; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCollection.cs", "namespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their URI templates.\npublic sealed class McpServerResourceCollection()\n : McpServerPrimitiveCollection(UriTemplate.UriTemplateComparer.Instance);"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of tools available from the server.\n/// \n/// \n/// The server responds with a containing the available tools.\n/// See the schema for details.\n/// \npublic sealed class ListToolsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resources available from the server.\n/// \n/// \n/// The server responds with a containing the available resources.\n/// See the schema for details.\n/// \npublic sealed class ListResourcesRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of prompts available from the server.\n/// \n/// \n/// The server responds with a containing the available prompts.\n/// See the schema for details.\n/// \npublic sealed class ListPromptsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a server to request\n/// a list of roots available from the client.\n/// \n/// \n/// The client responds with a containing the client's roots.\n/// See the schema for details.\n/// \npublic sealed class ListRootsRequestParams : RequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resource templates available from the server.\n/// \n/// \n/// The server responds with a containing the available resource templates.\n/// See the schema for details.\n/// \npublic sealed class ListResourceTemplatesRequestParams : PaginatedRequestParams;"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/UserIdClaim.cs", "namespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed record UserIdClaim(string Type, string Value, string Issuer);\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the client to the server, informing it that the list of roots has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of tools it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ToolListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptListChangedNotification .cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of prompts it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of resources it can read from has changed. \n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// sent from the client to the server after initialization has finished.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class InitializedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServerPrimitive.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Represents an MCP server primitive, like a tool or a prompt.\n/// \npublic interface IMcpServerPrimitive\n{\n /// Gets the unique identifier of the primitive.\n string Id { get; }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 18:38:49", "created_task_model": "DeepSeek-R1", "class_skeleton": "internal\nclass\nMcpHttpClient\n(HttpClient httpClient)\n{\ninternal virtual async Task SendAsync (HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken) {}\nprivate HttpContent? CreatePostBodyContent (JsonRpcMessage? message) {}\n}", "code_description": "This code segment functions to: Construct and send HTTP POST requests containing serialized JSON-RPC payloads while handling framework-specific content creation and ensuring proper resource disposal during network communication."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\ninternal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n try\n {\n request.Content = CreatePostBodyContent(message);\n return await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);\n }\n catch (HttpRequestException ex)\n {\n if (Activity.Current != null)\n {\n Activity.Current.AddTag(\"error.type\", ex.GetType().FullName);\n Activity.Current.AddTag(\"error.message\", ex.Message);\n }\n throw;\n }\n }\n\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null) return null;\n\n#if NET\n return JsonContent.Create(message);\n#else\n var json = JsonSerializer.Serialize(message);\n return new StringContent(json, Encoding.UTF8, \"application/json\");\n#endif\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-39-11"}, "editdistance_info": {"edit_distance": 43.2558, "calculate_time": "2025-08-20 18:39:11", "true_code_clean": "internal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n Debug.Assert(request.Content is null, \"The request body should only be supplied as a JsonRpcMessage\");\n Debug.Assert(message is null || request.Method == HttpMethod.Post, \"All messages should be sent in POST requests.\");\n using var content = CreatePostBodyContent(message);\n request.Content = content;\n return await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);\n }\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null)\n {\n return null;\n }\n#if NET\n return JsonContent.Create(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n#else\n return new StringContent(\n JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage),\n Encoding.UTF8,\n \"application/json\"\n );\n#endif\n }\n}", "predict_code_clean": "internal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n try\n {\n request.Content = CreatePostBodyContent(message);\n return await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);\n }\n catch (HttpRequestException ex)\n {\n if (Activity.Current != null)\n {\n Activity.Current.AddTag(\"error.type\", ex.GetType().FullName);\n Activity.Current.AddTag(\"error.message\", ex.Message);\n }\n throw;\n }\n }\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null) return null;\n#if NET\n return JsonContent.Create(message);\n#else\n var json = JsonSerializer.Serialize(message);\n return new StringContent(json, Encoding.UTF8, \"application/json\");\n#endif\n }\n}"}} {"repo_name": "csharp-sdk", "file_name": "/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcRequest.cs", "inference_info": {"prefix_code": "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A request message in the JSON-RPC protocol.\n/// \n/// \n/// Requests are messages that require a response from the receiver. Each request includes a unique ID\n/// that will be included in the corresponding response message (either a success response or an error).\n/// \n/// The receiver of a request message is expected to execute the specified method with the provided parameters\n/// and return either a with the result, or a \n/// if the method execution fails.\n/// \n", "suffix_code": "\n", "middle_code": "public sealed class JsonRpcRequest : JsonRpcMessageWithId\n{\n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n internal JsonRpcRequest WithId(RequestId id)\n {\n return new JsonRpcRequest\n {\n JsonRpc = JsonRpc,\n Id = id,\n Method = Method,\n Params = Params,\n RelatedTransport = RelatedTransport,\n };\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessage.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents any JSON-RPC message used in the Model Context Protocol (MCP).\n/// \n/// \n/// This interface serves as the foundation for all message types in the JSON-RPC 2.0 protocol\n/// used by MCP, including requests, responses, notifications, and errors. JSON-RPC is a stateless,\n/// lightweight remote procedure call (RPC) protocol that uses JSON as its data format.\n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessage()\n {\n }\n\n /// \n /// Gets the JSON-RPC protocol version used.\n /// \n /// \n [JsonPropertyName(\"jsonrpc\")]\n public string JsonRpc { get; init; } = \"2.0\";\n\n /// \n /// Gets or sets the transport the was received on or should be sent over.\n /// \n /// \n /// This is used to support the Streamable HTTP transport where the specification states that the server\n /// SHOULD include JSON-RPC responses in the HTTP response body for the POST request containing\n /// the corresponding JSON-RPC request. It may be for other transports.\n /// \n [JsonIgnore]\n public ITransport? RelatedTransport { get; set; }\n\n /// \n /// Gets or sets the that should be used to run any handlers\n /// \n /// \n /// This is used to support the Streamable HTTP transport in its default stateful mode. In this mode,\n /// the outlives the initial HTTP request context it was created on, and new\n /// JSON-RPC messages can originate from future HTTP requests. This allows the transport to flow the\n /// context with the JSON-RPC message. This is particularly useful for enabling IHttpContextAccessor\n /// in tool calls.\n /// \n [JsonIgnore]\n public ExecutionContext? ExecutionContext { get; set; }\n\n /// \n /// Provides a for messages,\n /// handling polymorphic deserialization of different message types.\n /// \n /// \n /// \n /// This converter is responsible for correctly deserializing JSON-RPC messages into their appropriate\n /// concrete types based on the message structure. It analyzes the JSON payload and determines if it\n /// represents a request, notification, successful response, or error response.\n /// \n /// \n /// The type determination rules follow the JSON-RPC 2.0 specification:\n /// \n /// Messages with \"method\" and \"id\" properties are deserialized as .\n /// Messages with \"method\" but no \"id\" property are deserialized as .\n /// Messages with \"id\" and \"result\" properties are deserialized as .\n /// Messages with \"id\" and \"error\" properties are deserialized as .\n /// \n /// \n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override JsonRpcMessage? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException(\"Expected StartObject token\");\n }\n\n using var doc = JsonDocument.ParseValue(ref reader);\n var root = doc.RootElement;\n\n // All JSON-RPC messages must have a jsonrpc property with value \"2.0\"\n if (!root.TryGetProperty(\"jsonrpc\", out var versionProperty) ||\n versionProperty.GetString() != \"2.0\")\n {\n throw new JsonException(\"Invalid or missing jsonrpc version\");\n }\n\n // Determine the message type based on the presence of id, method, and error properties\n bool hasId = root.TryGetProperty(\"id\", out _);\n bool hasMethod = root.TryGetProperty(\"method\", out _);\n bool hasError = root.TryGetProperty(\"error\", out _);\n\n var rawText = root.GetRawText();\n\n // Messages with an id but no method are responses\n if (hasId && !hasMethod)\n {\n // Messages with an error property are error responses\n if (hasError)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with a result property are success responses\n if (root.TryGetProperty(\"result\", out _))\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Response must have either result or error\");\n }\n\n // Messages with a method but no id are notifications\n if (hasMethod && !hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with both method and id are requests\n if (hasMethod && hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Invalid JSON-RPC message format\");\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, JsonRpcMessage value, JsonSerializerOptions options)\n {\n switch (value)\n {\n case JsonRpcRequest request:\n JsonSerializer.Serialize(writer, request, options.GetTypeInfo());\n break;\n case JsonRpcNotification notification:\n JsonSerializer.Serialize(writer, notification, options.GetTypeInfo());\n break;\n case JsonRpcResponse response:\n JsonSerializer.Serialize(writer, response, options.GetTypeInfo());\n break;\n case JsonRpcError error:\n JsonSerializer.Serialize(writer, error, options.GetTypeInfo());\n break;\n default:\n throw new JsonException($\"Unknown JSON-RPC message type: {value.GetType()}\");\n }\n }\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/Protocol/JsonRpcResponse.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A successful response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Response messages are sent in reply to a request message and contain the result of the method execution.\n/// Each response includes the same ID as the original request, allowing the sender to match responses\n/// with their corresponding requests.\n/// \n/// \n/// This class represents a successful response with a result. For error responses, see .\n/// \n/// \npublic sealed class JsonRpcResponse : JsonRpcMessageWithId\n{\n /// \n /// Gets the result of the method invocation.\n /// \n /// \n /// This property contains the result data returned by the server in response to the JSON-RPC method request.\n /// \n [JsonPropertyName(\"result\")]\n public required JsonNode? Result { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcNotification.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification message in the JSON-RPC protocol.\n/// \n/// \n/// Notifications are messages that do not require a response and are not matched with a response message.\n/// They are useful for one-way communication, such as log notifications and progress updates.\n/// Unlike requests, notifications do not include an ID field, since there will be no response to match with it.\n/// \npublic sealed class JsonRpcNotification : JsonRpcMessage\n{\n /// \n /// Gets or sets the name of the notification method.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Gets or sets optional parameters for the notification.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpEndpointExtensions.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class provides strongly-typed methods for working with the Model Context Protocol (MCP) endpoints,\n/// simplifying JSON-RPC communication by handling serialization and deserialization of parameters and results.\n/// \n/// \n/// These extension methods are designed to be used with both client () and\n/// server () implementations of the interface.\n/// \n/// \npublic static class McpEndpointExtensions\n{\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The request id for the request.\n /// The options governing request serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n public static ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo paramsTypeInfo = serializerOptions.GetTypeInfo();\n JsonTypeInfo resultTypeInfo = serializerOptions.GetTypeInfo();\n return SendRequestAsync(endpoint, method, parameters, paramsTypeInfo, resultTypeInfo, requestId, cancellationToken);\n }\n\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The type information for request parameter deserialization.\n /// The request id for the request.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n internal static async ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n JsonTypeInfo resultTypeInfo,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n Throw.IfNull(resultTypeInfo);\n\n JsonRpcRequest jsonRpcRequest = new()\n {\n Id = requestId,\n Method = method,\n Params = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo),\n };\n\n JsonRpcResponse response = await endpoint.SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.Deserialize(response.Result, resultTypeInfo) ?? throw new JsonException(\"Unexpected JSON result in response.\");\n }\n\n /// \n /// Sends a parameterless notification to the connected endpoint.\n /// \n /// The MCP client or server instance.\n /// The notification method name.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification without any parameters. Notifications are one-way messages \n /// that don't expect a response. They are commonly used for events, status updates, or to signal \n /// changes in state.\n /// \n /// \n public static Task SendNotificationAsync(this IMcpEndpoint client, string method, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(method);\n return client.SendMessageAsync(new JsonRpcNotification { Method = method }, cancellationToken);\n }\n\n /// \n /// Sends a notification with parameters to the connected endpoint.\n /// \n /// The type of the notification parameters to serialize.\n /// The MCP client or server instance.\n /// The JSON-RPC method name for the notification.\n /// Object representing the notification parameters.\n /// The options governing parameter serialization. If null, default options are used.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification with parameters to the connected endpoint. Notifications are one-way \n /// messages that don't expect a response, commonly used for events, status updates, or signaling changes.\n /// \n /// \n /// The parameters object is serialized to JSON according to the provided serializer options or the default \n /// options if none are specified.\n /// \n /// \n /// The Model Context Protocol defines several standard notification methods in ,\n /// but custom methods can also be used for application-specific notifications.\n /// \n /// \n public static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo parametersTypeInfo = serializerOptions.GetTypeInfo();\n return SendNotificationAsync(endpoint, method, parameters, parametersTypeInfo, cancellationToken);\n }\n\n /// \n /// Sends a notification to the server with parameters.\n /// \n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The to monitor for cancellation requests. The default is .\n internal static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n\n JsonNode? parametersJson = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo);\n return endpoint.SendMessageAsync(new JsonRpcNotification { Method = method, Params = parametersJson }, cancellationToken);\n }\n\n /// \n /// Notifies the connected endpoint of progress for a long-running operation.\n /// \n /// The endpoint issuing the notification.\n /// The identifying the operation for which progress is being reported.\n /// The progress update to send, containing information such as percentage complete or status message.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the completion of the notification operation (not the operation being tracked).\n /// is .\n /// \n /// \n /// This method sends a progress notification to the connected endpoint using the Model Context Protocol's\n /// standardized progress notification format. Progress updates are identified by a \n /// that allows the recipient to correlate multiple updates with a specific long-running operation.\n /// \n /// \n /// Progress notifications are sent asynchronously and don't block the operation from continuing.\n /// \n /// \n public static Task NotifyProgressAsync(\n this IMcpEndpoint endpoint,\n ProgressToken progressToken,\n ProgressNotificationValue progress, \n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n\n return endpoint.SendNotificationAsync(\n NotificationMethods.ProgressNotification,\n new ProgressNotificationParams\n {\n ProgressToken = progressToken,\n Progress = progress,\n },\n McpJsonUtilities.JsonContext.Default.ProgressNotificationParams,\n cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessageWithId.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC message used in the Model Context Protocol (MCP) and that includes an ID.\n/// \n/// \n/// In the JSON-RPC protocol, messages with an ID require a response from the receiver.\n/// This includes request messages (which expect a matching response) and response messages\n/// (which include the ID of the original request they're responding to).\n/// The ID is used to correlate requests with their responses, allowing asynchronous\n/// communication where multiple requests can be sent without waiting for responses.\n/// \npublic abstract class JsonRpcMessageWithId : JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessageWithId()\n {\n }\n\n /// \n /// Gets the message identifier.\n /// \n /// \n /// Each ID is expected to be unique within the context of a given session.\n /// \n [JsonPropertyName(\"id\")]\n public RequestId Id { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as\n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \npublic sealed class StreamableHttpServerTransport : ITransport\n{\n // For JsonRpcMessages without a RelatedTransport, we don't want to block just because the client didn't make a GET request to handle unsolicited messages.\n private readonly SseWriter _sseWriter = new(channelOptions: new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n FullMode = BoundedChannelFullMode.DropOldest,\n });\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n private readonly CancellationTokenSource _disposeCts = new();\n\n private int _getRequestStarted;\n\n /// \n public string? SessionId { get; set; }\n\n /// \n /// Configures whether the transport should be in stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process. Unsolicited server-to-client messages are not supported in this mode,\n /// so calling results in an .\n /// Server-to-client requests are also unsupported, because the responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// \n public bool Stateless { get; init; }\n\n /// \n /// Gets a value indicating whether the execution context should flow from the calls to \n /// to the corresponding emitted by the .\n /// \n /// \n /// Defaults to .\n /// \n public bool FlowExecutionContextFromRequests { get; init; }\n\n /// \n /// Gets or sets a callback to be invoked before handling the initialize request.\n /// \n public Func? OnInitRequestReceived { get; set; }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n internal ChannelWriter MessageWriter => _incomingChannel.Writer;\n\n /// \n /// Handles an optional SSE GET request a client using the Streamable HTTP transport might make by\n /// writing any unsolicited JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The response stream to write MCP JSON-RPC messages as SSE events to.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task HandleGetRequest(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"GET requests are not supported in stateless mode.\");\n }\n\n if (Interlocked.Exchange(ref _getRequestStarted, 1) == 1)\n {\n throw new InvalidOperationException(\"Session resumption is not yet supported. Please start a new session.\");\n }\n\n // We do not need to reference _disposeCts like in HandlePostRequest, because the session ending completes the _sseWriter gracefully.\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles a Streamable HTTP POST request processing both the request body and response body ensuring that\n /// and other correlated messages are sent back to the client directly in response\n /// to the that initiated the message.\n /// \n /// The duplex pipe facilitates the reading and writing of HTTP request and response data.\n /// This token allows for the operation to be canceled if needed.\n /// \n /// True, if data was written to the response body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async Task HandlePostRequest(IDuplexPipe httpBodies, CancellationToken cancellationToken)\n {\n using var postCts = CancellationTokenSource.CreateLinkedTokenSource(_disposeCts.Token, cancellationToken);\n await using var postTransport = new StreamableHttpPostTransport(this, httpBodies);\n return await postTransport.RunAsync(postCts.Token).ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"Unsolicited server to client messages are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n }\n finally\n {\n try\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n finally\n {\n _disposeCts.Dispose();\n }\n }\n }\n}\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/Protocol/JsonRpcError.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an error response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Error responses are sent when a request cannot be fulfilled or encounters an error during processing.\n/// Like successful responses, error messages include the same ID as the original request, allowing the\n/// sender to match errors with their corresponding requests.\n/// \n/// \n/// Each error response contains a structured error detail object with a numeric code, descriptive message,\n/// and optional additional data to provide more context about the error.\n/// \n/// \npublic sealed class JsonRpcError : JsonRpcMessageWithId\n{\n /// \n /// Gets detailed error information for the failed request, containing an error code, \n /// message, and optional additional data\n /// \n [JsonPropertyName(\"error\")]\n public required JsonRpcErrorDetail Error { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Net.ServerSentEvents;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Handles processing the request/response body pairs for the Streamable HTTP transport.\n/// This is typically used via .\n/// \ninternal sealed class StreamableHttpPostTransport(StreamableHttpServerTransport parentTransport, IDuplexPipe httpBodies) : ITransport\n{\n private readonly SseWriter _sseWriter = new();\n private RequestId _pendingRequest;\n\n public ChannelReader MessageReader => throw new NotSupportedException(\"JsonRpcMessage.RelatedTransport should only be used for sending messages.\");\n\n string? ITransport.SessionId => parentTransport.SessionId;\n\n /// \n /// True, if data was written to the respond body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async ValueTask RunAsync(CancellationToken cancellationToken)\n {\n var message = await JsonSerializer.DeserializeAsync(httpBodies.Input.AsStream(),\n McpJsonUtilities.JsonContext.Default.JsonRpcMessage, cancellationToken).ConfigureAwait(false);\n await OnMessageReceivedAsync(message, cancellationToken).ConfigureAwait(false);\n\n if (_pendingRequest.Id is null)\n {\n return false;\n }\n\n _sseWriter.MessageFilter = StopOnFinalResponseFilter;\n await _sseWriter.WriteAllAsync(httpBodies.Output.AsStream(), cancellationToken).ConfigureAwait(false);\n return true;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (parentTransport.Stateless && message is JsonRpcRequest)\n {\n throw new InvalidOperationException(\"Server to client requests are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n private async IAsyncEnumerable> StopOnFinalResponseFilter(IAsyncEnumerable> messages, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n await foreach (var message in messages.WithCancellation(cancellationToken))\n {\n yield return message;\n\n if (message.Data is JsonRpcResponse or JsonRpcError && ((JsonRpcMessageWithId)message.Data).Id == _pendingRequest)\n {\n // Complete the SSE response stream now that all pending requests have been processed.\n break;\n }\n }\n }\n\n private async ValueTask OnMessageReceivedAsync(JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (message is null)\n {\n throw new InvalidOperationException(\"Received invalid null message.\");\n }\n\n if (message is JsonRpcRequest request)\n {\n _pendingRequest = request.Id;\n\n // Invoke the initialize request callback if applicable.\n if (parentTransport.OnInitRequestReceived is { } onInitRequest && request.Method == RequestMethods.Initialize)\n {\n var initializeRequest = JsonSerializer.Deserialize(request.Params, McpJsonUtilities.JsonContext.Default.InitializeRequestParams);\n await onInitRequest(initializeRequest).ConfigureAwait(false);\n }\n }\n\n message.RelatedTransport = this;\n\n if (parentTransport.FlowExecutionContextFromRequests)\n {\n message.ExecutionContext = ExecutionContext.Capture();\n }\n\n await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\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 posts.\n internal static UserIdClaim? GetUserIdClaim(ClaimsPrincipal user)\n {\n if (user?.Identity?.IsAuthenticated != true)\n {\n return null;\n }\n\n var claim = user.FindFirst(ClaimTypes.NameIdentifier) ?? user.FindFirst(\"sub\") ?? user.FindFirst(ClaimTypes.Upn);\n\n if (claim is { } idClaim)\n {\n return new(idClaim.Type, idClaim.Value, idClaim.Issuer);\n }\n\n return null;\n }\n\n private static JsonTypeInfo GetRequiredJsonTypeInfo() => (JsonTypeInfo)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));\n\n private static bool MatchesApplicationJsonMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"application/json\");\n\n private static bool MatchesTextEventStreamMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"text/event-stream\");\n\n private sealed class HttpDuplexPipe(HttpContext context) : IDuplexPipe\n {\n public PipeReader Input => context.Request.BodyReader;\n public PipeWriter Output => context.Response.BodyWriter;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/IMcpEndpoint.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Represents a client or server Model Context Protocol (MCP) endpoint.\n/// \n/// \n/// \n/// The MCP endpoint provides the core communication functionality used by both clients and servers:\n/// \n/// Sending JSON-RPC requests and receiving responses.\n/// Sending notifications to the connected endpoint.\n/// Registering handlers for receiving notifications.\n/// \n/// \n/// \n/// serves as the base interface for both and \n/// interfaces, providing the common functionality needed for MCP protocol \n/// communication. Most applications will use these more specific interfaces rather than working with \n/// directly.\n/// \n/// \n/// All MCP endpoints should be properly disposed after use as they implement .\n/// \n/// \npublic interface IMcpEndpoint : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Sends a JSON-RPC request to the connected endpoint and waits for a response.\n /// \n /// The JSON-RPC request to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the endpoint's response.\n /// The transport is not connected, or another error occurs during request processing.\n /// An error occured during request processing.\n /// \n /// This method provides low-level access to send raw JSON-RPC requests. For most use cases,\n /// consider using the strongly-typed extension methods that provide a more convenient API.\n /// \n Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default);\n\n /// \n /// Sends a JSON-RPC message to the connected endpoint.\n /// \n /// \n /// The JSON-RPC message to send. This can be any type that implements JsonRpcMessage, such as\n /// JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, or JsonRpcError.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// is .\n /// \n /// \n /// This method provides low-level access to send any JSON-RPC message. For specific message types,\n /// consider using the higher-level methods such as or extension methods\n /// like ,\n /// which provide a simpler API.\n /// \n /// \n /// The method will serialize the message and transmit it using the underlying transport mechanism.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n\n /// Registers a handler to be invoked when a notification for the specified method is received.\n /// The notification method.\n /// The handler to be invoked.\n /// An that will remove the registered handler when disposed.\n IAsyncDisposable RegisterNotificationHandler(string method, Func handler);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/RequestHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\ninternal sealed class RequestHandlers : Dictionary>>\n{\n /// \n /// Registers a handler for incoming requests of a specific method in the MCP protocol.\n /// \n /// Type of request payload that will be deserialized from incoming JSON\n /// Type of response payload that will be serialized to JSON (not full RPC response)\n /// Method identifier to register for (e.g., \"tools/list\", \"logging/setLevel\")\n /// Handler function to be called when a request with the specified method identifier is received\n /// The JSON contract governing request parameter deserialization\n /// The JSON contract governing response serialization\n /// \n /// \n /// This method is used internally by the MCP infrastructure to register handlers for various protocol methods.\n /// When an incoming request matches the specified method, the registered handler will be invoked with the\n /// deserialized request parameters.\n /// \n /// \n /// The handler function receives the deserialized request object and a cancellation token, and should return\n /// a response object that will be serialized back to the client.\n /// \n /// \n public void Set(\n string method,\n Func> handler,\n JsonTypeInfo requestTypeInfo,\n JsonTypeInfo responseTypeInfo)\n {\n Throw.IfNull(method);\n Throw.IfNull(handler);\n Throw.IfNull(requestTypeInfo);\n Throw.IfNull(responseTypeInfo);\n\n this[method] = async (request, cancellationToken) =>\n {\n TRequest? typedRequest = JsonSerializer.Deserialize(request.Params, requestTypeInfo);\n object? result = await handler(typedRequest, request.RelatedTransport, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToNode(result, responseTypeInfo);\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcErrorDetail.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents detailed error information for JSON-RPC error responses.\n/// \n/// \n/// This class is used as part of the message to provide structured \n/// error information when a request cannot be fulfilled. The JSON-RPC 2.0 specification defines\n/// a standard format for error responses that includes a numeric code, a human-readable message,\n/// and optional additional data.\n/// \npublic sealed class JsonRpcErrorDetail\n{\n /// \n /// Gets an integer error code according to the JSON-RPC specification.\n /// \n [JsonPropertyName(\"code\")]\n public required int Code { get; init; }\n\n /// \n /// Gets a short description of the error.\n /// \n /// \n /// This is expected to be a brief, human-readable explanation of what went wrong.\n /// For standard error codes, it's recommended to use the descriptions defined \n /// in the JSON-RPC 2.0 specification.\n /// \n [JsonPropertyName(\"message\")]\n public required string Message { get; init; }\n\n /// \n /// Gets optional additional error data.\n /// \n /// \n /// This property can contain any additional information that might help the client\n /// understand or resolve the error. Common examples include validation errors,\n /// stack traces (in development environments), or contextual information about\n /// the error condition.\n /// \n [JsonPropertyName(\"data\")]\n public object? Data { get; init; }\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.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/Server/SseResponseStreamTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as \n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \n/// The response stream to write MCP JSON-RPC messages as SSE events to.\n/// \n/// The relative or absolute URI the client should use to post MCP JSON-RPC messages for this session.\n/// These messages should be passed to .\n/// Defaults to \"/message\".\n/// \n/// The identifier corresponding to the current MCP session.\npublic sealed class SseResponseStreamTransport(Stream sseResponseStream, string? messageEndpoint = \"/message\", string? sessionId = null) : ITransport\n{\n private readonly SseWriter _sseWriter = new(messageEndpoint);\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private bool _isConnected;\n\n /// \n /// Starts the transport and writes the JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task RunAsync(CancellationToken cancellationToken)\n {\n _isConnected = true;\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n /// \n public string? SessionId { get; } = sessionId;\n\n /// \n public async ValueTask DisposeAsync()\n {\n _isConnected = false;\n _incomingChannel.Writer.TryComplete();\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles incoming JSON-RPC messages received on the /message endpoint.\n /// \n /// The JSON-RPC message received from the client.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation to buffer the JSON-RPC message for processing.\n /// Thrown when there is an attempt to process a message before calling .\n /// \n /// \n /// This method is the entry point for processing client-to-server communication in the SSE transport model. \n /// While the SSE protocol itself is unidirectional (server to client), this method allows bidirectional \n /// communication by handling HTTP POST requests sent to the message endpoint.\n /// \n /// \n /// When a client sends a JSON-RPC message to the /message endpoint, the server calls this method to\n /// process the message and make it available to the MCP server via the channel.\n /// \n /// \n /// This method validates that the transport is connected before processing the message, ensuring proper\n /// sequencing of operations in the transport lifecycle.\n /// \n /// \n public async Task OnMessageReceivedAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n Throw.IfNull(message);\n\n if (!_isConnected)\n {\n throw new InvalidOperationException($\"Transport is not connected. Make sure to call {nameof(RunAsync)} first.\");\n }\n\n await _incomingChannel.Writer.WriteAsync(message, cancellationToken).ConfigureAwait(false);\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/Protocol/CallToolResult.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// \n/// Any errors that originate from the tool should be reported inside the result\n/// object, with set to true, rather than as a .\n/// \n/// \n/// However, any errors in finding the tool, an error indicating that the\n/// server does not support tool calls, or any other exceptional conditions,\n/// should be reported as an MCP error response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CallToolResult : Result\n{\n /// \n /// Gets or sets the response content from the tool call.\n /// \n [JsonPropertyName(\"content\")]\n public IList Content { get; set; } = [];\n\n /// \n /// Gets or sets an optional JSON object representing the structured result of the tool call.\n /// \n [JsonPropertyName(\"structuredContent\")]\n public JsonNode? StructuredContent { get; set; }\n\n /// \n /// Gets or sets an indication of whether the tool call was unsuccessful.\n /// \n /// \n /// When set to , it signifies that the tool execution failed.\n /// Tool errors are reported with this property set to and details in the \n /// property, rather than as protocol-level errors. This allows LLMs to see that an error occurred\n /// and potentially self-correct in subsequent requests.\n /// \n [JsonPropertyName(\"isError\")]\n public bool? IsError { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpJsonUtilities.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Authentication;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// Provides a collection of utility methods for working with JSON data in the context of MCP.\npublic static partial class McpJsonUtilities\n{\n /// \n /// Gets the singleton used as the default in JSON serialization operations.\n /// \n /// \n /// \n /// For Native AOT or applications disabling , this instance \n /// includes source generated contracts for all common exchange types contained in the ModelContextProtocol library.\n /// \n /// \n /// It additionally turns on the following settings:\n /// \n /// Enables defaults.\n /// Enables as the default ignore condition for properties.\n /// Enables as the default number handling for number types.\n /// \n /// \n /// \n public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();\n\n /// \n /// Creates default options to use for MCP-related serialization.\n /// \n /// The configured options.\n [UnconditionalSuppressMessage(\"ReflectionAnalysis\", \"IL3050:RequiresDynamicCode\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n [UnconditionalSuppressMessage(\"Trimming\", \"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n private static JsonSerializerOptions CreateDefaultOptions()\n {\n // Copy the configuration from the source generated context.\n JsonSerializerOptions options = new(JsonContext.Default.Options);\n\n // Chain with all supported types from MEAI.\n options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);\n\n // Add a converter for user-defined enums, if reflection is enabled by default.\n if (JsonSerializer.IsReflectionEnabledByDefault)\n {\n options.Converters.Add(new CustomizableJsonStringEnumConverter());\n }\n\n options.MakeReadOnly();\n return options;\n }\n\n internal static JsonTypeInfo GetTypeInfo(this JsonSerializerOptions options) =>\n (JsonTypeInfo)options.GetTypeInfo(typeof(T));\n\n internal static JsonElement DefaultMcpToolSchema { get; } = ParseJsonElement(\"\"\"{\"type\":\"object\"}\"\"\"u8);\n internal static object? AsObject(this JsonElement element) => element.ValueKind is JsonValueKind.Null ? null : element;\n\n internal static bool IsValidMcpToolSchema(JsonElement element)\n {\n if (element.ValueKind is not JsonValueKind.Object)\n {\n return false;\n }\n\n foreach (JsonProperty property in element.EnumerateObject())\n {\n if (property.NameEquals(\"type\"))\n {\n if (property.Value.ValueKind is not JsonValueKind.String ||\n !property.Value.ValueEquals(\"object\"))\n {\n return false;\n }\n\n return true; // No need to check other properties\n }\n }\n\n return false; // No type keyword found.\n }\n\n // Keep in sync with CreateDefaultOptions above.\n [JsonSourceGenerationOptions(JsonSerializerDefaults.Web,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n NumberHandling = JsonNumberHandling.AllowReadingFromString)]\n \n // JSON-RPC\n [JsonSerializable(typeof(JsonRpcMessage))]\n [JsonSerializable(typeof(JsonRpcMessage[]))]\n [JsonSerializable(typeof(JsonRpcRequest))]\n [JsonSerializable(typeof(JsonRpcNotification))]\n [JsonSerializable(typeof(JsonRpcResponse))]\n [JsonSerializable(typeof(JsonRpcError))]\n\n // MCP Notification Params\n [JsonSerializable(typeof(CancelledNotificationParams))]\n [JsonSerializable(typeof(InitializedNotificationParams))]\n [JsonSerializable(typeof(LoggingMessageNotificationParams))]\n [JsonSerializable(typeof(ProgressNotificationParams))]\n [JsonSerializable(typeof(PromptListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceUpdatedNotificationParams))]\n [JsonSerializable(typeof(RootsListChangedNotificationParams))]\n [JsonSerializable(typeof(ToolListChangedNotificationParams))]\n\n // MCP Request Params / Results\n [JsonSerializable(typeof(CallToolRequestParams))]\n [JsonSerializable(typeof(CallToolResult))]\n [JsonSerializable(typeof(CompleteRequestParams))]\n [JsonSerializable(typeof(CompleteResult))]\n [JsonSerializable(typeof(CreateMessageRequestParams))]\n [JsonSerializable(typeof(CreateMessageResult))]\n [JsonSerializable(typeof(ElicitRequestParams))]\n [JsonSerializable(typeof(ElicitResult))]\n [JsonSerializable(typeof(EmptyResult))]\n [JsonSerializable(typeof(GetPromptRequestParams))]\n [JsonSerializable(typeof(GetPromptResult))]\n [JsonSerializable(typeof(InitializeRequestParams))]\n [JsonSerializable(typeof(InitializeResult))]\n [JsonSerializable(typeof(ListPromptsRequestParams))]\n [JsonSerializable(typeof(ListPromptsResult))]\n [JsonSerializable(typeof(ListResourcesRequestParams))]\n [JsonSerializable(typeof(ListResourcesResult))]\n [JsonSerializable(typeof(ListResourceTemplatesRequestParams))]\n [JsonSerializable(typeof(ListResourceTemplatesResult))]\n [JsonSerializable(typeof(ListRootsRequestParams))]\n [JsonSerializable(typeof(ListRootsResult))]\n [JsonSerializable(typeof(ListToolsRequestParams))]\n [JsonSerializable(typeof(ListToolsResult))]\n [JsonSerializable(typeof(PingResult))]\n [JsonSerializable(typeof(ReadResourceRequestParams))]\n [JsonSerializable(typeof(ReadResourceResult))]\n [JsonSerializable(typeof(SetLevelRequestParams))]\n [JsonSerializable(typeof(SubscribeRequestParams))]\n [JsonSerializable(typeof(UnsubscribeRequestParams))]\n\n // MCP Content\n [JsonSerializable(typeof(ContentBlock))]\n [JsonSerializable(typeof(TextContentBlock))]\n [JsonSerializable(typeof(ImageContentBlock))]\n [JsonSerializable(typeof(AudioContentBlock))]\n [JsonSerializable(typeof(EmbeddedResourceBlock))]\n [JsonSerializable(typeof(ResourceLinkBlock))]\n [JsonSerializable(typeof(PromptReference))]\n [JsonSerializable(typeof(ResourceTemplateReference))]\n [JsonSerializable(typeof(BlobResourceContents))]\n [JsonSerializable(typeof(TextResourceContents))]\n\n // Other MCP Types\n [JsonSerializable(typeof(IReadOnlyDictionary))]\n [JsonSerializable(typeof(ProgressToken))]\n\n [JsonSerializable(typeof(ProtectedResourceMetadata))]\n [JsonSerializable(typeof(AuthorizationServerMetadata))]\n [JsonSerializable(typeof(TokenContainer))]\n [JsonSerializable(typeof(DynamicClientRegistrationRequest))]\n [JsonSerializable(typeof(DynamicClientRegistrationResponse))]\n\n // Primitive types for use in consuming AIFunctions\n [JsonSerializable(typeof(string))]\n [JsonSerializable(typeof(byte))]\n [JsonSerializable(typeof(byte?))]\n [JsonSerializable(typeof(sbyte))]\n [JsonSerializable(typeof(sbyte?))]\n [JsonSerializable(typeof(ushort))]\n [JsonSerializable(typeof(ushort?))]\n [JsonSerializable(typeof(short))]\n [JsonSerializable(typeof(short?))]\n [JsonSerializable(typeof(uint))]\n [JsonSerializable(typeof(uint?))]\n [JsonSerializable(typeof(int))]\n [JsonSerializable(typeof(int?))]\n [JsonSerializable(typeof(ulong))]\n [JsonSerializable(typeof(ulong?))]\n [JsonSerializable(typeof(long))]\n [JsonSerializable(typeof(long?))]\n [JsonSerializable(typeof(nuint))]\n [JsonSerializable(typeof(nuint?))]\n [JsonSerializable(typeof(nint))]\n [JsonSerializable(typeof(nint?))]\n [JsonSerializable(typeof(bool))]\n [JsonSerializable(typeof(bool?))]\n [JsonSerializable(typeof(char))]\n [JsonSerializable(typeof(char?))]\n [JsonSerializable(typeof(float))]\n [JsonSerializable(typeof(float?))]\n [JsonSerializable(typeof(double))]\n [JsonSerializable(typeof(double?))]\n [JsonSerializable(typeof(decimal))]\n [JsonSerializable(typeof(decimal?))]\n [JsonSerializable(typeof(Guid))]\n [JsonSerializable(typeof(Guid?))]\n [JsonSerializable(typeof(Uri))]\n [JsonSerializable(typeof(Version))]\n [JsonSerializable(typeof(TimeSpan))]\n [JsonSerializable(typeof(TimeSpan?))]\n [JsonSerializable(typeof(DateTime))]\n [JsonSerializable(typeof(DateTime?))]\n [JsonSerializable(typeof(DateTimeOffset))]\n [JsonSerializable(typeof(DateTimeOffset?))]\n#if NET\n [JsonSerializable(typeof(DateOnly))]\n [JsonSerializable(typeof(DateOnly?))]\n [JsonSerializable(typeof(TimeOnly))]\n [JsonSerializable(typeof(TimeOnly?))]\n [JsonSerializable(typeof(Half))]\n [JsonSerializable(typeof(Half?))]\n [JsonSerializable(typeof(Int128))]\n [JsonSerializable(typeof(Int128?))]\n [JsonSerializable(typeof(UInt128))]\n [JsonSerializable(typeof(UInt128?))]\n#endif\n\n [ExcludeFromCodeCoverage]\n internal sealed partial class JsonContext : JsonSerializerContext;\n\n private static JsonElement ParseJsonElement(ReadOnlySpan utf8Json)\n {\n Utf8JsonReader reader = new(utf8Json);\n return JsonElement.ParseValue(ref reader);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Diagnostics.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\n\nnamespace ModelContextProtocol;\n\ninternal static class Diagnostics\n{\n internal static ActivitySource ActivitySource { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Meter Meter { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Histogram CreateDurationHistogram(string name, string description, bool longBuckets) =>\n Meter.CreateHistogram(name, \"s\", description\n#if NET9_0_OR_GREATER\n , advice: longBuckets ? LongSecondsBucketBoundaries : ShortSecondsBucketBoundaries\n#endif\n );\n\n#if NET9_0_OR_GREATER\n /// \n /// Follows boundaries from http.server.request.duration/http.client.request.duration\n /// \n private static InstrumentAdvice ShortSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n };\n\n /// \n /// Not based on a standard. Larger bucket sizes for longer lasting operations, e.g. HTTP connection duration.\n /// See https://github.com/open-telemetry/semantic-conventions/issues/336\n /// \n private static InstrumentAdvice LongSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300],\n };\n#endif\n\n internal static ActivityContext ExtractActivityContext(this DistributedContextPropagator propagator, JsonRpcMessage message)\n {\n propagator.ExtractTraceIdAndState(message, ExtractContext, out var traceparent, out var tracestate);\n ActivityContext.TryParse(traceparent, tracestate, true, out var activityContext);\n return activityContext;\n }\n\n private static void ExtractContext(object? message, string fieldName, out string? fieldValue, out IEnumerable? fieldValues)\n {\n fieldValues = null;\n fieldValue = null;\n\n JsonNode? meta = null;\n switch (message)\n {\n case JsonRpcRequest request:\n meta = request.Params?[\"_meta\"];\n break;\n\n case JsonRpcNotification notification:\n meta = notification.Params?[\"_meta\"];\n break;\n }\n\n if (meta?[fieldName] is JsonValue value && value.GetValueKind() == JsonValueKind.String)\n {\n fieldValue = value.GetValue();\n }\n }\n\n internal static void InjectActivityContext(this DistributedContextPropagator propagator, Activity? activity, JsonRpcMessage message)\n {\n // noop if activity is null\n propagator.Inject(activity, message, InjectContext);\n }\n\n private static void InjectContext(object? message, string key, string value)\n {\n JsonNode? parameters = null;\n switch (message)\n {\n case JsonRpcRequest request:\n parameters = request.Params;\n break;\n\n case JsonRpcNotification notification:\n parameters = notification.Params;\n break;\n }\n\n // Replace any params._meta with the current value\n if (parameters is JsonObject jsonObject)\n {\n if (jsonObject[\"_meta\"] is not JsonObject meta)\n {\n meta = new JsonObject();\n jsonObject[\"_meta\"] = meta;\n }\n meta[key] = value;\n }\n }\n\n internal static bool ShouldInstrumentMessage(JsonRpcMessage message) =>\n ActivitySource.HasListeners() &&\n message switch\n {\n JsonRpcRequest => true,\n JsonRpcNotification notification => notification.Method != NotificationMethods.LoggingMessageNotification,\n _ => false\n };\n\n internal static ActivityLink[] ActivityLinkFromCurrent() => Activity.Current is null ? [] : [new ActivityLink(Activity.Current.Context)];\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/Protocol/ProgressNotificationParams.cs", "using Microsoft.Extensions.Logging.Abstractions;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an out-of-band notification used to inform the receiver of a progress update for a long-running request.\n/// \n/// \n/// See the schema for more details.\n/// \n[JsonConverter(typeof(Converter))]\npublic sealed class ProgressNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the progress token which was given in the initial request, used to associate this notification with \n /// the corresponding request.\n /// \n /// \n /// \n /// This token acts as a correlation identifier that links progress updates to their corresponding request.\n /// \n /// \n /// When an endpoint initiates a request with a in its metadata, \n /// the receiver can send progress notifications using this same token. This allows both sides to \n /// correlate the notifications with the original request.\n /// \n /// \n public required ProgressToken ProgressToken { get; init; }\n\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// This should increase for each notification issued as part of the same request, even if the total is unknown.\n /// \n public required ProgressNotificationValue Progress { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressNotificationParams? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n ProgressToken? progressToken = null;\n float? progress = null;\n float? total = null;\n string? message = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType == JsonTokenType.PropertyName)\n {\n var propertyName = reader.GetString();\n reader.Read();\n switch (propertyName)\n {\n case \"progressToken\":\n progressToken = (ProgressToken)JsonSerializer.Deserialize(ref reader, options.GetTypeInfo(typeof(ProgressToken)))!;\n break;\n\n case \"progress\":\n progress = reader.GetSingle();\n break;\n\n case \"total\":\n total = reader.GetSingle();\n break;\n\n case \"message\":\n message = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n }\n }\n }\n\n if (progress is null)\n {\n throw new JsonException(\"Missing required property 'progress'.\");\n }\n\n if (progressToken is null)\n {\n throw new JsonException(\"Missing required property 'progressToken'.\");\n }\n\n return new ProgressNotificationParams\n {\n ProgressToken = progressToken.GetValueOrDefault(),\n Progress = new ProgressNotificationValue\n {\n Progress = progress.GetValueOrDefault(),\n Total = total,\n Message = message,\n },\n Meta = meta,\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressNotificationParams value, JsonSerializerOptions options)\n {\n writer.WriteStartObject();\n\n writer.WritePropertyName(\"progressToken\");\n JsonSerializer.Serialize(writer, value.ProgressToken, options.GetTypeInfo(typeof(ProgressToken)));\n\n writer.WriteNumber(\"progress\", value.Progress.Progress);\n\n if (value.Progress.Total is { } total)\n {\n writer.WriteNumber(\"total\", total);\n }\n\n if (value.Progress.Message is { } message)\n {\n writer.WriteString(\"message\", message);\n }\n\n if (value.Meta is { } meta)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed partial class AIFunctionMcpServerTool : McpServerTool\n{\n private readonly ILogger _logger;\n private readonly bool _structuredOutputRequiresWrapping;\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n \n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n object? target,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerToolCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options)\n {\n Throw.IfNull(function);\n\n Tool tool = new()\n {\n Name = options?.Name ?? function.Name,\n Description = options?.Description ?? function.Description,\n InputSchema = function.JsonSchema,\n OutputSchema = CreateOutputSchema(function, options, out bool structuredOutputRequiresWrapping),\n };\n\n if (options is not null)\n {\n if (options.Title is not null ||\n options.Idempotent is not null ||\n options.Destructive is not null ||\n options.OpenWorld is not null ||\n options.ReadOnly is not null)\n {\n tool.Title = options.Title;\n\n tool.Annotations = new()\n {\n Title = options.Title,\n IdempotentHint = options.Idempotent,\n DestructiveHint = options.Destructive,\n OpenWorldHint = options.OpenWorld,\n ReadOnlyHint = options.ReadOnly,\n };\n }\n }\n\n return new AIFunctionMcpServerTool(function, tool, options?.Services, structuredOutputRequiresWrapping);\n }\n\n private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpServerToolCreateOptions? options)\n {\n McpServerToolCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } toolAttr)\n {\n newOptions.Name ??= toolAttr.Name;\n newOptions.Title ??= toolAttr.Title;\n\n if (toolAttr._destructive is bool destructive)\n {\n newOptions.Destructive ??= destructive;\n }\n\n if (toolAttr._idempotent is bool idempotent)\n {\n newOptions.Idempotent ??= idempotent;\n }\n\n if (toolAttr._openWorld is bool openWorld)\n {\n newOptions.OpenWorld ??= openWorld;\n }\n\n if (toolAttr._readOnly is bool readOnly)\n {\n newOptions.ReadOnly ??= readOnly;\n }\n\n newOptions.UseStructuredContent = toolAttr.UseStructuredContent;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this tool.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerTool(AIFunction function, Tool tool, IServiceProvider? serviceProvider, bool structuredOutputRequiresWrapping)\n {\n AIFunction = function;\n ProtocolTool = tool;\n _logger = serviceProvider?.GetService()?.CreateLogger() ?? (ILogger)NullLogger.Instance;\n _structuredOutputRequiresWrapping = structuredOutputRequiresWrapping;\n }\n\n /// \n public override Tool ProtocolTool { get; }\n\n /// \n public override async ValueTask InvokeAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result;\n try\n {\n result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e) when (e is not OperationCanceledException)\n {\n ToolCallError(request.Params?.Name ?? string.Empty, e);\n\n string errorMessage = e is McpException ?\n $\"An error occurred invoking '{request.Params?.Name}': {e.Message}\" :\n $\"An error occurred invoking '{request.Params?.Name}'.\";\n\n return new()\n {\n IsError = true,\n Content = [new TextContentBlock { Text = errorMessage }],\n };\n }\n\n JsonNode? structuredContent = CreateStructuredResponse(result);\n return result switch\n {\n AIContent aiContent => new()\n {\n Content = [aiContent.ToContent()],\n StructuredContent = structuredContent,\n IsError = aiContent is ErrorContent\n },\n\n null => new()\n {\n Content = [],\n StructuredContent = structuredContent,\n },\n \n string text => new()\n {\n Content = [new TextContentBlock { Text = text }],\n StructuredContent = structuredContent,\n },\n \n ContentBlock content => new()\n {\n Content = [content],\n StructuredContent = structuredContent,\n },\n \n IEnumerable texts => new()\n {\n Content = [.. texts.Select(x => new TextContentBlock { Text = x ?? string.Empty })],\n StructuredContent = structuredContent,\n },\n \n IEnumerable contentItems => ConvertAIContentEnumerableToCallToolResult(contentItems, structuredContent),\n \n IEnumerable contents => new()\n {\n Content = [.. contents],\n StructuredContent = structuredContent,\n },\n \n CallToolResult callToolResponse => callToolResponse,\n\n _ => new()\n {\n Content = [new TextContentBlock { Text = JsonSerializer.Serialize(result, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))) }],\n StructuredContent = structuredContent,\n },\n };\n }\n\n /// Creates a name to use based on the supplied method and naming policy.\n internal static string DeriveName(MethodInfo method, JsonNamingPolicy? policy = null)\n {\n string name = method.Name;\n\n // Remove any \"Async\" suffix if the method is an async method and if the method name isn't just \"Async\".\n const string AsyncSuffix = \"Async\";\n if (IsAsyncMethod(method) &&\n name.EndsWith(AsyncSuffix, StringComparison.Ordinal) &&\n name.Length > AsyncSuffix.Length)\n {\n name = name.Substring(0, name.Length - AsyncSuffix.Length);\n }\n\n // Replace anything other than ASCII letters or digits with underscores, trim off any leading or trailing underscores.\n name = NonAsciiLetterDigitsRegex().Replace(name, \"_\").Trim('_');\n\n // If after all our transformations the name is empty, just use the original method name.\n if (name.Length == 0)\n {\n name = method.Name;\n }\n\n // Case the name based on the provided naming policy.\n return (policy ?? JsonNamingPolicy.SnakeCaseLower).ConvertName(name) ?? name;\n\n static bool IsAsyncMethod(MethodInfo method)\n {\n Type t = method.ReturnType;\n\n if (t == typeof(Task) || t == typeof(ValueTask))\n {\n return true;\n }\n\n if (t.IsGenericType)\n {\n t = t.GetGenericTypeDefinition();\n if (t == typeof(Task<>) || t == typeof(ValueTask<>) || t == typeof(IAsyncEnumerable<>))\n {\n return true;\n }\n }\n\n return false;\n }\n }\n\n /// Regex that flags runs of characters other than ASCII digits or letters.\n#if NET\n [GeneratedRegex(\"[^0-9A-Za-z]+\")]\n private static partial Regex NonAsciiLetterDigitsRegex();\n#else\n private static Regex NonAsciiLetterDigitsRegex() => _nonAsciiLetterDigits;\n private static readonly Regex _nonAsciiLetterDigits = new(\"[^0-9A-Za-z]+\", RegexOptions.Compiled);\n#endif\n\n private static JsonElement? CreateOutputSchema(AIFunction function, McpServerToolCreateOptions? toolCreateOptions, out bool structuredOutputRequiresWrapping)\n {\n structuredOutputRequiresWrapping = false;\n\n if (toolCreateOptions?.UseStructuredContent is not true)\n {\n return null;\n }\n\n if (function.ReturnJsonSchema is not JsonElement outputSchema)\n {\n return null;\n }\n\n if (outputSchema.ValueKind is not JsonValueKind.Object ||\n !outputSchema.TryGetProperty(\"type\", out JsonElement typeProperty) ||\n typeProperty.ValueKind is not JsonValueKind.String ||\n typeProperty.GetString() is not \"object\")\n {\n // If the output schema is not an object, need to modify to be a valid MCP output schema.\n JsonNode? schemaNode = JsonSerializer.SerializeToNode(outputSchema, McpJsonUtilities.JsonContext.Default.JsonElement);\n\n if (schemaNode is JsonObject objSchema &&\n objSchema.TryGetPropertyValue(\"type\", out JsonNode? typeNode) &&\n typeNode is JsonArray { Count: 2 } typeArray && typeArray.Any(type => (string?)type is \"object\") && typeArray.Any(type => (string?)type is \"null\"))\n {\n // For schemas that are of type [\"object\", \"null\"], replace with just \"object\" to be conformant.\n objSchema[\"type\"] = \"object\";\n }\n else\n {\n // For anything else, wrap the schema in an envelope with a \"result\" property.\n schemaNode = new JsonObject\n {\n [\"type\"] = \"object\",\n [\"properties\"] = new JsonObject\n {\n [\"result\"] = schemaNode\n },\n [\"required\"] = new JsonArray { (JsonNode)\"result\" }\n };\n\n structuredOutputRequiresWrapping = true;\n }\n\n outputSchema = JsonSerializer.Deserialize(schemaNode, McpJsonUtilities.JsonContext.Default.JsonElement);\n }\n\n return outputSchema;\n }\n\n private JsonNode? CreateStructuredResponse(object? aiFunctionResult)\n {\n if (ProtocolTool.OutputSchema is null)\n {\n // Only provide structured responses if the tool has an output schema defined.\n return null;\n }\n\n JsonNode? nodeResult = aiFunctionResult switch\n {\n JsonNode node => node,\n JsonElement jsonElement => JsonSerializer.SerializeToNode(jsonElement, McpJsonUtilities.JsonContext.Default.JsonElement),\n _ => JsonSerializer.SerializeToNode(aiFunctionResult, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))),\n };\n\n if (_structuredOutputRequiresWrapping)\n {\n return new JsonObject\n {\n [\"result\"] = nodeResult\n };\n }\n\n return nodeResult;\n }\n\n private static CallToolResult ConvertAIContentEnumerableToCallToolResult(IEnumerable contentItems, JsonNode? structuredContent)\n {\n List contentList = [];\n bool allErrorContent = true;\n bool hasAny = false;\n\n foreach (var item in contentItems)\n {\n contentList.Add(item.ToContent());\n hasAny = true;\n\n if (allErrorContent && item is not ErrorContent)\n {\n allErrorContent = false;\n }\n }\n\n return new()\n {\n Content = contentList,\n StructuredContent = structuredContent,\n IsError = allErrorContent && hasAny\n };\n }\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"\\\"{ToolName}\\\" threw an unhandled exception.\")]\n private partial void ToolCallError(string toolName, Exception exception);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContentBlock.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents content within the Model Context Protocol (MCP).\n/// \n/// \n/// \n/// The class is a fundamental type in the MCP that can represent different forms of content\n/// based on the property. Derived types like , ,\n/// and provide the type-specific content.\n/// \n/// \n/// This class is used throughout the MCP for representing content in messages, tool responses,\n/// and other communication between clients and servers.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\npublic abstract class ContentBlock\n{\n /// Prevent external derivations.\n private protected ContentBlock()\n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This determines the structure of the content object. Valid values include \"image\", \"audio\", \"text\", \"resource\", and \"resource_link\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Gets or sets optional annotations for the content.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the content. Clients can use this information to filter or prioritize content for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ContentBlock? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? text = null;\n string? name = null;\n string? data = null;\n string? mimeType = null;\n string? uri = null;\n string? description = null;\n long? size = null;\n ResourceContents? resource = null;\n Annotations? annotations = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"data\":\n data = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"size\":\n size = reader.GetInt64();\n break;\n\n case \"resource\":\n resource = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.ResourceContents);\n break;\n\n case \"annotations\":\n annotations = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.Annotations);\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n return type switch\n {\n \"text\" => new TextContentBlock\n {\n Text = text ?? throw new JsonException(\"Text contents must be provided for 'text' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"image\" => new ImageContentBlock\n {\n Data = data ?? throw new JsonException(\"Image data must be provided for 'image' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'image' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"audio\" => new AudioContentBlock\n {\n Data = data ?? throw new JsonException(\"Audio data must be provided for 'audio' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'audio' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource\" => new EmbeddedResourceBlock\n {\n Resource = resource ?? throw new JsonException(\"Resource contents must be provided for 'resource' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource_link\" => new ResourceLinkBlock\n {\n Uri = uri ?? throw new JsonException(\"URI must be provided for 'resource_link' type.\"),\n Name = name ?? throw new JsonException(\"Name must be provided for 'resource_link' type.\"),\n Description = description,\n MimeType = mimeType,\n Size = size,\n Annotations = annotations,\n },\n\n _ => throw new JsonException($\"Unknown content type: '{type}'\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case TextContentBlock textContent:\n writer.WriteString(\"text\", textContent.Text);\n if (textContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, textContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ImageContentBlock imageContent:\n writer.WriteString(\"data\", imageContent.Data);\n writer.WriteString(\"mimeType\", imageContent.MimeType);\n if (imageContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, imageContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case AudioContentBlock audioContent:\n writer.WriteString(\"data\", audioContent.Data);\n writer.WriteString(\"mimeType\", audioContent.MimeType);\n if (audioContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, audioContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case EmbeddedResourceBlock embeddedResource:\n writer.WritePropertyName(\"resource\");\n JsonSerializer.Serialize(writer, embeddedResource.Resource, McpJsonUtilities.JsonContext.Default.ResourceContents);\n if (embeddedResource.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, embeddedResource.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ResourceLinkBlock resourceLink:\n writer.WriteString(\"uri\", resourceLink.Uri);\n writer.WriteString(\"name\", resourceLink.Name);\n if (resourceLink.Description is not null)\n {\n writer.WriteString(\"description\", resourceLink.Description);\n }\n if (resourceLink.MimeType is not null)\n {\n writer.WriteString(\"mimeType\", resourceLink.MimeType);\n }\n if (resourceLink.Size.HasValue)\n {\n writer.WriteNumber(\"size\", resourceLink.Size.Value);\n }\n break;\n }\n\n if (value.Annotations is { } annotations)\n {\n writer.WritePropertyName(\"annotations\");\n JsonSerializer.Serialize(writer, annotations, McpJsonUtilities.JsonContext.Default.Annotations);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// Represents text provided to or from an LLM.\npublic sealed class TextContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public TextContentBlock() => Type = \"text\";\n\n /// \n /// Gets or sets the text content of the message.\n /// \n [JsonPropertyName(\"text\")]\n public required string Text { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents an image provided to or from an LLM.\npublic sealed class ImageContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ImageContentBlock() => Type = \"image\";\n\n /// \n /// Gets or sets the base64-encoded image data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"image/png\" and \"image/jpeg\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents audio provided to or from an LLM.\npublic sealed class AudioContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public AudioContentBlock() => Type = \"audio\";\n\n /// \n /// Gets or sets the base64-encoded audio data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"audio/wav\" and \"audio/mp3\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents the contents of a resource, embedded into a prompt or tool call result.\n/// \n/// It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user.\n/// \npublic sealed class EmbeddedResourceBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public EmbeddedResourceBlock() => Type = \"resource\";\n\n /// \n /// Gets or sets the resource content of the message when is \"resource\".\n /// \n /// \n /// \n /// Resources can be either text-based () or \n /// binary (), allowing for flexible data representation.\n /// Each resource has a URI that can be used for identification and retrieval.\n /// \n /// \n [JsonPropertyName(\"resource\")]\n public required ResourceContents Resource { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents a resource that the server is capable of reading, included in a prompt or tool call result.\n/// \n/// Resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n/// \npublic sealed class ResourceLinkBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ResourceLinkBlock() => Type = \"resource_link\";\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for this resource.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthenticatingMcpHttpClient.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Net.Http.Headers;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// A delegating handler that adds authentication tokens to requests and handles 401 responses.\n/// \ninternal sealed class AuthenticatingMcpHttpClient(HttpClient httpClient, ClientOAuthProvider credentialProvider) : McpHttpClient(httpClient)\n{\n // Select first supported scheme as the default\n private string _currentScheme = credentialProvider.SupportedSchemes.FirstOrDefault() ??\n throw new ArgumentException(\"Authorization provider must support at least one authentication scheme.\", nameof(credentialProvider));\n\n /// \n /// Sends an HTTP request with authentication handling.\n /// \n internal override async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (request.Headers.Authorization == null)\n {\n await AddAuthorizationHeaderAsync(request, _currentScheme, cancellationToken).ConfigureAwait(false);\n }\n\n var response = await base.SendAsync(request, message, cancellationToken).ConfigureAwait(false);\n\n if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)\n {\n return await HandleUnauthorizedResponseAsync(request, message, response, cancellationToken).ConfigureAwait(false);\n }\n\n return response;\n }\n\n /// \n /// Handles a 401 Unauthorized response by attempting to authenticate and retry the request.\n /// \n private async Task HandleUnauthorizedResponseAsync(\n HttpRequestMessage originalRequest,\n JsonRpcMessage? originalJsonRpcMessage,\n HttpResponseMessage response,\n CancellationToken cancellationToken)\n {\n // Gather the schemes the server wants us to use from WWW-Authenticate headers\n var serverSchemes = ExtractServerSupportedSchemes(response);\n\n if (!serverSchemes.Contains(_currentScheme))\n {\n // Find the first server scheme that's in our supported set\n var bestSchemeMatch = serverSchemes.Intersect(credentialProvider.SupportedSchemes, StringComparer.OrdinalIgnoreCase).FirstOrDefault();\n\n if (bestSchemeMatch is not null)\n {\n _currentScheme = bestSchemeMatch;\n }\n else if (serverSchemes.Count > 0)\n {\n // If no match was found, either throw an exception or use default\n throw new McpException(\n $\"The server does not support any of the provided authentication schemes.\" +\n $\"Server supports: [{string.Join(\", \", serverSchemes)}], \" +\n $\"Provider supports: [{string.Join(\", \", credentialProvider.SupportedSchemes)}].\");\n }\n }\n\n // Try to handle the 401 response with the selected scheme\n await credentialProvider.HandleUnauthorizedResponseAsync(_currentScheme, response, cancellationToken).ConfigureAwait(false);\n\n using var retryRequest = new HttpRequestMessage(originalRequest.Method, originalRequest.RequestUri);\n\n // Copy headers except Authorization which we'll set separately\n foreach (var header in originalRequest.Headers)\n {\n if (!header.Key.Equals(\"Authorization\", StringComparison.OrdinalIgnoreCase))\n {\n retryRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);\n }\n }\n\n await AddAuthorizationHeaderAsync(retryRequest, _currentScheme, cancellationToken).ConfigureAwait(false);\n return await base.SendAsync(retryRequest, originalJsonRpcMessage, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Extracts the authentication schemes that the server supports from the WWW-Authenticate headers.\n /// \n private static HashSet ExtractServerSupportedSchemes(HttpResponseMessage response)\n {\n var serverSchemes = new HashSet(StringComparer.OrdinalIgnoreCase);\n\n foreach (var header in response.Headers.WwwAuthenticate)\n {\n serverSchemes.Add(header.Scheme);\n }\n\n return serverSchemes;\n }\n\n /// \n /// Adds an authorization header to the request.\n /// \n private async Task AddAuthorizationHeaderAsync(HttpRequestMessage request, string scheme, CancellationToken cancellationToken)\n {\n if (request.RequestUri is null)\n {\n return;\n }\n\n var token = await credentialProvider.GetCredentialAsync(scheme, request.RequestUri, cancellationToken).ConfigureAwait(false);\n if (string.IsNullOrEmpty(token))\n {\n return;\n }\n\n request.Headers.Authorization = new AuthenticationHeaderValue(scheme, token);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestId.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC request identifier, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct RequestId : IEquatable\n{\n /// The id, either a string or a boxed long or null.\n private readonly object? _id;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(string value)\n {\n Throw.IfNull(value);\n _id = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(long value)\n {\n // Box the long. Request IDs are almost always strings in practice, so this should be rare.\n _id = value;\n }\n\n /// Gets the underlying object for this id.\n /// This will either be a , a boxed , or .\n public object? Id => _id;\n\n /// \n public override string ToString() =>\n _id is string stringValue ? stringValue :\n _id is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n string.Empty;\n\n /// \n public bool Equals(RequestId other) => Equals(_id, other._id);\n\n /// \n public override bool Equals(object? obj) => obj is RequestId other && Equals(other);\n\n /// \n public override int GetHashCode() => _id?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(RequestId left, RequestId right) => left.Equals(right);\n\n /// \n public static bool operator !=(RequestId left, RequestId right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override RequestId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"requestId must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, RequestId value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._id)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\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/Protocol/Tool.cs", "using System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a tool that the server is capable of calling.\n/// \npublic sealed class Tool : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the tool.\n /// \n /// \n /// \n /// This description helps the AI model understand what the tool does and when to use it.\n /// It should be clear, concise, and accurately describe the tool's purpose and functionality.\n /// \n /// \n /// The description is typically presented to AI models to help them determine when\n /// and how to use the tool based on user requests.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a JSON Schema object defining the expected parameters for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema typically defines the properties (parameters) that the tool accepts, \n /// their types, and which ones are required. This helps AI models understand\n /// how to structure their calls to the tool.\n /// \n /// \n /// If not explicitly set, a default minimal schema of {\"type\":\"object\"} is used.\n /// \n /// \n [JsonPropertyName(\"inputSchema\")]\n public JsonElement InputSchema \n { \n get => field; \n set\n {\n if (!McpJsonUtilities.IsValidMcpToolSchema(value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool input JSON schema.\", nameof(InputSchema));\n }\n\n field = value;\n }\n\n } = McpJsonUtilities.DefaultMcpToolSchema;\n\n /// \n /// Gets or sets a JSON Schema object defining the expected structured outputs for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema should describe the shape of the data as returned in .\n /// \n /// \n [JsonPropertyName(\"outputSchema\")]\n public JsonElement? OutputSchema\n {\n get => field;\n set\n {\n if (value is not null && !McpJsonUtilities.IsValidMcpToolSchema(value.Value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool output JSON schema.\", nameof(OutputSchema));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets optional additional tool information and behavior hints.\n /// \n /// \n /// These annotations provide metadata about the tool's behavior, such as whether it's read-only,\n /// destructive, idempotent, or operates in an open world. They also can include a human-readable title.\n /// Note that these are hints and should not be relied upon for security decisions.\n /// \n [JsonPropertyName(\"annotations\")]\n public ToolAnnotations? Annotations { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides extension methods for interacting with an instance.\n/// \npublic static class McpServerExtensions\n{\n /// \n /// Requests to sample an LLM via the client using the specified request parameters.\n /// \n /// The server instance initiating the request.\n /// The parameters for the sampling request.\n /// The to monitor for cancellation requests.\n /// A task containing the sampling result from the client.\n /// is .\n /// The client does not support sampling.\n /// \n /// This method requires the client to support sampling capabilities.\n /// It allows detailed control over sampling parameters including messages, system prompt, temperature, \n /// and token limits.\n /// \n public static ValueTask SampleAsync(\n this IMcpServer server, CreateMessageRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.SamplingCreateMessage,\n request,\n McpJsonUtilities.JsonContext.Default.CreateMessageRequestParams,\n McpJsonUtilities.JsonContext.Default.CreateMessageResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests to sample an LLM via the client using the provided chat messages and options.\n /// \n /// The server initiating the request.\n /// The messages to send as part of the request.\n /// The options to use for the request, including model parameters and constraints.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the chat response from the model.\n /// is .\n /// is .\n /// The client does not support sampling.\n /// \n /// This method converts the provided chat messages into a format suitable for the sampling API,\n /// handling different content types such as text, images, and audio.\n /// \n public static async Task SampleAsync(\n this IMcpServer server,\n IEnumerable messages, ChatOptions? options = default, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n Throw.IfNull(messages);\n\n StringBuilder? systemPrompt = null;\n\n if (options?.Instructions is { } instructions)\n {\n (systemPrompt ??= new()).Append(instructions);\n }\n\n List samplingMessages = [];\n foreach (var message in messages)\n {\n if (message.Role == ChatRole.System)\n {\n if (systemPrompt is null)\n {\n systemPrompt = new();\n }\n else\n {\n systemPrompt.AppendLine();\n }\n\n systemPrompt.Append(message.Text);\n continue;\n }\n\n if (message.Role == ChatRole.User || message.Role == ChatRole.Assistant)\n {\n Role role = message.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n foreach (var content in message.Contents)\n {\n switch (content)\n {\n case TextContent textContent:\n samplingMessages.Add(new()\n {\n Role = role,\n Content = new TextContentBlock { Text = textContent.Text },\n });\n break;\n\n case DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") || dataContent.HasTopLevelMediaType(\"audio\"):\n samplingMessages.Add(new()\n {\n Role = role,\n Content = dataContent.HasTopLevelMediaType(\"image\") ?\n new ImageContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n } :\n new AudioContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n },\n });\n break;\n }\n }\n }\n }\n\n ModelPreferences? modelPreferences = null;\n if (options?.ModelId is { } modelId)\n {\n modelPreferences = new() { Hints = [new() { Name = modelId }] };\n }\n\n var result = await server.SampleAsync(new()\n {\n Messages = samplingMessages,\n MaxTokens = options?.MaxOutputTokens,\n StopSequences = options?.StopSequences?.ToArray(),\n SystemPrompt = systemPrompt?.ToString(),\n Temperature = options?.Temperature,\n ModelPreferences = modelPreferences,\n }, cancellationToken).ConfigureAwait(false);\n\n AIContent? responseContent = result.Content.ToAIContent();\n\n return new(new ChatMessage(result.Role is Role.User ? ChatRole.User : ChatRole.Assistant, responseContent is not null ? [responseContent] : []))\n {\n ModelId = result.Model,\n FinishReason = result.StopReason switch\n {\n \"maxTokens\" => ChatFinishReason.Length,\n \"endTurn\" or \"stopSequence\" or _ => ChatFinishReason.Stop,\n }\n };\n }\n\n /// \n /// Creates an wrapper that can be used to send sampling requests to the client.\n /// \n /// The server to be wrapped as an .\n /// The that can be used to issue sampling requests to the client.\n /// is .\n /// The client does not support sampling.\n public static IChatClient AsSamplingChatClient(this IMcpServer server)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return new SamplingChatClient(server);\n }\n\n /// Gets an on which logged messages will be sent as notifications to the client.\n /// The server to wrap as an .\n /// An that can be used to log to the client..\n public static ILoggerProvider AsClientLoggerProvider(this IMcpServer server)\n {\n Throw.IfNull(server);\n\n return new ClientLoggerProvider(server);\n }\n\n /// \n /// Requests the client to list the roots it exposes.\n /// \n /// The server initiating the request.\n /// The parameters for the list roots request.\n /// The to monitor for cancellation requests.\n /// A task containing the list of roots exposed by the client.\n /// is .\n /// The client does not support roots.\n /// \n /// This method requires the client to support the roots capability.\n /// Root resources allow clients to expose a hierarchical structure of resources that can be\n /// navigated and accessed by the server. These resources might include file systems, databases,\n /// or other structured data sources that the client makes available through the protocol.\n /// \n public static ValueTask RequestRootsAsync(\n this IMcpServer server, ListRootsRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfRootsUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.RootsList,\n request,\n McpJsonUtilities.JsonContext.Default.ListRootsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListRootsResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests additional information from the user via the client, allowing the server to elicit structured data.\n /// \n /// The server initiating the request.\n /// The parameters for the elicitation request.\n /// The to monitor for cancellation requests.\n /// A task containing the elicitation result.\n /// is .\n /// The client does not support elicitation.\n /// \n /// This method requires the client to support the elicitation capability.\n /// \n public static ValueTask ElicitAsync(\n this IMcpServer server, ElicitRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfElicitationUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.ElicitationCreate,\n request,\n McpJsonUtilities.JsonContext.Default.ElicitRequestParams,\n McpJsonUtilities.JsonContext.Default.ElicitResult,\n cancellationToken: cancellationToken);\n }\n\n private static void ThrowIfSamplingUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Sampling is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Sampling is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support sampling.\");\n }\n }\n\n private static void ThrowIfRootsUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Roots is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Roots are not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support roots.\");\n }\n }\n\n private static void ThrowIfElicitationUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Elicitation is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Elicitation is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support elicitation requests.\");\n }\n }\n\n /// Provides an implementation that's implemented via client sampling.\n private sealed class SamplingChatClient(IMcpServer server) : IChatClient\n {\n /// \n public Task GetResponseAsync(IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) =>\n server.SampleAsync(messages, options, cancellationToken);\n\n /// \n async IAsyncEnumerable IChatClient.GetStreamingResponseAsync(\n IEnumerable messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n var response = await GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);\n foreach (var update in response.ToChatResponseUpdates())\n {\n yield return update;\n }\n }\n\n /// \n object? IChatClient.GetService(Type serviceType, object? serviceKey)\n {\n Throw.IfNull(serviceType);\n\n return\n serviceKey is not null ? null :\n serviceType.IsInstanceOfType(this) ? this :\n serviceType.IsInstanceOfType(server) ? server :\n null;\n }\n\n /// \n void IDisposable.Dispose() { } // nop\n }\n\n /// \n /// Provides an implementation for creating loggers\n /// that send logging message notifications to the client for logged messages.\n /// \n private sealed class ClientLoggerProvider(IMcpServer server) : ILoggerProvider\n {\n /// \n public ILogger CreateLogger(string categoryName)\n {\n Throw.IfNull(categoryName);\n\n return new ClientLogger(server, categoryName);\n }\n\n /// \n void IDisposable.Dispose() { }\n\n private sealed class ClientLogger(IMcpServer server, string categoryName) : ILogger\n {\n /// \n public IDisposable? BeginScope(TState state) where TState : notnull =>\n null;\n\n /// \n public bool IsEnabled(LogLevel logLevel) =>\n server?.LoggingLevel is { } loggingLevel &&\n McpServer.ToLoggingLevel(logLevel) >= loggingLevel;\n\n /// \n public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)\n {\n if (!IsEnabled(logLevel))\n {\n return;\n }\n\n Throw.IfNull(formatter);\n\n Log(logLevel, formatter(state, exception));\n\n void Log(LogLevel logLevel, string message)\n {\n _ = server.SendNotificationAsync(NotificationMethods.LoggingMessageNotification, new LoggingMessageNotificationParams\n {\n Level = McpServer.ToLoggingLevel(logLevel),\n Data = JsonSerializer.SerializeToElement(message, McpJsonUtilities.JsonContext.Default.String),\n Logger = categoryName,\n });\n }\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceContents.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class representing contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// serves as the base class for different types of resources that can be \n/// exchanged through the Model Context Protocol. Resources are identified by URIs and can contain\n/// different types of data.\n/// \n/// \n/// This class is abstract and has two concrete implementations:\n/// \n/// - For text-based resources\n/// - For binary data resources\n/// \n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class ResourceContents\n{\n /// Prevent external derivations.\n private protected ResourceContents()\n {\n }\n\n /// \n /// Gets or sets the URI of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n public string Uri { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the MIME type of the resource content.\n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ResourceContents? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? uri = null;\n string? mimeType = null;\n string? blob = null;\n string? text = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"blob\":\n blob = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n if (blob is not null)\n {\n return new BlobResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Blob = blob,\n Meta = meta,\n };\n }\n\n if (text is not null)\n {\n return new TextResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Text = text,\n Meta = meta,\n };\n }\n\n return null;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ResourceContents value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n writer.WriteString(\"uri\", value.Uri);\n writer.WriteString(\"mimeType\", value.MimeType);\n \n Debug.Assert(value is BlobResourceContents or TextResourceContents);\n if (value is BlobResourceContents blobResource)\n {\n writer.WriteString(\"blob\", blobResource.Blob);\n }\n else if (value is TextResourceContents textResource)\n {\n writer.WriteString(\"text\", textResource.Text);\n }\n\n if (value.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, value.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerPrompt : McpServerPrompt\n{\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n object? target,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerPromptCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(function);\n\n List args = [];\n HashSet? requiredProps = function.JsonSchema.TryGetProperty(\"required\", out JsonElement required)\n ? new(required.EnumerateArray().Select(p => p.GetString()!), StringComparer.Ordinal)\n : null;\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n foreach (var param in properties.EnumerateObject())\n {\n args.Add(new()\n {\n Name = param.Name,\n Description = param.Value.TryGetProperty(\"description\", out JsonElement description) ? description.GetString() : null,\n Required = requiredProps?.Contains(param.Name) ?? false,\n });\n }\n }\n\n Prompt prompt = new()\n {\n Name = options?.Name ?? function.Name,\n Title = options?.Title,\n Description = options?.Description ?? function.Description,\n Arguments = args,\n };\n\n return new AIFunctionMcpServerPrompt(function, prompt);\n }\n\n private static McpServerPromptCreateOptions DeriveOptions(MethodInfo method, McpServerPromptCreateOptions? options)\n {\n McpServerPromptCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } promptAttr)\n {\n newOptions.Name ??= promptAttr.Name;\n newOptions.Title ??= promptAttr.Title;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this prompt.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerPrompt(AIFunction function, Prompt prompt)\n {\n AIFunction = function;\n ProtocolPrompt = prompt;\n }\n\n /// \n public override Prompt ProtocolPrompt { get; }\n\n /// \n public override async ValueTask GetAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n return result switch\n {\n GetPromptResult getPromptResult => getPromptResult,\n\n string text => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [new() { Role = Role.User, Content = new TextContentBlock { Text = text } }],\n },\n\n PromptMessage promptMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [promptMessage],\n },\n\n IEnumerable promptMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. promptMessages],\n },\n\n ChatMessage chatMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessage.ToPromptMessages()],\n },\n\n IEnumerable chatMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessages.SelectMany(chatMessage => chatMessage.ToPromptMessages())],\n },\n\n null => throw new InvalidOperationException(\"Null result returned from prompt function.\"),\n\n _ => throw new InvalidOperationException($\"Unknown result type '{result.GetType()}' returned from prompt function.\"),\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/Client/McpClientExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class contains extension methods that simplify common operations with an MCP client,\n/// such as pinging a server, listing and working with tools, prompts, and resources, and\n/// managing subscriptions to resources.\n/// \n/// \npublic static class McpClientExtensions\n{\n /// \n /// Sends a ping request to verify server connectivity.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A task that completes when the ping is successful.\n /// \n /// \n /// This method is used to check if the MCP server is online and responding to requests.\n /// It can be useful for health checking, ensuring the connection is established, or verifying \n /// that the client has proper authorization to communicate with the server.\n /// \n /// \n /// The ping operation is lightweight and does not require any parameters. A successful completion\n /// of the task indicates that the server is operational and accessible.\n /// \n /// \n /// is .\n /// Thrown when the server cannot be reached or returns an error response.\n public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.Ping,\n parameters: null,\n McpJsonUtilities.JsonContext.Default.Object!,\n McpJsonUtilities.JsonContext.Default.Object,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Retrieves a list of available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available tools as instances.\n /// \n /// \n /// This method fetches all available tools from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of tools and that responds with paginated responses, consider using \n /// instead, as it streams tools as they arrive rather than loading them all at once.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// \n /// \n /// // Get all tools available on the server\n /// var tools = await mcpClient.ListToolsAsync();\n /// \n /// // Use tools with an AI client\n /// ChatOptions chatOptions = new()\n /// {\n /// Tools = [.. tools]\n /// };\n /// \n /// await foreach (var update in chatClient.GetStreamingResponseAsync(userMessage, chatOptions))\n /// {\n /// Console.Write(update);\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n List? tools = null;\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n tools ??= new List(toolResults.Tools.Count);\n foreach (var tool in toolResults.Tools)\n {\n tools.Add(new McpClientTool(client, tool, serializerOptions));\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n\n return tools;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available tools as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve tools from the server, which allows processing tools\n /// as they arrive rather than waiting for all tools to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with tools split across multiple responses.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available tools.\n /// \n /// \n /// \n /// \n /// // Enumerate all tools available on the server\n /// await foreach (var tool in client.EnumerateToolsAsync())\n /// {\n /// Console.WriteLine($\"Tool: {tool.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var tool in toolResults.Tools)\n {\n yield return new McpClientTool(client, tool, serializerOptions);\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available prompts as instances.\n /// \n /// \n /// This method fetches all available prompts from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of prompts and that responds with paginated responses, consider using \n /// instead, as it streams prompts as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListPromptsAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? prompts = null;\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n prompts ??= new List(promptResults.Prompts.Count);\n foreach (var prompt in promptResults.Prompts)\n {\n prompts.Add(new McpClientPrompt(client, prompt));\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n\n return prompts;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available prompts as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve prompts from the server, which allows processing prompts\n /// as they arrive rather than waiting for all prompts to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with prompts split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available prompts.\n /// \n /// \n /// \n /// \n /// // Enumerate all prompts available on the server\n /// await foreach (var prompt in client.EnumeratePromptsAsync())\n /// {\n /// Console.WriteLine($\"Prompt: {prompt.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumeratePromptsAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var prompt in promptResults.Prompts)\n {\n yield return new(client, prompt);\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a specific prompt from the MCP server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the prompt to retrieve.\n /// Optional arguments for the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to create the specified prompt with the provided arguments.\n /// The server will process the arguments and return a prompt containing messages or other content.\n /// \n /// \n /// Arguments are serialized into JSON and passed to the server, where they may be used to customize the \n /// prompt's behavior or content. Each prompt may have different argument requirements.\n /// \n /// \n /// The returned contains a collection of objects,\n /// which can be converted to objects using the method.\n /// \n /// \n /// Thrown when the prompt does not exist, when required arguments are missing, or when the server encounters an error processing the prompt.\n /// is .\n public static ValueTask GetPromptAsync(\n this IMcpClient client,\n string name,\n IReadOnlyDictionary? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(name);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n return client.SendRequestAsync(\n RequestMethods.PromptsGet,\n new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },\n McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,\n McpJsonUtilities.JsonContext.Default.GetPromptResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Retrieves a list of available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resource templates as instances.\n /// \n /// \n /// This method fetches all available resource templates from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resource templates and that responds with paginated responses, consider using \n /// instead, as it streams templates as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListResourceTemplatesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resourceTemplates = null;\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resourceTemplates ??= new List(templateResults.ResourceTemplates.Count);\n foreach (var template in templateResults.ResourceTemplates)\n {\n resourceTemplates.Add(new McpClientResourceTemplate(client, template));\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n\n return resourceTemplates;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resource templates as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resource templates from the server, which allows processing templates\n /// as they arrive rather than waiting for all templates to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with templates split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resource templates.\n /// \n /// \n /// \n /// \n /// // Enumerate all resource templates available on the server\n /// await foreach (var template in client.EnumerateResourceTemplatesAsync())\n /// {\n /// Console.WriteLine($\"Template: {template.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourceTemplatesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var templateResult in templateResults.ResourceTemplates)\n {\n yield return new McpClientResourceTemplate(client, templateResult);\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resources as instances.\n /// \n /// \n /// This method fetches all available resources from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resources and that responds with paginated responses, consider using \n /// instead, as it streams resources as they arrive rather than loading them all at once.\n /// \n /// \n /// \n /// \n /// // Get all resources available on the server\n /// var resources = await client.ListResourcesAsync();\n /// \n /// // Display information about each resource\n /// foreach (var resource in resources)\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListResourcesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resources = null;\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resources ??= new List(resourceResults.Resources.Count);\n foreach (var resource in resourceResults.Resources)\n {\n resources.Add(new McpClientResource(client, resource));\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n\n return resources;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resources as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resources from the server, which allows processing resources\n /// as they arrive rather than waiting for all resources to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with resources split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resources.\n /// \n /// \n /// \n /// \n /// // Enumerate all resources available on the server\n /// await foreach (var resource in client.EnumerateResourcesAsync())\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourcesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var resource in resourceResults.Resources)\n {\n yield return new McpClientResource(client, resource);\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return ReadResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri template of the resource.\n /// Arguments to use to format .\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uriTemplate, IReadOnlyDictionary arguments, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uriTemplate);\n Throw.IfNull(arguments);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = UriTemplate.FormatUri(uriTemplate, arguments) },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests completion suggestions for a prompt argument or resource reference.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The reference object specifying the type and optional URI or name.\n /// The name of the argument for which completions are requested.\n /// The current value of the argument, used to filter relevant completions.\n /// The to monitor for cancellation requests. The default is .\n /// A containing completion suggestions.\n /// \n /// \n /// This method allows clients to request auto-completion suggestions for arguments in a prompt template\n /// or for resource references.\n /// \n /// \n /// When working with prompt references, the server will return suggestions for the specified argument\n /// that match or begin with the current argument value. This is useful for implementing intelligent\n /// auto-completion in user interfaces.\n /// \n /// \n /// When working with resource references, the server will return suggestions relevant to the specified \n /// resource URI.\n /// \n /// \n /// is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n /// The server returned an error response.\n public static ValueTask CompleteAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(reference);\n Throw.IfNullOrWhiteSpace(argumentName);\n\n return client.SendRequestAsync(\n RequestMethods.CompletionComplete,\n new()\n {\n Ref = reference,\n Argument = new Argument { Name = argumentName, Value = argumentValue }\n },\n McpJsonUtilities.JsonContext.Default.CompleteRequestParams,\n McpJsonUtilities.JsonContext.Default.CompleteResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesSubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n public static Task SubscribeToResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return SubscribeToResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesUnsubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return UnsubscribeFromResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Invokes a tool on the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the tool to call on the server..\n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// is .\n /// is .\n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// // Call a simple echo tool with a string argument\n /// var result = await client.CallToolAsync(\n /// \"echo\",\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public static ValueTask CallToolAsync(\n this IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(toolName);\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n if (progress is not null)\n {\n return SendRequestWithProgressAsync(client, toolName, arguments, progress, serializerOptions, cancellationToken);\n }\n\n return client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken);\n\n static async ValueTask SendRequestWithProgressAsync(\n IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments,\n IProgress progress,\n JsonSerializerOptions serializerOptions,\n CancellationToken cancellationToken)\n {\n ProgressToken progressToken = new(Guid.NewGuid().ToString(\"N\"));\n\n await using var _ = client.RegisterNotificationHandler(NotificationMethods.ProgressNotification,\n (notification, cancellationToken) =>\n {\n if (JsonSerializer.Deserialize(notification.Params, McpJsonUtilities.JsonContext.Default.ProgressNotificationParams) is { } pn &&\n pn.ProgressToken == progressToken)\n {\n progress.Report(pn.Progress);\n }\n\n return default;\n }).ConfigureAwait(false);\n\n return await client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n ProgressToken = progressToken,\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n }\n\n /// \n /// Converts the contents of a into a pair of\n /// and instances to use\n /// as inputs into a operation.\n /// \n /// \n /// The created pair of messages and options.\n /// is .\n internal static (IList Messages, ChatOptions? Options) ToChatClientArguments(\n this CreateMessageRequestParams requestParams)\n {\n Throw.IfNull(requestParams);\n\n ChatOptions? options = null;\n\n if (requestParams.MaxTokens is int maxTokens)\n {\n (options ??= new()).MaxOutputTokens = maxTokens;\n }\n\n if (requestParams.Temperature is float temperature)\n {\n (options ??= new()).Temperature = temperature;\n }\n\n if (requestParams.StopSequences is { } stopSequences)\n {\n (options ??= new()).StopSequences = stopSequences.ToArray();\n }\n\n List messages =\n (from sm in requestParams.Messages\n let aiContent = sm.Content.ToAIContent()\n where aiContent is not null\n select new ChatMessage(sm.Role == Role.Assistant ? ChatRole.Assistant : ChatRole.User, [aiContent]))\n .ToList();\n\n return (messages, options);\n }\n\n /// Converts the contents of a into a .\n /// The whose contents should be extracted.\n /// The created .\n /// is .\n internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chatResponse)\n {\n Throw.IfNull(chatResponse);\n\n // The ChatResponse can include multiple messages, of varying modalities, but CreateMessageResult supports\n // only either a single blob of text or a single image. Heuristically, we'll use an image if there is one\n // in any of the response messages, or we'll use all the text from them concatenated, otherwise.\n\n ChatMessage? lastMessage = chatResponse.Messages.LastOrDefault();\n\n ContentBlock? content = null;\n if (lastMessage is not null)\n {\n foreach (var lmc in lastMessage.Contents)\n {\n if (lmc is DataContent dc && (dc.HasTopLevelMediaType(\"image\") || dc.HasTopLevelMediaType(\"audio\")))\n {\n content = dc.ToContent();\n }\n }\n }\n\n return new()\n {\n Content = content ?? new TextContentBlock { Text = lastMessage?.Text ?? string.Empty },\n Model = chatResponse.ModelId ?? \"unknown\",\n Role = lastMessage?.Role == ChatRole.User ? Role.User : Role.Assistant,\n StopReason = chatResponse.FinishReason == ChatFinishReason.Length ? \"maxTokens\" : \"endTurn\",\n };\n }\n\n /// \n /// Creates a sampling handler for use with that will\n /// satisfy sampling requests using the specified .\n /// \n /// The with which to satisfy sampling requests.\n /// The created handler delegate that can be assigned to .\n /// \n /// \n /// This method creates a function that converts MCP message requests into chat client calls, enabling\n /// an MCP client to generate text or other content using an actual AI model via the provided chat client.\n /// \n /// \n /// The handler can process text messages, image messages, and resource messages as defined in the\n /// Model Context Protocol.\n /// \n /// \n /// is .\n public static Func, CancellationToken, ValueTask> CreateSamplingHandler(\n this IChatClient chatClient)\n {\n Throw.IfNull(chatClient);\n\n return async (requestParams, progress, cancellationToken) =>\n {\n Throw.IfNull(requestParams);\n\n var (messages, options) = requestParams.ToChatClientArguments();\n var progressToken = requestParams.ProgressToken;\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false))\n {\n updates.Add(update);\n\n if (progressToken is not null)\n {\n progress.Report(new()\n {\n Progress = updates.Count,\n });\n }\n }\n\n return updates.ToChatResponse().ToCreateMessageResult();\n };\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// , , and \n /// level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LoggingLevel level, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.LoggingSetLevel,\n new() { Level = level },\n McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// and level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LogLevel level, CancellationToken cancellationToken = default) =>\n SetLoggingLevel(client, McpServer.ToLoggingLevel(level), cancellationToken);\n\n /// Convers a dictionary with values to a dictionary with values.\n private static Dictionary? ToArgumentsDictionary(\n IReadOnlyDictionary? arguments, JsonSerializerOptions options)\n {\n var typeInfo = options.GetTypeInfo();\n\n Dictionary? result = null;\n if (arguments is not null)\n {\n result = new(arguments.Count);\n foreach (var kvp in arguments)\n {\n result.Add(kvp.Key, kvp.Value is JsonElement je ? je : JsonSerializer.SerializeToElement(kvp.Value, typeInfo));\n }\n }\n\n return result;\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Reference.cs", "using ModelContextProtocol.Client;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a reference to a resource or prompt in the Model Context Protocol.\n/// \n/// \n/// \n/// References are commonly used with to request completion suggestions for arguments,\n/// and with other methods that need to reference resources or prompts.\n/// \n/// \n/// See the schema for details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class Reference\n{\n /// Prevent external derivations.\n private protected Reference() \n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This can be \"ref/resource\" or \"ref/prompt\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override Reference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? name = null;\n string? title = null;\n string? uri = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n default:\n break;\n }\n }\n\n // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n\n switch (type)\n {\n case \"ref/prompt\":\n if (name is null)\n {\n throw new JsonException(\"Prompt references must have a 'name' property.\");\n }\n\n return new PromptReference { Name = name, Title = title };\n\n case \"ref/resource\":\n if (uri is null)\n {\n throw new JsonException(\"Resource references must have a 'uri' property.\");\n }\n\n return new ResourceTemplateReference { Uri = uri };\n\n default:\n throw new JsonException($\"Unknown content type: '{type}'\");\n }\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, Reference value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case PromptReference pr:\n writer.WriteString(\"name\", pr.Name);\n if (pr.Title is not null)\n {\n writer.WriteString(\"title\", pr.Title);\n }\n break;\n\n case ResourceTemplateReference rtr:\n writer.WriteString(\"uri\", rtr.Uri);\n break;\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// \n/// Represents a reference to a prompt, identified by its name.\n/// \npublic sealed class PromptReference : Reference, IBaseMetadata\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public PromptReference() => Type = \"ref/prompt\";\n\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Name}\\\"\";\n}\n\n/// \n/// Represents a reference to a resource or resource template definition.\n/// \npublic sealed class ResourceTemplateReference : Reference\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public ResourceTemplateReference() => Type = \"ref/resource\";\n\n /// \n /// Gets or sets the URI or URI template of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public required string? Uri { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Uri}\\\"\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ITransport.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Server;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a transport mechanism for MCP (Model Context Protocol) communication between clients and servers.\n/// \n/// \n/// \n/// The interface is the core abstraction for bidirectional communication.\n/// It provides methods for sending and receiving messages, abstracting away the underlying transport mechanism\n/// and allowing protocol implementations to be decoupled from communication details.\n/// \n/// \n/// Implementations of handle the serialization, transmission, and reception of\n/// messages over various channels like standard input/output streams and HTTP (Server-Sent Events).\n/// \n/// \n/// While is responsible for establishing a client's connection,\n/// represents an established session. Client implementations typically obtain an\n/// instance by calling .\n/// \n/// \npublic interface ITransport : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Gets a channel reader for receiving messages from the transport.\n /// \n /// \n /// \n /// The provides access to incoming JSON-RPC messages received by the transport.\n /// It returns a which allows consuming messages in a thread-safe manner.\n /// \n /// \n /// The reader will continue to provide messages as long as the transport is connected. When the transport\n /// is disconnected or disposed, the channel will be completed and no more messages will be available after\n /// any already transmitted messages are consumed.\n /// \n /// \n ChannelReader MessageReader { get; }\n\n /// \n /// Sends a JSON-RPC message through the transport.\n /// \n /// The JSON-RPC message to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// \n /// \n /// This method serializes and sends the provided JSON-RPC message through the transport connection.\n /// \n /// \n /// This is a core method used by higher-level abstractions in the MCP protocol implementation.\n /// Most client code should use the higher-level methods provided by ,\n /// , , or ,\n /// rather than accessing this method directly.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.ObjectModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides an that calls a tool via an .\n/// \n/// \n/// \n/// The class encapsulates an along with a description of \n/// a tool available via that client, allowing it to be invoked as an . This enables integration\n/// with AI models that support function calling capabilities.\n/// \n/// \n/// Tools retrieved from an MCP server can be customized for model presentation using methods like\n/// and without changing the underlying tool functionality.\n/// \n/// \n/// Typically, you would get instances of this class by calling the \n/// or extension methods on an instance.\n/// \n/// \npublic sealed class McpClientTool : AIFunction\n{\n /// Additional properties exposed from tools.\n private static readonly ReadOnlyDictionary s_additionalProperties =\n new(new Dictionary()\n {\n [\"Strict\"] = false, // some MCP schemas may not meet \"strict\" requirements\n });\n\n private readonly IMcpClient _client;\n private readonly string _name;\n private readonly string _description;\n private readonly IProgress? _progress;\n\n internal McpClientTool(\n IMcpClient client,\n Tool tool,\n JsonSerializerOptions serializerOptions,\n string? name = null,\n string? description = null,\n IProgress? progress = null)\n {\n _client = client;\n ProtocolTool = tool;\n JsonSerializerOptions = serializerOptions;\n _name = name ?? tool.Name;\n _description = description ?? tool.Description ?? string.Empty;\n _progress = progress;\n }\n\n /// \n /// Gets the protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the tool,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// It contains the original metadata about the tool as provided by the server, including its\n /// name, description, and schema information before any customizations applied through methods\n /// like or .\n /// \n public Tool ProtocolTool { get; }\n\n /// \n public override string Name => _name;\n\n /// Gets the tool's title.\n public string? Title => ProtocolTool.Title ?? ProtocolTool.Annotations?.Title;\n\n /// \n public override string Description => _description;\n\n /// \n public override JsonElement JsonSchema => ProtocolTool.InputSchema;\n\n /// \n public override JsonElement? ReturnJsonSchema => ProtocolTool.OutputSchema;\n\n /// \n public override JsonSerializerOptions JsonSerializerOptions { get; }\n\n /// \n public override IReadOnlyDictionary AdditionalProperties => s_additionalProperties;\n\n /// \n protected async override ValueTask InvokeCoreAsync(\n AIFunctionArguments arguments, CancellationToken cancellationToken)\n {\n CallToolResult result = await CallAsync(arguments, _progress, JsonSerializerOptions, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult);\n }\n\n /// \n /// Invokes the tool on the server.\n /// \n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// \n /// The base method is overridden to invoke this method.\n /// The only difference in behavior is will serialize the resulting \"/>\n /// such that the returned is a containing the serialized .\n /// This method is intended to be called directly by user code, whereas the base \n /// is intended to be used polymorphically via the base class, typically as part of an operation.\n /// \n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// var result = await tool.CallAsync(\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public ValueTask CallAsync(\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default) =>\n _client.CallToolAsync(ProtocolTool.Name, arguments, progress, serializerOptions, cancellationToken);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified name from its property.\n /// \n /// The model-facing name to give the tool.\n /// A new instance of with the provided name.\n /// \n /// \n /// This is useful for optimizing the tool name for specific models or for prefixing the tool name \n /// with a namespace to avoid conflicts.\n /// \n /// \n /// Changing the name can help with:\n /// \n /// \n /// Making the tool name more intuitive for the model\n /// Preventing name collisions when using tools from multiple sources\n /// Creating specialized versions of a general tool for specific contexts\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool name, so no mapping is required on the server side. This new name only affects\n /// the value returned from this instance's .\n /// \n /// \n public McpClientTool WithName(string name) =>\n new(_client, ProtocolTool, JsonSerializerOptions, name, _description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified description from its property.\n /// \n /// The description to give the tool.\n /// \n /// \n /// Changing the description can help the model better understand the tool's purpose or provide more\n /// context about how the tool should be used. This is particularly useful when:\n /// \n /// \n /// The original description is too technical or lacks clarity for the model\n /// You want to add example usage scenarios to improve the model's understanding\n /// You need to tailor the tool's description for specific model requirements\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool description, so no mapping is required on the server side. This new description only affects\n /// the value returned from this instance's .\n /// \n /// \n /// A new instance of with the provided description.\n public McpClientTool WithDescription(string description) =>\n new(_client, ProtocolTool, JsonSerializerOptions, _name, description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to report progress via the specified .\n /// \n /// The to which progress notifications should be reported.\n /// \n /// \n /// Adding an to the tool does not impact how it is reported to any AI model.\n /// Rather, when the tool is invoked, the request to the MCP server will include a unique progress token,\n /// and any progress notifications issued by the server with that progress token while the operation is in\n /// flight will be reported to the instance.\n /// \n /// \n /// Only one can be specified at a time. Calling again\n /// will overwrite any previously specified progress instance.\n /// \n /// \n /// A new instance of , configured with the provided progress instance.\n public McpClientTool WithProgress(IProgress progress)\n {\n Throw.IfNull(progress);\n\n return new McpClientTool(_client, ProtocolTool, JsonSerializerOptions, _name, _description, progress);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitRequestParams.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued from the server to elicit additional information from the user via the client.\n/// \npublic sealed class ElicitRequestParams\n{\n /// \n /// Gets or sets the message to present to the user.\n /// \n [JsonPropertyName(\"message\")]\n public string Message { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the requested schema.\n /// \n /// \n /// May be one of , , , or .\n /// \n [JsonPropertyName(\"requestedSchema\")]\n [field: MaybeNull]\n public RequestSchema RequestedSchema\n {\n get => field ??= new RequestSchema();\n set => field = value;\n }\n\n /// Represents a request schema used in an elicitation request.\n public class RequestSchema\n {\n /// Gets the type of the schema.\n /// This is always \"object\".\n [JsonPropertyName(\"type\")]\n public string Type => \"object\";\n\n /// Gets or sets the properties of the schema.\n [JsonPropertyName(\"properties\")]\n [field: MaybeNull]\n public IDictionary Properties\n {\n get => field ??= new Dictionary();\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets the required properties of the schema.\n [JsonPropertyName(\"required\")]\n public IList? Required { get; set; }\n }\n\n /// \n /// Represents restricted subset of JSON Schema: \n /// , , , or .\n /// \n [JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n public abstract class PrimitiveSchemaDefinition\n {\n /// Prevent external derivations.\n protected private PrimitiveSchemaDefinition()\n {\n }\n\n /// Gets the type of the schema.\n [JsonPropertyName(\"type\")]\n public abstract string Type { get; set; }\n\n /// Gets or sets a title for the schema.\n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// Gets or sets a description for the schema.\n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override PrimitiveSchemaDefinition? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? title = null;\n string? description = null;\n int? minLength = null;\n int? maxLength = null;\n string? format = null;\n double? minimum = null;\n double? maximum = null;\n bool? defaultBool = null;\n IList? enumValues = null;\n IList? enumNames = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"title\":\n title = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"minLength\":\n minLength = reader.GetInt32();\n break;\n\n case \"maxLength\":\n maxLength = reader.GetInt32();\n break;\n\n case \"format\":\n format = reader.GetString();\n break;\n\n case \"minimum\":\n minimum = reader.GetDouble();\n break;\n\n case \"maximum\":\n maximum = reader.GetDouble();\n break;\n\n case \"default\":\n defaultBool = reader.GetBoolean();\n break;\n\n case \"enum\":\n enumValues = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n case \"enumNames\":\n enumNames = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n default:\n break;\n }\n }\n\n if (type is null)\n {\n throw new JsonException(\"The 'type' property is required.\");\n }\n\n PrimitiveSchemaDefinition? psd = null;\n switch (type)\n {\n case \"string\":\n if (enumValues is not null)\n {\n psd = new EnumSchema\n {\n Enum = enumValues,\n EnumNames = enumNames\n };\n }\n else\n {\n psd = new StringSchema\n {\n MinLength = minLength,\n MaxLength = maxLength,\n Format = format,\n };\n }\n break;\n\n case \"integer\":\n case \"number\":\n psd = new NumberSchema\n {\n Minimum = minimum,\n Maximum = maximum,\n };\n break;\n\n case \"boolean\":\n psd = new BooleanSchema\n {\n Default = defaultBool,\n };\n break;\n }\n\n if (psd is not null)\n {\n psd.Type = type;\n psd.Title = title;\n psd.Description = description;\n }\n\n return psd;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, PrimitiveSchemaDefinition value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n if (value.Title is not null)\n {\n writer.WriteString(\"title\", value.Title);\n }\n if (value.Description is not null)\n {\n writer.WriteString(\"description\", value.Description);\n }\n\n switch (value)\n {\n case StringSchema stringSchema:\n if (stringSchema.MinLength.HasValue)\n {\n writer.WriteNumber(\"minLength\", stringSchema.MinLength.Value);\n }\n if (stringSchema.MaxLength.HasValue)\n {\n writer.WriteNumber(\"maxLength\", stringSchema.MaxLength.Value);\n }\n if (stringSchema.Format is not null)\n {\n writer.WriteString(\"format\", stringSchema.Format);\n }\n break;\n\n case NumberSchema numberSchema:\n if (numberSchema.Minimum.HasValue)\n {\n writer.WriteNumber(\"minimum\", numberSchema.Minimum.Value);\n }\n if (numberSchema.Maximum.HasValue)\n {\n writer.WriteNumber(\"maximum\", numberSchema.Maximum.Value);\n }\n break;\n\n case BooleanSchema booleanSchema:\n if (booleanSchema.Default.HasValue)\n {\n writer.WriteBoolean(\"default\", booleanSchema.Default.Value);\n }\n break;\n\n case EnumSchema enumSchema:\n if (enumSchema.Enum is not null)\n {\n writer.WritePropertyName(\"enum\");\n JsonSerializer.Serialize(writer, enumSchema.Enum, McpJsonUtilities.JsonContext.Default.IListString);\n }\n if (enumSchema.EnumNames is not null)\n {\n writer.WritePropertyName(\"enumNames\");\n JsonSerializer.Serialize(writer, enumSchema.EnumNames, McpJsonUtilities.JsonContext.Default.IListString);\n }\n break;\n\n default:\n throw new JsonException($\"Unexpected schema type: {value.GetType().Name}\");\n }\n\n writer.WriteEndObject();\n }\n }\n }\n\n /// Represents a schema for a string type.\n public sealed class StringSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the minimum length for the string.\n [JsonPropertyName(\"minLength\")]\n public int? MinLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Minimum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the maximum length for the string.\n [JsonPropertyName(\"maxLength\")]\n public int? MaxLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Maximum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets a specific format for the string (\"email\", \"uri\", \"date\", or \"date-time\").\n [JsonPropertyName(\"format\")]\n public string? Format\n {\n get => field;\n set\n {\n if (value is not (null or \"email\" or \"uri\" or \"date\" or \"date-time\"))\n {\n throw new ArgumentException(\"Format must be 'email', 'uri', 'date', or 'date-time'.\", nameof(value));\n }\n\n field = value;\n }\n }\n }\n\n /// Represents a schema for a number or integer type.\n public sealed class NumberSchema : PrimitiveSchemaDefinition\n {\n /// \n [field: MaybeNull]\n public override string Type\n {\n get => field ??= \"number\";\n set\n {\n if (value is not (\"number\" or \"integer\"))\n {\n throw new ArgumentException(\"Type must be 'number' or 'integer'.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the minimum allowed value.\n [JsonPropertyName(\"minimum\")]\n public double? Minimum { get; set; }\n\n /// Gets or sets the maximum allowed value.\n [JsonPropertyName(\"maximum\")]\n public double? Maximum { get; set; }\n }\n\n /// Represents a schema for a Boolean type.\n public sealed class BooleanSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"boolean\";\n set\n {\n if (value is not \"boolean\")\n {\n throw new ArgumentException(\"Type must be 'boolean'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the default value for the Boolean.\n [JsonPropertyName(\"default\")]\n public bool? Default { get; set; }\n }\n\n /// Represents a schema for an enum type.\n public sealed class EnumSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the list of allowed string values for the enum.\n [JsonPropertyName(\"enum\")]\n [field: MaybeNull]\n public IList Enum\n {\n get => field ??= [];\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets optional display names corresponding to the enum values.\n [JsonPropertyName(\"enumNames\")]\n public IList? EnumNames { get; set; }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/NotificationHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol;\n\n/// Provides thread-safe storage for notification handlers.\ninternal sealed class NotificationHandlers\n{\n /// A dictionary of linked lists of registrations, indexed by the notification method.\n private readonly Dictionary _handlers = [];\n\n /// Gets the object to be used for all synchronization.\n private object SyncObj => _handlers;\n\n /// \n /// Registers a collection of notification handlers at once.\n /// \n /// \n /// A collection of notification method names paired with their corresponding handler functions.\n /// Each key in the collection is a notification method name, and each value is a handler function\n /// that will be invoked when a notification with that method name is received.\n /// \n /// \n /// \n /// This method is typically used during client or server initialization to register\n /// all notification handlers provided in capabilities.\n /// \n /// \n /// Registrations completed with this method are permanent and non-removable.\n /// This differs from handlers registered with which can be temporary.\n /// \n /// \n /// When multiple handlers are registered for the same method, all handlers will be invoked\n /// in reverse order of registration (newest first) when a notification is received.\n /// \n /// \n /// The registered handlers will be invoked by when a notification\n /// with the corresponding method name is received.\n /// \n /// \n public void RegisterRange(IEnumerable>> handlers)\n {\n foreach (var entry in handlers)\n {\n _ = Register(entry.Key, entry.Value, temporary: false);\n }\n }\n\n /// \n /// Adds a notification handler as part of configuring the endpoint.\n /// \n /// The notification method for which the handler is being registered.\n /// The handler being registered.\n /// \n /// if the registration can be removed later; if it cannot.\n /// If , the registration will be permanent: calling \n /// on the returned instance will not unregister the handler.\n /// \n /// \n /// An that when disposed will unregister the handler if is .\n /// \n /// \n /// Multiple handlers can be registered for the same method. When a notification for that method is received,\n /// all registered handlers will be invoked in reverse order of registration (newest first).\n /// \n public IAsyncDisposable Register(\n string method, Func handler, bool temporary = true)\n {\n // Create the new registration instance.\n Registration reg = new(this, method, handler, temporary);\n\n // Store the registration into the dictionary. If there's not currently a registration for the method,\n // then this registration instance just becomes the single value. If there is currently a registration,\n // then this new registration becomes the new head of the linked list, and the old head becomes the next\n // item in the list.\n lock (SyncObj)\n {\n if (_handlers.TryGetValue(method, out var existingHandlerHead))\n {\n reg.Next = existingHandlerHead;\n existingHandlerHead.Prev = reg;\n }\n\n _handlers[method] = reg;\n }\n\n // Return the new registration. It must be disposed of when no longer used, or it will end up being\n // leaked into the list. This is the same as with CancellationToken.Register.\n return reg;\n }\n\n /// \n /// Invokes all registered handlers for the specified notification method.\n /// \n /// The notification method name to invoke handlers for.\n /// The notification object to pass to each handler.\n /// A token that can be used to cancel the operation.\n /// \n /// Handlers are invoked in reverse order of registration (newest first).\n /// If any handler throws an exception, all handlers will still be invoked, and an \n /// containing all exceptions will be thrown after all handlers have been invoked.\n /// \n public async Task InvokeHandlers(string method, JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // If there are no handlers registered for this method, we're done.\n Registration? reg;\n lock (SyncObj)\n {\n if (!_handlers.TryGetValue(method, out reg))\n {\n return;\n }\n }\n\n // Invoke each handler in the list. We guarantee that we'll try to invoke\n // any handlers that were in the list when the list was fetched from the dictionary,\n // which is why DisposeAsync doesn't modify the Prev/Next of the registration being\n // disposed; if those were nulled out, we'd be unable to walk around it in the list\n // if we happened to be on that item when it was disposed.\n List? exceptions = null;\n while (reg is not null)\n {\n try\n {\n await reg.InvokeAsync(notification, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e)\n {\n (exceptions ??= []).Add(e);\n }\n\n lock (SyncObj)\n {\n reg = reg.Next;\n }\n }\n\n if (exceptions is not null)\n {\n throw new AggregateException(exceptions);\n }\n }\n\n /// Provides storage for a handler registration.\n private sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable) : IAsyncDisposable\n {\n /// Used to prevent deadlocks during disposal.\n /// \n /// The task returned from does not complete until all invocations of the handler\n /// have completed and no more will be performed, so that the consumer can then trust that any resources accessed\n /// by that handler are no longer in use and may be cleaned up. If were to be invoked\n /// and its task awaited from within the invocation of the handler, however, that would result in deadlock, since\n /// the task wouldn't complete until the invocation completed, and the invocation wouldn't complete until the task\n /// completed. To circument that, we track via an in-flight invocations. If\n /// detects it's being invoked from within an invocation, it will avoid waiting. For\n /// simplicity, we don't require that it's the same handler.\n /// \n private static readonly AsyncLocal s_invokingAncestor = new();\n\n /// The parent to which this registration belongs.\n private readonly NotificationHandlers _handlers = handlers;\n\n /// The method with which this registration is associated.\n private readonly string _method = method;\n \n /// The handler this registration represents.\n private readonly Func _handler = handler;\n\n /// true if this instance is temporary; false if it's permanent\n private readonly bool _temporary = unregisterable;\n\n /// Provides a task that can await to know when all in-flight invocations have completed.\n /// \n /// This will only be initialized if sees in-flight invocations, in which case it'll initialize\n /// this and then await its task. The task will be completed when the last\n /// in-flight notification completes.\n /// \n private TaskCompletionSource? _disposeTcs;\n \n /// The number of remaining references to this registration.\n /// \n /// The ref count starts life at 1 to represent the whole registration; that ref count will be subtracted when\n /// the instance is disposed. Every invocation then temporarily increases the ref count before invocation and\n /// decrements it after. When is called, it decrements the ref count. In the common\n /// case, that'll bring the count down to 0, in which case the instance will never be subsequently invoked.\n /// If, however, after that decrement the count is still positive, then there are in-flight invocations; the last\n /// one of those to complete will end up decrementing the ref count to 0.\n /// \n private int _refCount = 1;\n\n /// Tracks whether has ever been invoked.\n /// \n /// It's rare but possible is called multiple times. Only the first\n /// should decrement the initial ref count, but they all must wait until all invocations have quiesced.\n /// \n private bool _disposedCalled = false;\n\n /// The next registration in the linked list.\n public Registration? Next;\n /// \n /// The previous registration in the linked list of handlers for a specific notification method.\n /// Used to maintain the bidirectional linked list when handlers are added or removed.\n /// \n public Registration? Prev;\n\n /// Removes the registration.\n public async ValueTask DisposeAsync()\n {\n if (!_temporary)\n {\n return;\n }\n\n lock (_handlers.SyncObj)\n {\n // If DisposeAsync was previously called, we don't want to do all of the work again\n // to remove the registration from the list, and we must not do the work again to\n // decrement the ref count and possibly initialize the _disposeTcs.\n if (!_disposedCalled)\n {\n _disposedCalled = true;\n\n // If this handler is the head of the list for this method, we need to update\n // the dictionary, either to point to a different head, or if this is the only\n // item in the list, to remove the entry from the dictionary entirely.\n if (_handlers._handlers.TryGetValue(_method, out var handlers) && handlers == this)\n {\n if (Next is not null)\n {\n _handlers._handlers[_method] = Next;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n\n // Remove the registration from the linked list by routing the nodes around it\n // to point past this one. Importantly, we do not modify this node's Next or Prev.\n // We want to ensure that an enumeration through all of the registrations can still\n // progress through this one.\n if (Prev is not null)\n {\n Prev.Next = Next;\n }\n if (Next is not null)\n {\n Next.Prev = Prev;\n }\n\n // Decrement the ref count. In the common case, there's no in-flight invocation for\n // this handler. However, in the uncommon case that there is, we need to wait for\n // that invocation to complete. To do that, initialize the _disposeTcs. It's created\n // with RunContinuationsAsynchronously so that completing it doesn't run the continuation\n // under any held locks.\n if (--_refCount != 0)\n {\n Debug.Assert(_disposeTcs is null);\n _disposeTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);\n }\n }\n }\n\n // Ensure that DisposeAsync doesn't complete until all in-flight invocations have completed,\n // unless our call chain includes one of those in-flight invocations, in which case waiting\n // would deadlock.\n if (_disposeTcs is not null && s_invokingAncestor.Value == 0)\n {\n await _disposeTcs.Task.ConfigureAwait(false);\n }\n }\n\n /// Invoke the handler associated with the registration.\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // For permanent registrations, skip all the tracking overhead and just invoke the handler.\n if (!_temporary)\n {\n return _handler(notification, cancellationToken);\n }\n\n // For temporary registrations, track the invocation and coordinate with disposal.\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n\n /// Invoke the handler associated with the temporary registration.\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // Check whether we need to handle this registration. If DisposeAsync has been called,\n // then even if there are in-flight invocations for it, we avoid adding more.\n // If DisposeAsync has not been called, then we need to increment the ref count to\n // signal that there's another in-flight invocation.\n lock (_handlers.SyncObj)\n {\n Debug.Assert(_refCount != 0 || _disposedCalled, $\"Expected {nameof(_disposedCalled)} == true when {nameof(_refCount)} == 0\");\n if (_disposedCalled)\n {\n return;\n }\n\n Debug.Assert(_refCount > 0);\n _refCount++;\n }\n\n // Ensure that if DisposeAsync is called from within the handler, it won't deadlock by waiting\n // for the in-flight invocation to complete.\n s_invokingAncestor.Value++;\n\n try\n {\n // Invoke the handler.\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n // Undo the in-flight tracking.\n s_invokingAncestor.Value--;\n\n // Now decrement the ref count we previously incremented. If that brings the ref count to 0,\n // DisposeAsync must have been called while this was in-flight, which also means it's now\n // waiting on _disposeTcs; unblock it.\n lock (_handlers.SyncObj)\n {\n _refCount--;\n if (_refCount == 0)\n {\n Debug.Assert(_disposedCalled);\n Debug.Assert(_disposeTcs is not null);\n bool completed = _disposeTcs!.TrySetResult(true);\n Debug.Assert(completed);\n }\n }\n }\n }\n }\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/Client/McpHttpClient.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\n#if NET\nusing System.Net.Http.Json;\n#else\nusing System.Text;\nusing System.Text.Json;\n#endif\n\nnamespace ModelContextProtocol.Client;\n\ninternal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n Debug.Assert(request.Content is null, \"The request body should only be supplied as a JsonRpcMessage\");\n Debug.Assert(message is null || request.Method == HttpMethod.Post, \"All messages should be sent in POST requests.\");\n\n using var content = CreatePostBodyContent(message);\n request.Content = content;\n return await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);\n }\n\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null)\n {\n return null;\n }\n\n#if NET\n return JsonContent.Create(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n#else\n return new StringContent(\n JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage),\n Encoding.UTF8,\n \"application/json\"\n );\n#endif\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// request from a server to sample an LLM via the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageRequestParams : RequestParams\n{\n /// \n /// Gets or sets an indication as to which server contexts should be included in the prompt.\n /// \n /// \n /// The client may ignore this request.\n /// \n [JsonPropertyName(\"includeContext\")]\n public ContextInclusion? IncludeContext { get; init; }\n\n /// \n /// Gets or sets the maximum number of tokens to generate in the LLM response, as requested by the server.\n /// \n /// \n /// A token is generally a word or part of a word in the text. Setting this value helps control \n /// response length and computation time. The client may choose to sample fewer tokens than requested.\n /// \n [JsonPropertyName(\"maxTokens\")]\n public int? MaxTokens { get; init; }\n\n /// \n /// Gets or sets the messages requested by the server to be included in the prompt.\n /// \n [JsonPropertyName(\"messages\")]\n public required IReadOnlyList Messages { get; init; }\n\n /// \n /// Gets or sets optional metadata to pass through to the LLM provider.\n /// \n /// \n /// The format of this metadata is provider-specific and can include model-specific settings or\n /// configuration that isn't covered by standard parameters. This allows for passing custom parameters \n /// that are specific to certain AI models or providers.\n /// \n [JsonPropertyName(\"metadata\")]\n public JsonElement? Metadata { get; init; }\n\n /// \n /// Gets or sets the server's preferences for which model to select.\n /// \n /// \n /// \n /// The client may ignore these preferences.\n /// \n /// \n /// These preferences help the client make an appropriate model selection based on the server's priorities\n /// for cost, speed, intelligence, and specific model hints.\n /// \n /// \n /// When multiple dimensions are specified (cost, speed, intelligence), the client should balance these\n /// based on their relative values. If specific model hints are provided, the client should evaluate them\n /// in order and prioritize them over numeric priorities.\n /// \n /// \n [JsonPropertyName(\"modelPreferences\")]\n public ModelPreferences? ModelPreferences { get; init; }\n\n /// \n /// Gets or sets optional sequences of characters that signal the LLM to stop generating text when encountered.\n /// \n /// \n /// \n /// When the model generates any of these sequences during sampling, text generation stops immediately,\n /// even if the maximum token limit hasn't been reached. This is useful for controlling generation \n /// endings or preventing the model from continuing beyond certain points.\n /// \n /// \n /// Stop sequences are typically case-sensitive, and typically the LLM will only stop generation when a produced\n /// sequence exactly matches one of the provided sequences. Common uses include ending markers like \"END\", punctuation\n /// like \".\", or special delimiter sequences like \"###\".\n /// \n /// \n [JsonPropertyName(\"stopSequences\")]\n public IReadOnlyList? StopSequences { get; init; }\n\n /// \n /// Gets or sets an optional system prompt the server wants to use for sampling.\n /// \n /// \n /// The client may modify or omit this prompt.\n /// \n [JsonPropertyName(\"systemPrompt\")]\n public string? SystemPrompt { get; init; }\n\n /// \n /// Gets or sets the temperature to use for sampling, as requested by the server.\n /// \n [JsonPropertyName(\"temperature\")]\n public float? Temperature { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseWriter.cs", "using ModelContextProtocol.Protocol;\nusing System.Buffers;\nusing System.Net.ServerSentEvents;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class SseWriter(string? messageEndpoint = null, BoundedChannelOptions? channelOptions = null) : IAsyncDisposable\n{\n private readonly Channel> _messages = Channel.CreateBounded>(channelOptions ?? new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private Utf8JsonWriter? _jsonWriter;\n private Task? _writeTask;\n private CancellationToken? _writeCancellationToken;\n\n private readonly SemaphoreSlim _disposeLock = new(1, 1);\n private bool _disposed;\n\n public Func>, CancellationToken, IAsyncEnumerable>>? MessageFilter { get; set; }\n\n public Task WriteAllAsync(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n // When messageEndpoint is set, the very first SSE event isn't really an IJsonRpcMessage, but there's no API to write a single\n // item of a different type, so we fib and special-case the \"endpoint\" event type in the formatter.\n if (messageEndpoint is not null && !_messages.Writer.TryWrite(new SseItem(null, \"endpoint\")))\n {\n throw new InvalidOperationException(\"You must call RunAsync before calling SendMessageAsync.\");\n }\n\n _writeCancellationToken = cancellationToken;\n\n var messages = _messages.Reader.ReadAllAsync(cancellationToken);\n if (MessageFilter is not null)\n {\n messages = MessageFilter(messages, cancellationToken);\n }\n\n _writeTask = SseFormatter.WriteAsync(messages, sseResponseStream, WriteJsonRpcMessageToBuffer, cancellationToken);\n return _writeTask;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(message);\n\n using var _ = await _disposeLock.LockAsync(cancellationToken).ConfigureAwait(false);\n\n if (_disposed)\n {\n // Don't throw an ODE, because this is disposed internally when the transport disconnects due to an abort\n // or sending all the responses for the a give given Streamable HTTP POST request, so the user might not be at fault.\n // There's precedence for no-oping here similar to writing to the response body of an aborted request in ASP.NET Core.\n return;\n }\n\n // Emit redundant \"event: message\" lines for better compatibility with other SDKs.\n await _messages.Writer.WriteAsync(new SseItem(message, SseParser.EventTypeDefault), cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);\n\n if (_disposed)\n {\n return;\n }\n\n _messages.Writer.Complete();\n try\n {\n if (_writeTask is not null)\n {\n await _writeTask.ConfigureAwait(false);\n }\n }\n catch (OperationCanceledException) when (_writeCancellationToken?.IsCancellationRequested == true)\n {\n // Ignore exceptions caused by intentional cancellation during shutdown.\n }\n finally\n {\n _jsonWriter?.Dispose();\n _disposed = true;\n }\n }\n\n private void WriteJsonRpcMessageToBuffer(SseItem item, IBufferWriter writer)\n {\n if (item.EventType == \"endpoint\" && messageEndpoint is not null)\n {\n writer.Write(Encoding.UTF8.GetBytes(messageEndpoint));\n return;\n }\n\n JsonSerializer.Serialize(GetUtf8JsonWriter(writer), item.Data, McpJsonUtilities.JsonContext.Default.JsonRpcMessage!);\n }\n\n private Utf8JsonWriter GetUtf8JsonWriter(IBufferWriter writer)\n {\n if (_jsonWriter is null)\n {\n _jsonWriter = new Utf8JsonWriter(writer);\n }\n else\n {\n _jsonWriter.Reset(writer);\n }\n\n return _jsonWriter;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/AIContentExtensions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\n#if !NET\nusing System.Runtime.InteropServices;\n#endif\nusing System.Text.Json;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for converting between Model Context Protocol (MCP) types and Microsoft.Extensions.AI types.\n/// \n/// \n/// This class serves as an adapter layer between Model Context Protocol (MCP) types and the model types\n/// from the Microsoft.Extensions.AI namespace.\n/// \npublic static class AIContentExtensions\n{\n /// \n /// Converts a to a object.\n /// \n /// The prompt message to convert.\n /// A object created from the prompt message.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries.\n /// \n public static ChatMessage ToChatMessage(this PromptMessage promptMessage)\n {\n Throw.IfNull(promptMessage);\n\n AIContent? content = ToAIContent(promptMessage.Content);\n\n return new()\n {\n RawRepresentation = promptMessage,\n Role = promptMessage.Role == Role.User ? ChatRole.User : ChatRole.Assistant,\n Contents = content is not null ? [content] : [],\n };\n }\n\n /// \n /// Converts a to a object.\n /// \n /// The tool result to convert.\n /// The identifier for the function call request that triggered the tool invocation.\n /// A object created from the tool result.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries. It produces a\n /// message containing a with result as a\n /// serialized .\n /// \n public static ChatMessage ToChatMessage(this CallToolResult result, string callId)\n {\n Throw.IfNull(result);\n Throw.IfNull(callId);\n\n return new(ChatRole.Tool, [new FunctionResultContent(callId, JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult))\n {\n RawRepresentation = result,\n }]);\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The prompt result containing messages to convert.\n /// A list of objects created from the prompt messages.\n /// \n /// This method transforms protocol-specific objects from a Model Context Protocol\n /// prompt result into standard objects that can be used with AI client libraries.\n /// \n public static IList ToChatMessages(this GetPromptResult promptResult)\n {\n Throw.IfNull(promptResult);\n\n return promptResult.Messages.Select(m => m.ToChatMessage()).ToList();\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The chat message to convert.\n /// A list of objects created from the chat message's contents.\n /// \n /// This method transforms standard objects used with AI client libraries into\n /// protocol-specific objects for the Model Context Protocol system.\n /// Only representable content items are processed.\n /// \n public static IList ToPromptMessages(this ChatMessage chatMessage)\n {\n Throw.IfNull(chatMessage);\n\n Role r = chatMessage.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n List messages = [];\n foreach (var content in chatMessage.Contents)\n {\n if (content is TextContent or DataContent)\n {\n messages.Add(new PromptMessage { Role = r, Content = content.ToContent() });\n }\n }\n\n return messages;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// \n /// The created . If the content can't be converted (such as when it's a resource link), is returned.\n /// \n /// \n /// This method converts Model Context Protocol content types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent? ToAIContent(this ContentBlock content)\n {\n Throw.IfNull(content);\n\n AIContent? ac = content switch\n {\n TextContentBlock textContent => new TextContent(textContent.Text),\n ImageContentBlock imageContent => new DataContent(Convert.FromBase64String(imageContent.Data), imageContent.MimeType),\n AudioContentBlock audioContent => new DataContent(Convert.FromBase64String(audioContent.Data), audioContent.MimeType),\n EmbeddedResourceBlock resourceContent => resourceContent.Resource.ToAIContent(),\n _ => null,\n };\n\n if (ac is not null)\n {\n ac.RawRepresentation = content;\n }\n\n return ac;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// The created .\n /// \n /// This method converts Model Context Protocol resource types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent ToAIContent(this ResourceContents content)\n {\n Throw.IfNull(content);\n\n AIContent ac = content switch\n {\n BlobResourceContents blobResource => new DataContent(Convert.FromBase64String(blobResource.Blob), blobResource.MimeType ?? \"application/octet-stream\"),\n TextResourceContents textResource => new TextContent(textResource.Text),\n _ => throw new NotSupportedException($\"Resource type '{content.GetType().Name}' is not supported.\")\n };\n\n (ac.AdditionalProperties ??= [])[\"uri\"] = content.Uri;\n ac.RawRepresentation = content;\n\n return ac;\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// The created instances.\n /// \n /// \n /// This method converts a collection of Model Context Protocol content objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple content items, such as\n /// when processing the contents of a message or response.\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic for text, images, audio, and resources.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent).OfType()];\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// A list of objects created from the resource contents.\n /// \n /// \n /// This method converts a collection of Model Context Protocol resource objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple resources, such as\n /// when processing the contents of a .\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic: text resources become objects and\n /// binary resources become objects.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent)];\n }\n\n internal static ContentBlock ToContent(this AIContent content) =>\n content switch\n {\n TextContent textContent => new TextContentBlock\n {\n Text = textContent.Text,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") => new ImageContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"audio\") => new AudioContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent => new EmbeddedResourceBlock\n {\n Resource = new BlobResourceContents\n {\n Blob = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n }\n },\n\n _ => new TextContentBlock\n {\n Text = JsonSerializer.Serialize(content, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))),\n }\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceTemplate.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource template that the server is capable of reading.\n/// \n/// \n/// Resource templates provide metadata about resources available on the server,\n/// including how to construct URIs for those resources.\n/// \npublic sealed class ResourceTemplate : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI template (according to RFC 6570) that can be used to construct resource URIs.\n /// \n [JsonPropertyName(\"uriTemplate\")]\n public required string UriTemplate { get; init; }\n\n /// \n /// Gets or sets a description of what this resource template represents.\n /// \n /// \n /// \n /// This description helps clients understand the purpose and content of resources\n /// that can be generated from this template. It can be used by client applications\n /// to provide context about available resource types or to display in user interfaces.\n /// \n /// \n /// For AI models, this description can serve as a hint about when and how to use\n /// the resource template, enhancing the model's ability to generate appropriate URIs.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource template, if known.\n /// \n /// \n /// \n /// Specifies the expected format of resources that can be generated from this template.\n /// This helps clients understand what type of content to expect when accessing resources\n /// created using this template.\n /// \n /// \n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, or \"application/json\" for JSON data.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource template.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource template. Clients can use this information to filter\n /// or prioritize resource templates for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n\n /// Gets whether contains any template expressions.\n [JsonIgnore]\n public bool IsTemplated => UriTemplate.Contains('{');\n\n /// Converts the into a .\n /// A if is ; otherwise, .\n public Resource? AsResource()\n {\n if (IsTemplated)\n {\n return null;\n }\n\n return new()\n {\n Uri = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n Annotations = Annotations,\n Meta = Meta,\n };\n }\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/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/Protocol/RequestParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for all request parameters.\n/// \n/// \n/// See the schema for details.\n/// \npublic abstract class RequestParams\n{\n /// Prevent external derivations.\n private protected RequestParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n [JsonIgnore]\n public ProgressToken? ProgressToken\n {\n get\n {\n if (Meta?[\"progressToken\"] is JsonValue progressToken)\n {\n if (progressToken.TryGetValue(out string? stringValue))\n {\n return new ProgressToken(stringValue);\n }\n\n if (progressToken.TryGetValue(out long longValue))\n {\n return new ProgressToken(longValue);\n }\n }\n\n return null;\n }\n set\n {\n if (value is null)\n {\n Meta?.Remove(\"progressToken\");\n }\n else\n {\n (Meta ??= [])[\"progressToken\"] = value.Value.Token switch\n {\n string s => JsonValue.Create(s),\n long l => JsonValue.Create(l),\n _ => throw new InvalidOperationException(\"ProgressToken must be a string or a long.\")\n };\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpException.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents an exception that is thrown when an Model Context Protocol (MCP) error occurs.\n/// \n/// \n/// This exception is used to represent failures to do with protocol-level concerns, such as invalid JSON-RPC requests,\n/// invalid parameters, or internal errors. It is not intended to be used for application-level errors.\n/// or from a may be \n/// propagated to the remote endpoint; sensitive information should not be included. If sensitive details need\n/// to be included, a different exception type should be used.\n/// \npublic class McpException : Exception\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpException()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public McpException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n public McpException(string message, Exception? innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// A .\n public McpException(string message, McpErrorCode errorCode) : this(message, null, errorCode)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message, inner exception, and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n /// A .\n public McpException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)\n {\n ErrorCode = errorCode;\n }\n\n /// \n /// Gets the error code associated with this exception.\n /// \n /// \n /// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:\n /// \n /// -32700: Parse error - Invalid JSON received\n /// -32600: Invalid request - The JSON is not a valid Request object\n /// -32601: Method not found - The method does not exist or is not available\n /// -32602: Invalid params - Invalid method parameters\n /// -32603: Internal error - Internal JSON-RPC error\n /// \n /// \n public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/CustomizableJsonStringEnumConverter.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.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\n#if !NET9_0_OR_GREATER\nusing System.Reflection;\n#endif\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n#if !NET9_0_OR_GREATER\nusing ModelContextProtocol;\n#endif\n\n// NOTE:\n// This is a workaround for lack of System.Text.Json's JsonStringEnumConverter\n// 9.x support for JsonStringEnumMemberNameAttribute. Once all builds use the System.Text.Json 9.x\n// version, this whole file can be removed. Note that the type is public so that external source\n// generators can use it, so removing it is a potential breaking change.\n\nnamespace ModelContextProtocol\n{\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// The enum type to convert.\n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class CustomizableJsonStringEnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum> :\n JsonStringEnumConverter where TEnum : struct, Enum\n {\n#if !NET9_0_OR_GREATER\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The converter automatically detects any enum members decorated with \n /// and uses those values during serialization and deserialization.\n /// \n public CustomizableJsonStringEnumConverter() :\n base(namingPolicy: ResolveNamingPolicy())\n {\n }\n\n private static JsonNamingPolicy? ResolveNamingPolicy()\n {\n var map = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)\n .Select(f => (f.Name, AttributeName: f.GetCustomAttribute()?.Name))\n .Where(pair => pair.AttributeName != null)\n .ToDictionary(pair => pair.Name, pair => pair.AttributeName);\n\n return map.Count > 0 ? new EnumMemberNamingPolicy(map!) : null;\n }\n\n private sealed class EnumMemberNamingPolicy(Dictionary map) : JsonNamingPolicy\n {\n public override string ConvertName(string name) =>\n map.TryGetValue(name, out string? newName) ?\n newName :\n name;\n }\n#endif\n }\n\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n [RequiresUnreferencedCode(\"Requires unreferenced code to instantiate the generic enum converter.\")]\n [RequiresDynamicCode(\"Requires dynamic code to instantiate the generic enum converter.\")]\n public sealed class CustomizableJsonStringEnumConverter : JsonConverterFactory\n {\n /// \n public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum;\n /// \n public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)\n {\n Type converterType = typeof(CustomizableJsonStringEnumConverter<>).MakeGenericType(typeToConvert)!;\n var factory = (JsonConverterFactory)Activator.CreateInstance(converterType)!;\n return factory.CreateConverter(typeToConvert, options);\n }\n }\n}\n\n#if !NET9_0_OR_GREATER\nnamespace System.Text.Json.Serialization\n{\n /// \n /// Determines the custom string value that should be used when serializing an enum member using JSON.\n /// \n /// \n /// This attribute is a temporary workaround for lack of System.Text.Json's support for custom enum member naming\n /// in versions prior to .NET 9. It works together with \n /// to provide customized string representations of enum values during JSON serialization and deserialization.\n /// \n [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\n internal sealed class JsonStringEnumMemberNameAttribute : Attribute\n {\n /// \n /// Creates new attribute instance with a specified enum member name.\n /// \n /// The name to apply to the current enum member when serialized to JSON.\n public JsonStringEnumMemberNameAttribute(string name)\n {\n Name = name;\n }\n\n /// \n /// Gets the custom JSON name of the enum member.\n /// \n public string Name { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// The server will respond with a containing the result of the tool invocation.\n/// See the schema for details.\n/// \npublic sealed class CallToolRequestParams : RequestParams\n{\n /// Gets or sets the name of the tool to invoke.\n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets optional arguments to pass to the tool when invoking it on the server.\n /// \n /// \n /// This dictionary contains the parameter values to be passed to the tool. Each key-value pair represents \n /// a parameter name and its corresponding argument value.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingMessageNotificationParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a log message is generated.\n/// \n/// \n/// \n/// Logging notifications allow servers to communicate diagnostic information to clients with varying severity levels.\n/// Clients can filter these messages based on the and properties.\n/// \n/// \n/// If no request has been sent from the client, the server may decide which\n/// messages to send automatically.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class LoggingMessageNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the severity of this log message.\n /// \n [JsonPropertyName(\"level\")]\n public LoggingLevel Level { get; init; }\n\n /// \n /// Gets or sets an optional name of the logger issuing this message.\n /// \n /// \n /// \n /// typically represents a category or component in the server's logging system.\n /// The logger name is useful for filtering and routing log messages in client applications.\n /// \n /// \n /// When implementing custom servers, choose clear, hierarchical logger names to help\n /// clients understand the source of log messages.\n /// \n /// \n [JsonPropertyName(\"logger\")]\n public string? Logger { get; init; }\n\n /// \n /// Gets or sets the data to be logged, such as a string message.\n /// \n [JsonPropertyName(\"data\")]\n public JsonElement? Data { get; init; }\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/AIFunctionMcpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerResource : McpServerResource\n{\n private readonly Regex? _uriParser;\n private readonly string[] _templateVariableNames = [];\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n object? target,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerResourceCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n // These parameters are the ones and only ones to include in the schema. The schema\n // won't be consumed by anyone other than this instance, which will use it to determine\n // which properties should show up in the URI template.\n if (pi.Name is not null && GetConverter(pi.ParameterType) is { } converter)\n {\n return new()\n {\n ExcludeFromSchema = false,\n BindParameter = (pi, args) =>\n {\n if (args.TryGetValue(pi.Name!, out var value))\n {\n return\n value is null || pi.ParameterType.IsInstanceOfType(value) ? value :\n value is string stringValue ? converter(stringValue) :\n throw new ArgumentException($\"Parameter '{pi.Name}' is of type '{pi.ParameterType}', but value '{value}' is of type '{value.GetType()}'.\");\n }\n\n return\n pi.HasDefaultValue ? pi.DefaultValue :\n throw new ArgumentException($\"Missing a value for the required parameter '{pi.Name}'.\");\n },\n };\n }\n\n return default;\n },\n };\n\n private static readonly ConcurrentDictionary> s_convertersCache = [];\n\n private static Func? GetConverter(Type type)\n {\n Type key = type;\n\n if (s_convertersCache.TryGetValue(key, out var converter))\n {\n return converter;\n }\n\n if (Nullable.GetUnderlyingType(type) is { } underlyingType)\n {\n // We will have already screened out null values by the time the converter is used,\n // so we can parse just the underlying type.\n type = underlyingType;\n }\n\n if (type == typeof(string) || type == typeof(object)) converter = static s => s;\n if (type == typeof(bool)) converter = static s => bool.Parse(s);\n if (type == typeof(char)) converter = static s => char.Parse(s);\n if (type == typeof(byte)) converter = static s => byte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(sbyte)) converter = static s => sbyte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ushort)) converter = static s => ushort.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(short)) converter = static s => short.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(uint)) converter = static s => uint.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(int)) converter = static s => int.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ulong)) converter = static s => ulong.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(long)) converter = static s => long.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(float)) converter = static s => float.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(double)) converter = static s => double.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(decimal)) converter = static s => decimal.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeSpan)) converter = static s => TimeSpan.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTime)) converter = static s => DateTime.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTimeOffset)) converter = static s => DateTimeOffset.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Uri)) converter = static s => new Uri(s, UriKind.RelativeOrAbsolute);\n if (type == typeof(Guid)) converter = static s => Guid.Parse(s);\n if (type == typeof(Version)) converter = static s => Version.Parse(s);\n#if NET\n if (type == typeof(Half)) converter = static s => Half.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Int128)) converter = static s => Int128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UInt128)) converter = static s => UInt128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(IntPtr)) converter = static s => IntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UIntPtr)) converter = static s => UIntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateOnly)) converter = static s => DateOnly.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeOnly)) converter = static s => TimeOnly.Parse(s, CultureInfo.InvariantCulture);\n#endif\n if (type.IsEnum) converter = s => Enum.Parse(type, s);\n\n if (type.GetCustomAttribute() is TypeConverterAttribute tca &&\n Type.GetType(tca.ConverterTypeName, throwOnError: false) is { } converterType &&\n Activator.CreateInstance(converterType) is TypeConverter typeConverter &&\n typeConverter.CanConvertFrom(typeof(string)))\n {\n converter = s => typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, s);\n }\n\n if (converter is not null)\n {\n s_convertersCache.TryAdd(key, converter);\n }\n\n return converter;\n }\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerResource Create(AIFunction function, McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(function);\n\n string name = options?.Name ?? function.Name;\n\n ResourceTemplate resource = new()\n {\n UriTemplate = options?.UriTemplate ?? DeriveUriTemplate(name, function),\n Name = name,\n Title = options?.Title,\n Description = options?.Description,\n MimeType = options?.MimeType ?? \"application/octet-stream\",\n };\n\n return new AIFunctionMcpServerResource(function, resource);\n }\n\n private static McpServerResourceCreateOptions DeriveOptions(MemberInfo member, McpServerResourceCreateOptions? options)\n {\n McpServerResourceCreateOptions newOptions = options?.Clone() ?? new();\n\n if (member.GetCustomAttribute() is { } resourceAttr)\n {\n newOptions.UriTemplate ??= resourceAttr.UriTemplate;\n newOptions.Name ??= resourceAttr.Name;\n newOptions.Title ??= resourceAttr.Title;\n newOptions.MimeType ??= resourceAttr.MimeType;\n }\n\n if (member.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Derives a name to be used as a resource name.\n private static string DeriveUriTemplate(string name, AIFunction function)\n {\n StringBuilder template = new();\n\n template.Append(\"resource://mcp/\").Append(Uri.EscapeDataString(name));\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n string separator = \"{?\";\n foreach (var prop in properties.EnumerateObject())\n {\n template.Append(separator).Append(prop.Name);\n separator = \",\";\n }\n\n if (separator == \",\")\n {\n template.Append('}');\n }\n }\n\n return template.ToString();\n }\n\n /// Gets the wrapped by this resource.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerResource(AIFunction function, ResourceTemplate resourceTemplate)\n {\n AIFunction = function;\n ProtocolResourceTemplate = resourceTemplate;\n ProtocolResource = resourceTemplate.AsResource();\n\n if (ProtocolResource is null)\n {\n _uriParser = UriTemplate.CreateParser(resourceTemplate.UriTemplate);\n _templateVariableNames = _uriParser.GetGroupNames().Where(n => n != \"0\").ToArray();\n }\n }\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// \n public override Resource? ProtocolResource { get; }\n\n /// \n public override async ValueTask ReadAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n Throw.IfNull(request.Params);\n Throw.IfNull(request.Params.Uri);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check to see if this URI template matches the request URI. If it doesn't, return null.\n // For templates, use the Regex to parse. For static resources, we can just compare the URIs.\n Match? match = null;\n if (_uriParser is not null)\n {\n match = _uriParser.Match(request.Params.Uri);\n if (!match.Success)\n {\n return null;\n }\n }\n else if (!UriTemplate.UriTemplateComparer.Instance.Equals(request.Params.Uri, ProtocolResource!.Uri))\n {\n return null;\n }\n\n // Build up the arguments for the AIFunction call, including all of the name/value pairs from the URI.\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n // For templates, populate the arguments from the URI template.\n if (match is not null)\n {\n foreach (string varName in _templateVariableNames)\n {\n if (match.Groups[varName] is { Success: true } value)\n {\n arguments[varName] = Uri.UnescapeDataString(value.Value);\n }\n }\n }\n\n // Invoke the function.\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n // And process the result.\n return result switch\n {\n ReadResourceResult readResourceResult => readResourceResult,\n\n ResourceContents content => new()\n {\n Contents = [content],\n },\n\n TextContent tc => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = tc.Text }],\n },\n\n DataContent dc => new()\n {\n Contents = [new BlobResourceContents { Uri = request.Params!.Uri, MimeType = dc.MediaType, Blob = dc.Base64Data.ToString() }],\n },\n\n string text => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = text }],\n },\n\n IEnumerable contents => new()\n {\n Contents = contents.ToList(),\n },\n\n IEnumerable aiContents => new()\n {\n Contents = aiContents.Select(\n ac => ac switch\n {\n TextContent tc => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = tc.Text\n },\n\n DataContent dc => new BlobResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = dc.MediaType,\n Blob = dc.Base64Data.ToString()\n },\n\n _ => throw new InvalidOperationException($\"Unsupported AIContent type '{ac.GetType()}' returned from resource function.\"),\n }).ToList(),\n },\n\n IEnumerable strings => new()\n {\n Contents = strings.Select(text => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = text\n }).ToList(),\n },\n\n null => throw new InvalidOperationException(\"Null result returned from resource function.\"),\n\n _ => throw new InvalidOperationException($\"Unsupported result type '{result.GetType()}' returned from resource function.\"),\n };\n }\n}"], ["/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/Protocol/ProgressToken.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a progress token, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct ProgressToken : IEquatable\n{\n /// The token, either a string or a boxed long or null.\n private readonly object? _token;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(string value)\n {\n Throw.IfNull(value);\n _token = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(long value)\n {\n // Box the long. Progress tokens are almost always strings in practice, so this should be rare.\n _token = value;\n }\n\n /// Gets the underlying object for this token.\n /// This will either be a , a boxed , or .\n public object? Token => _token;\n\n /// \n public override string? ToString() =>\n _token is string stringValue ? stringValue :\n _token is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n null;\n\n /// \n public bool Equals(ProgressToken other) => Equals(_token, other._token);\n\n /// \n public override bool Equals(object? obj) => obj is ProgressToken other && Equals(other);\n\n /// \n public override int GetHashCode() => _token?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(ProgressToken left, ProgressToken right) => left.Equals(right);\n\n /// \n public static bool operator !=(ProgressToken left, ProgressToken right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"progressToken must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressToken value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._token)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request sent to the server during connection establishment.\n/// \n/// \n/// \n/// The is sent by the server in response to an \n/// message from the client. It contains information about the server, its capabilities, and the protocol version\n/// that will be used for the session.\n/// \n/// \n/// After receiving this response, the client should send an \n/// notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeResult : Result\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the server will use for this session.\n /// \n /// \n /// \n /// This is the protocol version the server has agreed to use, which should match the client's \n /// requested version. If there's a mismatch, the client should throw an exception to prevent \n /// communication issues due to incompatible protocol versions.\n /// \n /// \n /// The protocol uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the server's capabilities.\n /// \n /// \n /// This defines the features the server supports, such as \"tools\", \"prompts\", \"resources\", or \"logging\", \n /// and other protocol-specific functionality.\n /// \n [JsonPropertyName(\"capabilities\")]\n public required ServerCapabilities Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the server implementation, including its name and version.\n /// \n /// \n /// This information identifies the server during the initialization handshake.\n /// Clients may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"serverInfo\")]\n public required Implementation ServerInfo { get; init; }\n\n /// \n /// Gets or sets optional instructions for using the server and its features.\n /// \n /// \n /// \n /// These instructions provide guidance to clients on how to effectively use the server's capabilities.\n /// They can include details about available tools, expected input formats, limitations,\n /// or any other information that helps clients interact with the server properly.\n /// \n /// \n /// Client applications often use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n /// \n [JsonPropertyName(\"instructions\")]\n public string? Instructions { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpErrorCode.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents standard JSON-RPC error codes as defined in the MCP specification.\n/// \npublic enum McpErrorCode\n{\n /// \n /// Indicates that the JSON received could not be parsed.\n /// \n /// \n /// This error occurs when the input contains malformed JSON or incorrect syntax.\n /// \n ParseError = -32700,\n\n /// \n /// Indicates that the JSON payload does not conform to the expected Request object structure.\n /// \n /// \n /// The request is considered invalid if it lacks required fields or fails to follow the JSON-RPC protocol.\n /// \n InvalidRequest = -32600,\n\n /// \n /// Indicates that the requested method does not exist or is not available on the server.\n /// \n /// \n /// This error is returned when the method name specified in the request cannot be found.\n /// \n MethodNotFound = -32601,\n\n /// \n /// Indicates that one or more parameters provided in the request are invalid.\n /// \n /// \n /// This error is returned when the parameters do not match the expected method signature or constraints.\n /// This includes cases where required parameters are missing or not understood, such as when a name for\n /// a tool or prompt is not recognized.\n /// \n InvalidParams = -32602,\n\n /// \n /// Indicates that an internal error occurred while processing the request.\n /// \n /// \n /// This error is used when the endpoint encounters an unexpected condition that prevents it from fulfilling the request.\n /// \n InternalError = -32603,\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable tool used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP tool for use in the server (as opposed\n/// to , which provides the protocol representation of a tool, and , which\n/// provides a client-side representation of a tool). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithToolsFromAssembly and WithTools. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \npublic abstract class McpServerTool : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerTool()\n {\n }\n\n /// Gets the protocol type for this instance.\n public abstract Tool ProtocolTool { get; }\n\n /// Invokes the .\n /// The request information resulting in the invocation of this tool.\n /// The to monitor for cancellation requests. The default is .\n /// The call response from invoking the tool.\n /// is .\n public abstract ValueTask InvokeAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerTool Create(\n MethodInfo method, \n object? target = null,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerTool Create(\n AIFunction function,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(function, options);\n\n /// \n public override string ToString() => ProtocolTool.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolTool.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring MCP servers via dependency injection.\n/// \npublic static partial class McpServerBuilderExtensions\n{\n #region WithTools\n private const string WithToolsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithTools)} and {nameof(WithToolsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithTools)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The tool type.\n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n public static IMcpServerBuilder WithTools<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TToolType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var toolMethod in typeof(TToolType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, static r => CreateTarget(r.Services, typeof(TToolType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable tools)\n {\n Throw.IfNull(builder);\n Throw.IfNull(tools);\n\n foreach (var tool in tools)\n {\n if (tool is not null)\n {\n builder.Services.AddSingleton(tool);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with -attributed methods to add as tools to the server.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable toolTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(toolTypes);\n\n foreach (var toolType in toolTypes)\n {\n if (toolType is not null)\n {\n foreach (var toolMethod in toolType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services , SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, r => CreateTarget(r.Services, toolType), new() { Services = services , SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as tools to the server.\n /// \n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the tool.\n /// \n /// \n /// Tools registered through this method can be discovered by clients using the list_tools request\n /// and invoked using the call_tool request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithToolsFromAssembly(this IMcpServerBuilder builder, Assembly? toolAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n toolAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithTools(\n from t in toolAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithPrompts\n private const string WithPromptsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithPrompts)} and {nameof(WithPromptsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithPrompts)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The prompt type.\n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n public static IMcpServerBuilder WithPrompts<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TPromptType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var promptMethod in typeof(TPromptType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, static r => CreateTarget(r.Services, typeof(TPromptType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable prompts)\n {\n Throw.IfNull(builder);\n Throw.IfNull(prompts);\n\n foreach (var prompt in prompts)\n {\n if (prompt is not null)\n {\n builder.Services.AddSingleton(prompt);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as prompts to the server.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable promptTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(promptTypes);\n\n foreach (var promptType in promptTypes)\n {\n if (promptType is not null)\n {\n foreach (var promptMethod in promptType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, r => CreateTarget(r.Services, promptType), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as prompts to the server.\n /// \n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the prompt.\n /// \n /// \n /// Prompts registered through this method can be discovered by clients using the list_prompts request\n /// and invoked using the call_prompt request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPromptsFromAssembly(this IMcpServerBuilder builder, Assembly? promptAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n promptAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithPrompts(\n from t in promptAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithResources\n private const string WithResourcesRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithResources)} and {nameof(WithResourcesFromAssembly)} methods require dynamic lookup of member metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithResources)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The resource type.\n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the members are attributed as , and adds an \n /// instance for each. For instance members, an instance will be constructed for each invocation of the resource.\n /// \n public static IMcpServerBuilder WithResources<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TResourceType>(\n this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n foreach (var resourceTemplateMethod in typeof(TResourceType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, static r => CreateTarget(r.Services, typeof(TResourceType)), new() { Services = services })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplates)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplates);\n\n foreach (var resourceTemplate in resourceTemplates)\n {\n if (resourceTemplate is not null)\n {\n builder.Services.AddSingleton(resourceTemplate);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as resources to the server.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the resource.\n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplateTypes)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplateTypes);\n\n foreach (var resourceTemplateType in resourceTemplateTypes)\n {\n if (resourceTemplateType is not null)\n {\n foreach (var resourceTemplateMethod in resourceTemplateType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, r => CreateTarget(r.Services, resourceTemplateType), new() { Services = services })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as resources to the server.\n /// \n /// The builder instance.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all members within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance members. For instance members, a new instance\n /// of the containing class will be constructed for each invocation of the resource.\n /// \n /// \n /// Resource templates registered through this method can be discovered by clients using the list_resourceTemplates request\n /// and invoked using the read_resource request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResourcesFromAssembly(this IMcpServerBuilder builder, Assembly? resourceAssembly = null)\n {\n Throw.IfNull(builder);\n\n resourceAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithResources(\n from t in resourceAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t);\n }\n #endregion\n\n #region Handlers\n /// \n /// Configures a handler for listing resource templates available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource template list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is responsible for providing clients with information about available resource templates\n /// that can be used to construct resource URIs.\n /// \n /// \n /// Resource templates describe the structure of resource URIs that the server can handle. They include\n /// URI templates (according to RFC 6570) that clients can use to construct valid resource URIs.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// resource system where templates define the URI patterns and the read handler provides the actual content.\n /// \n /// \n public static IMcpServerBuilder WithListResourceTemplatesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourceTemplatesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list tools requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available tools. It should return all tools\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// tool collections.\n /// \n /// \n /// When tools are also defined using collection, both sets of tools\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// tools and dynamically generated tools.\n /// \n /// \n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and \n /// executes them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListToolsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListToolsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for calling tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes tool calls.\n /// The builder provided in .\n /// is .\n /// \n /// The call tool handler is responsible for executing custom tools and returning their results to clients.\n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and this handler executes them.\n /// \n public static IMcpServerBuilder WithCallToolHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CallToolHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing prompts available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list prompts requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available prompts. It should return all prompts\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// prompt collections.\n /// \n /// \n /// When prompts are also defined using collection, both sets of prompts\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// prompts and dynamically generated prompts.\n /// \n /// \n /// This method is typically paired with to provide a complete prompts implementation,\n /// where advertises available prompts and \n /// produces them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListPromptsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListPromptsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for getting a prompt available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes prompt requests.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithGetPromptHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.GetPromptHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing resources available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where this handler advertises available resources and the read handler provides their content when requested.\n /// \n /// \n public static IMcpServerBuilder WithListResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for reading a resource available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource read requests.\n /// The builder provided in .\n /// is .\n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where the list handler advertises available resources and the read handler provides their content when requested.\n /// \n public static IMcpServerBuilder WithReadResourceHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ReadResourceHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for auto-completion suggestions for prompt arguments or resource references available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes completion requests.\n /// The builder provided in .\n /// is .\n /// \n /// The completion handler is invoked when clients request suggestions for argument values.\n /// This enables auto-complete functionality for both prompt arguments and resource references.\n /// \n public static IMcpServerBuilder WithCompleteHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CompleteHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource subscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource subscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The subscribe handler is responsible for registering client interest in specific resources. When a resource\n /// changes, the server can notify all subscribed clients about the change.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. Resource subscriptions allow clients to maintain up-to-date information without\n /// needing to poll resources constantly.\n /// \n /// \n /// After registering a subscription, it's the server's responsibility to track which client is subscribed to which\n /// resources and to send appropriate notifications through the connection when resources change.\n /// \n /// \n public static IMcpServerBuilder WithSubscribeToResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SubscribeToResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource unsubscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource unsubscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The unsubscribe handler is responsible for removing client interest in specific resources. When a client\n /// no longer needs to receive notifications about resource changes, it can send an unsubscribe request.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. The unsubscribe operation is idempotent, meaning it can be called multiple\n /// times for the same resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// After removing a subscription, the server should stop sending notifications to the client about changes\n /// to the specified resource.\n /// \n /// \n public static IMcpServerBuilder WithUnsubscribeFromResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.UnsubscribeFromResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for processing logging level change requests from clients.\n /// \n /// The server builder instance.\n /// The handler that processes requests to change the logging level.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// When a client sends a logging/setLevel request, this handler will be invoked to process\n /// the requested level change. The server typically adjusts its internal logging level threshold\n /// and may begin sending log messages at or above the specified level to the client.\n /// \n /// \n /// Regardless of whether a handler is provided, an should itself handle\n /// such notifications by updating its property to return the\n /// most recently set level.\n /// \n /// \n public static IMcpServerBuilder WithSetLoggingLevelHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SetLoggingLevelHandler = handler);\n return builder;\n }\n #endregion\n\n #region Transports\n /// \n /// Adds a server transport that uses standard input (stdin) and standard output (stdout) for communication.\n /// \n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method configures the server to communicate using the standard input and output streams,\n /// which is commonly used when the Model Context Protocol server is launched locally by a client process.\n /// \n /// \n /// When using this transport, the server runs as a single-session service that exits when the\n /// stdin stream is closed. This makes it suitable for scenarios where the server should terminate\n /// when the parent process disconnects.\n /// \n /// \n /// is .\n public static IMcpServerBuilder WithStdioServerTransport(this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(sp =>\n {\n var serverOptions = sp.GetRequiredService>();\n var loggerFactory = sp.GetService();\n return new StdioServerTransport(serverOptions.Value, loggerFactory);\n });\n\n return builder;\n }\n\n /// \n /// Adds a server transport that uses the specified input and output streams for communication.\n /// \n /// The builder instance.\n /// The input to use as standard input.\n /// The output to use as standard output.\n /// The builder provided in .\n /// is .\n /// is .\n /// is .\n public static IMcpServerBuilder WithStreamServerTransport(\n this IMcpServerBuilder builder,\n Stream inputStream,\n Stream outputStream)\n {\n Throw.IfNull(builder);\n Throw.IfNull(inputStream);\n Throw.IfNull(outputStream);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(new StreamServerTransport(inputStream, outputStream));\n\n return builder;\n }\n\n private static void AddSingleSessionServerDependencies(IServiceCollection services)\n {\n services.AddHostedService();\n services.TryAddSingleton(services =>\n {\n ITransport serverTransport = services.GetRequiredService();\n IOptions options = services.GetRequiredService>();\n ILoggerFactory? loggerFactory = services.GetService();\n return McpServerFactory.Create(serverTransport, options.Value, loggerFactory, services);\n });\n }\n #endregion\n\n #region Helpers\n /// Creates an instance of the target object.\n private static object CreateTarget(\n IServiceProvider? services,\n [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) =>\n services is not null ? ActivatorUtilities.CreateInstance(services, type) :\n Activator.CreateInstance(type)!;\n #endregion\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DestinationBoundMcpServer.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class DestinationBoundMcpServer(McpServer server, ITransport? transport) : IMcpServer\n{\n public string EndpointName => server.EndpointName;\n public string? SessionId => transport?.SessionId ?? server.SessionId;\n public ClientCapabilities? ClientCapabilities => server.ClientCapabilities;\n public Implementation? ClientInfo => server.ClientInfo;\n public McpServerOptions ServerOptions => server.ServerOptions;\n public IServiceProvider? Services => server.Services;\n public LoggingLevel? LoggingLevel => server.LoggingLevel;\n\n public ValueTask DisposeAsync() => server.DisposeAsync();\n\n public IAsyncDisposable RegisterNotificationHandler(string method, Func handler) => server.RegisterNotificationHandler(method, handler);\n\n // This will throw because the server must already be running for this class to be constructed, but it should give us a good Exception message.\n public Task RunAsync(CancellationToken cancellationToken) => server.RunAsync(cancellationToken);\n\n public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Debug.Assert(message.RelatedTransport is null);\n message.RelatedTransport = transport;\n return server.SendMessageAsync(message, cancellationToken);\n }\n\n public Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)\n {\n Debug.Assert(request.RelatedTransport is null);\n request.RelatedTransport = transport;\n return server.SendRequestAsync(request, cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable prompt used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP prompt for use in the server (as opposed\n/// to , which provides the protocol representation of a prompt, and , which\n/// provides a client-side representation of a prompt). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithPromptsFromAssembly and WithPrompts. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to \n/// rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerPrompt : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerPrompt()\n {\n }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolPrompt property represents the underlying prompt definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the prompt's name,\n /// description, and acceptable arguments.\n /// \n public abstract Prompt ProtocolPrompt { get; }\n\n /// \n /// Gets the prompt, rendering it with the provided request parameters and returning the prompt result.\n /// \n /// \n /// The request context containing information about the prompt invocation, including any arguments\n /// passed to the prompt. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the prompt content and messages.\n /// \n /// is .\n /// The prompt implementation returns or an unsupported result type.\n public abstract ValueTask GetAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerPrompt Create(\n MethodInfo method, \n object? target = null,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerPrompt Create(\n AIFunction function,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(function, options);\n\n /// \n public override string ToString() => ProtocolPrompt.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolPrompt.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request sent by a client to a server during the protocol handshake.\n/// \n/// \n/// \n/// The is the first message sent in the Model Context Protocol\n/// communication flow. It establishes the connection between client and server, negotiates the protocol\n/// version, and declares the client's capabilities.\n/// \n/// \n/// After sending this request, the client should wait for an response\n/// before sending an notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the client wants to use.\n /// \n /// \n /// \n /// Protocol version is specified using a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// The client and server must agree on a protocol version to communicate successfully.\n /// \n /// \n /// During initialization, the server will check if it supports this requested version. If there's a \n /// mismatch, the server will reject the connection with a version mismatch error.\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the client's capabilities.\n /// \n /// \n /// Capabilities define the features the client supports, such as \"sampling\" or \"roots\".\n /// \n [JsonPropertyName(\"capabilities\")]\n public ClientCapabilities? Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the client implementation, including its name and version.\n /// \n /// \n /// This information is required during the initialization handshake to identify the client.\n /// Servers may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"clientInfo\")]\n public required Implementation ClientInfo { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as tools in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as tools that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to when the tool is invoked rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided when the tool is invoked rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerToolAttribute : Attribute\n{\n // Defaults based on the spec\n private const bool DestructiveDefault = true;\n private const bool IdempotentDefault = false;\n private const bool OpenWorldDefault = true;\n private const bool ReadOnlyDefault = false;\n\n // Nullable backing fields so we can distinguish\n internal bool? _destructive;\n internal bool? _idempotent;\n internal bool? _openWorld;\n internal bool? _readOnly;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerToolAttribute()\n {\n }\n\n /// Gets the name of the tool.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Destructive \n {\n get => _destructive ?? DestructiveDefault; \n set => _destructive = value; \n }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Idempotent \n {\n get => _idempotent ?? IdempotentDefault;\n set => _idempotent = value; \n }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool OpenWorld\n {\n get => _openWorld ?? OpenWorldDefault; \n set => _openWorld = value; \n }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool ReadOnly \n {\n get => _readOnly ?? ReadOnlyDefault; \n set => _readOnly = value; \n }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a prompt provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting prompt.\n/// See the schema for details.\n/// \npublic sealed class GetPromptRequestParams : RequestParams\n{\n /// \n /// Gets or sets the name of the prompt.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets arguments to use for templating the prompt when retrieving it from the server.\n /// \n /// \n /// Typically, these arguments are used to replace placeholders in prompt templates. The keys in this dictionary\n /// should match the names defined in the prompt's list. However, the server may\n /// choose to use these arguments in any way it deems appropriate to generate the prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientPrompt.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named prompt that can be retrieved from an MCP server and invoked with arguments.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a prompt defined on an MCP server. It allows\n/// retrieving the prompt's content by sending a request to the server with optional arguments.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \n/// Each prompt has a name and optionally a description, and it can be invoked with arguments\n/// to produce customized prompt content from the server.\n/// \n/// \npublic sealed class McpClientPrompt\n{\n private readonly IMcpClient _client;\n\n internal McpClientPrompt(IMcpClient client, Prompt prompt)\n {\n _client = client;\n ProtocolPrompt = prompt;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the prompt,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Prompt ProtocolPrompt { get; }\n\n /// Gets the name of the prompt.\n public string Name => ProtocolPrompt.Name;\n\n /// Gets the title of the prompt.\n public string? Title => ProtocolPrompt.Title;\n\n /// Gets a description of the prompt.\n public string? Description => ProtocolPrompt.Description;\n\n /// \n /// Gets this prompt's content by sending a request to the server with optional arguments.\n /// \n /// Optional arguments to pass to the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to execute this prompt with the provided arguments.\n /// The server will process the request and return a result containing messages or other content.\n /// \n /// \n /// This is a convenience method that internally calls \n /// with this prompt's name and arguments.\n /// \n /// \n public async ValueTask GetAsync(\n IEnumerable>? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n IReadOnlyDictionary? argDict =\n arguments as IReadOnlyDictionary ??\n arguments?.ToDictionary();\n\n return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, serializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ClientCapabilities.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a client may support.\n/// \n/// \n/// \n/// Capabilities define the features and functionality that a client can handle when communicating with an MCP server.\n/// These are advertised to the server during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ClientCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the client supports.\n /// \n /// \n /// \n /// The dictionary allows clients to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Servers should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets the client's roots capability, which are entry points for resource navigation.\n /// \n /// \n /// \n /// When is non-, the client indicates that it can respond to \n /// server requests for listing root URIs. Root URIs serve as entry points for resource navigation in the protocol.\n /// \n /// \n /// The server can use to request the list of\n /// available roots from the client, which will trigger the client's .\n /// \n /// \n [JsonPropertyName(\"roots\")]\n public RootsCapability? Roots { get; set; }\n\n /// \n /// Gets or sets the client's sampling capability, which indicates whether the client \n /// supports issuing requests to an LLM on behalf of the server.\n /// \n [JsonPropertyName(\"sampling\")]\n public SamplingCapability? Sampling { get; set; }\n\n /// \n /// Gets or sets the client's elicitation capability, which indicates whether the client \n /// supports elicitation of additional information from the user on behalf of the server.\n /// \n [JsonPropertyName(\"elicitation\")]\n public ElicitationCapability? Elicitation { get; set; }\n\n /// Gets or sets notification handlers to register with the client.\n /// \n /// \n /// When constructed, the client will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The client will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the client to respond to server-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the client for the lifetime of the client.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ServerCapabilities.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a server may support.\n/// \n/// \n/// \n/// Server capabilities define the features and functionality available when clients connect.\n/// These capabilities are advertised to clients during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ServerCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the server supports.\n /// \n /// \n /// \n /// The dictionary allows servers to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Clients should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets a server's logging capability, supporting sending log messages to the client.\n /// \n [JsonPropertyName(\"logging\")]\n public LoggingCapability? Logging { get; set; }\n\n /// \n /// Gets or sets a server's prompts capability for serving predefined prompt templates that clients can discover and use.\n /// \n [JsonPropertyName(\"prompts\")]\n public PromptsCapability? Prompts { get; set; }\n\n /// \n /// Gets or sets a server's resources capability for serving predefined resources that clients can discover and use.\n /// \n [JsonPropertyName(\"resources\")]\n public ResourcesCapability? Resources { get; set; }\n\n /// \n /// Gets or sets a server's tools capability for listing tools that a client is able to invoke.\n /// \n [JsonPropertyName(\"tools\")]\n public ToolsCapability? Tools { get; set; }\n\n /// \n /// Gets or sets a server's completions capability for supporting argument auto-completion suggestions.\n /// \n [JsonPropertyName(\"completions\")]\n public CompletionsCapability? Completions { get; set; }\n\n /// Gets or sets notification handlers to register with the server.\n /// \n /// \n /// When constructed, the server will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The server will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the server to respond to client-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the server for the lifetime of the server.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of tools created with\n/// . They provide control over naming, description,\n/// tool properties, and dependency injection integration.\n/// \n/// \n/// When creating tools programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerToolCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisfied from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Destructive { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Idempotent { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? OpenWorld { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? ReadOnly { get; set; }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerToolCreateOptions Clone() =>\n new McpServerToolCreateOptions\n {\n Services = Services,\n Name = Name,\n Description = Description,\n Title = Title,\n Destructive = Destructive,\n Idempotent = Idempotent,\n OpenWorld = OpenWorld,\n ReadOnly = ReadOnly,\n UseStructuredContent = UseStructuredContent,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/RequestContext.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Provides a context container that provides access to the client request parameters and resources for the request.\n/// \n/// Type of the request parameters specific to each MCP operation.\n/// \n/// The encapsulates all contextual information for handling an MCP request.\n/// This type is typically received as a parameter in handler delegates registered with IMcpServerBuilder,\n/// and may be injected as parameters into s.\n/// \npublic sealed class RequestContext\n{\n /// The server with which this instance is associated.\n private IMcpServer _server;\n\n /// \n /// Initializes a new instance of the class with the specified server.\n /// \n /// The server with which this instance is associated.\n public RequestContext(IMcpServer server)\n {\n Throw.IfNull(server);\n\n _server = server;\n Services = server.Services;\n }\n\n /// Gets or sets the server with which this instance is associated.\n public IMcpServer Server \n {\n get => _server;\n set\n {\n Throw.IfNull(value);\n _server = value;\n }\n }\n\n /// Gets or sets the services associated with this request.\n /// \n /// This may not be the same instance stored in \n /// if was true, in which case this\n /// might be a scoped derived from the server's\n /// .\n /// \n public IServiceProvider? Services { get; set; }\n\n /// Gets or sets the parameters associated with this request.\n public TParams? Params { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CancelledNotificationParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification indicating that a request has been cancelled by the client,\n/// and that any associated processing should cease immediately.\n/// \n/// \n/// This class is typically used in conjunction with the \n/// method identifier. When a client sends this notification, the server should attempt to\n/// cancel any ongoing operations associated with the specified request ID.\n/// \npublic sealed class CancelledNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the ID of the request to cancel.\n /// \n /// \n /// This must match the ID of an in-flight request that the sender wishes to cancel.\n /// \n [JsonPropertyName(\"requestId\")]\n public RequestId RequestId { get; set; }\n\n /// \n /// Gets or sets an optional string describing the reason for the cancellation request.\n /// \n [JsonPropertyName(\"reason\")]\n public string? Reason { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/McpEndpointRouteBuilderExtensions.cs", "using Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Metadata;\nusing Microsoft.AspNetCore.Routing;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.AspNetCore.Builder;\n\n/// \n/// Provides extension methods for to add MCP endpoints.\n/// \npublic static class McpEndpointRouteBuilderExtensions\n{\n /// \n /// Sets up endpoints for handling MCP Streamable HTTP transport.\n /// See the 2025-06-18 protocol specification for details about the Streamable HTTP transport.\n /// Also maps legacy SSE endpoints for backward compatibility at the path \"/sse\" and \"/message\". the 2024-11-05 protocol specification for details about the HTTP with SSE transport.\n /// \n /// The web application to attach MCP HTTP endpoints.\n /// The route pattern prefix to map to.\n /// Returns a builder for configuring additional endpoint conventions like authorization policies.\n public static IEndpointConventionBuilder MapMcp(this IEndpointRouteBuilder endpoints, [StringSyntax(\"Route\")] string pattern = \"\")\n {\n var streamableHttpHandler = endpoints.ServiceProvider.GetService() ??\n throw new InvalidOperationException(\"You must call WithHttpTransport(). Unable to find required services. Call builder.Services.AddMcpServer().WithHttpTransport() in application startup code.\");\n\n var mcpGroup = endpoints.MapGroup(pattern);\n var streamableHttpGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP Streamable HTTP | {b.DisplayName}\")\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status404NotFound, typeof(JsonRpcError), contentTypes: [\"application/json\"]));\n\n streamableHttpGroup.MapPost(\"\", streamableHttpHandler.HandlePostRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n\n if (!streamableHttpHandler.HttpServerTransportOptions.Stateless)\n {\n // The GET and DELETE endpoints are not mapped in Stateless mode since there's no way to send unsolicited messages\n // for the GET to handle, and there is no server-side state for the DELETE to clean up.\n streamableHttpGroup.MapGet(\"\", streamableHttpHandler.HandleGetRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n streamableHttpGroup.MapDelete(\"\", streamableHttpHandler.HandleDeleteRequestAsync);\n\n // Map legacy HTTP with SSE endpoints only if not in Stateless mode, because we cannot guarantee the /message requests\n // will be handled by the same process as the /sse request.\n var sseHandler = endpoints.ServiceProvider.GetRequiredService();\n var sseGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP HTTP with SSE | {b.DisplayName}\");\n\n sseGroup.MapGet(\"/sse\", sseHandler.HandleSseRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n sseGroup.MapPost(\"/message\", sseHandler.HandleMessageRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n }\n\n return mcpGroup;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of prompts created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating prompts programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerPromptCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerPromptCreateOptions Clone() =>\n new McpServerPromptCreateOptions\n {\n Services = Services,\n Name = Name,\n Title = Title,\n Description = Description,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a from the server.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageResult : Result\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the name of the model that generated the message.\n /// \n /// \n /// \n /// This should contain the specific model identifier such as \"claude-3-5-sonnet-20241022\" or \"o3-mini\".\n /// \n /// \n /// This property allows the server to know which model was used to generate the response,\n /// enabling appropriate handling based on the model's capabilities and characteristics.\n /// \n /// \n [JsonPropertyName(\"model\")]\n public required string Model { get; init; }\n\n /// \n /// Gets or sets the reason why message generation (sampling) stopped, if known.\n /// \n /// \n /// Common values include:\n /// \n /// endTurnThe model naturally completed its response.\n /// maxTokensThe response was truncated due to reaching token limits.\n /// stopSequenceA specific stop sequence was encountered during generation.\n /// \n /// \n [JsonPropertyName(\"stopReason\")]\n public string? StopReason { get; init; }\n\n /// \n /// Gets or sets the role of the user who generated the message.\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerHandlers.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a container for handlers used in the creation of an MCP server.\n/// \n/// \n/// \n/// This class provides a centralized collection of delegates that implement various capabilities of the Model Context Protocol.\n/// Each handler in this class corresponds to a specific endpoint in the Model Context Protocol and\n/// is responsible for processing a particular type of request. The handlers are used to customize\n/// the behavior of the MCP server by providing implementations for the various protocol operations.\n/// \n/// \n/// Handlers can be configured individually using the extension methods in \n/// such as and\n/// .\n/// \n/// \n/// When a client sends a request to the server, the appropriate handler is invoked to process the\n/// request and produce a response according to the protocol specification. Which handler is selected\n/// is done based on an ordinal, case-sensitive string comparison.\n/// \n/// \npublic sealed class McpServerHandlers\n{\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// \n /// \n /// This handler works alongside any tools defined in the collection.\n /// Tools from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the collection.\n /// The handler should implement logic to execute the requested tool and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available prompts when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more prompts.\n /// \n /// \n /// This handler works alongside any prompts defined in the collection.\n /// Prompts from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt that isn't found in the collection.\n /// The handler should implement logic to fetch or generate the requested prompt and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resource templates when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resource templates.\n /// \n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resources when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resources.\n /// \n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests the content of a specific resource identified by its URI.\n /// The handler should implement logic to locate and retrieve the requested resource.\n /// \n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler processes auto-completion requests, returning a list of suggestions based on the \n /// reference type and current argument value.\n /// \n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to receive notifications about changes to specific resources or resource patterns.\n /// The handler should implement logic to register the client's interest in the specified resources\n /// and set up the necessary infrastructure to send notifications when those resources change.\n /// \n /// \n /// After a successful subscription, the server should send resource change notifications to the client\n /// whenever a relevant resource is created, updated, or deleted.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to stop receiving notifications about previously subscribed resources.\n /// The handler should implement logic to remove the client's subscriptions to the specified resources\n /// and clean up any associated resources.\n /// \n /// \n /// After a successful unsubscription, the server should no longer send resource change notifications\n /// to the client for the specified resources.\n /// \n /// \n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler processes requests from clients. When set, it enables\n /// clients to control which log messages they receive by specifying a minimum severity threshold.\n /// \n /// \n /// After handling a level change request, the server typically begins sending log messages\n /// at or above the specified level to the client as notifications/message notifications.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n\n /// \n /// Overwrite any handlers in McpServerOptions with non-null handlers from this instance.\n /// \n /// \n /// \n internal void OverwriteWithSetHandlers(McpServerOptions options)\n {\n PromptsCapability? promptsCapability = options.Capabilities?.Prompts;\n if (ListPromptsHandler is not null || GetPromptHandler is not null)\n {\n promptsCapability ??= new();\n promptsCapability.ListPromptsHandler = ListPromptsHandler ?? promptsCapability.ListPromptsHandler;\n promptsCapability.GetPromptHandler = GetPromptHandler ?? promptsCapability.GetPromptHandler;\n }\n\n ResourcesCapability? resourcesCapability = options.Capabilities?.Resources;\n if (ListResourcesHandler is not null ||\n ReadResourceHandler is not null)\n {\n resourcesCapability ??= new();\n resourcesCapability.ListResourceTemplatesHandler = ListResourceTemplatesHandler ?? resourcesCapability.ListResourceTemplatesHandler;\n resourcesCapability.ListResourcesHandler = ListResourcesHandler ?? resourcesCapability.ListResourcesHandler;\n resourcesCapability.ReadResourceHandler = ReadResourceHandler ?? resourcesCapability.ReadResourceHandler;\n\n if (SubscribeToResourcesHandler is not null || UnsubscribeFromResourcesHandler is not null)\n {\n resourcesCapability.SubscribeToResourcesHandler = SubscribeToResourcesHandler ?? resourcesCapability.SubscribeToResourcesHandler;\n resourcesCapability.UnsubscribeFromResourcesHandler = UnsubscribeFromResourcesHandler ?? resourcesCapability.UnsubscribeFromResourcesHandler;\n resourcesCapability.Subscribe = true;\n }\n }\n\n ToolsCapability? toolsCapability = options.Capabilities?.Tools;\n if (ListToolsHandler is not null || CallToolHandler is not null)\n {\n toolsCapability ??= new();\n toolsCapability.ListToolsHandler = ListToolsHandler ?? toolsCapability.ListToolsHandler;\n toolsCapability.CallToolHandler = CallToolHandler ?? toolsCapability.CallToolHandler;\n }\n\n LoggingCapability? loggingCapability = options.Capabilities?.Logging;\n if (SetLoggingLevelHandler is not null)\n {\n loggingCapability ??= new();\n loggingCapability.SetLoggingLevelHandler = SetLoggingLevelHandler;\n }\n\n CompletionsCapability? completionsCapability = options.Capabilities?.Completions;\n if (CompleteHandler is not null)\n {\n completionsCapability ??= new();\n completionsCapability.CompleteHandler = CompleteHandler;\n }\n\n options.Capabilities ??= new();\n options.Capabilities.Prompts = promptsCapability;\n options.Capabilities.Resources = resourcesCapability;\n options.Capabilities.Tools = toolsCapability;\n options.Capabilities.Logging = loggingCapability;\n options.Capabilities.Completions = completionsCapability;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationHandler.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Authentication;\nusing System.Text.Encodings.Web;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Authentication handler for MCP protocol that adds resource metadata to challenge responses\n/// and handles resource metadata endpoint requests.\n/// \npublic class McpAuthenticationHandler : AuthenticationHandler, IAuthenticationRequestHandler\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationHandler(\n IOptionsMonitor options,\n ILoggerFactory logger,\n UrlEncoder encoder)\n : base(options, logger, encoder)\n {\n }\n\n /// \n public async Task HandleRequestAsync()\n {\n // Check if the request is for the resource metadata endpoint\n string requestPath = Request.Path.Value ?? string.Empty;\n\n string expectedMetadataPath = Options.ResourceMetadataUri?.ToString() ?? string.Empty;\n if (Options.ResourceMetadataUri != null && !Options.ResourceMetadataUri.IsAbsoluteUri)\n {\n // For relative URIs, it's just the path component.\n expectedMetadataPath = Options.ResourceMetadataUri.OriginalString;\n }\n\n // If the path doesn't match, let the request continue through the pipeline\n if (!string.Equals(requestPath, expectedMetadataPath, StringComparison.OrdinalIgnoreCase))\n {\n return false;\n }\n\n return await HandleResourceMetadataRequestAsync();\n }\n\n /// \n /// Gets the base URL from the current request, including scheme, host, and path base.\n /// \n private string GetBaseUrl() => $\"{Request.Scheme}://{Request.Host}{Request.PathBase}\";\n\n /// \n /// Gets the absolute URI for the resource metadata endpoint.\n /// \n private string GetAbsoluteResourceMetadataUri()\n {\n var resourceMetadataUri = Options.ResourceMetadataUri;\n\n string currentPath = resourceMetadataUri?.ToString() ?? string.Empty;\n\n if (resourceMetadataUri != null && resourceMetadataUri.IsAbsoluteUri)\n {\n return currentPath;\n }\n\n // For relative URIs, combine with the base URL\n string baseUrl = GetBaseUrl();\n string relativePath = resourceMetadataUri?.OriginalString.TrimStart('/') ?? string.Empty;\n\n if (!Uri.TryCreate($\"{baseUrl.TrimEnd('/')}/{relativePath}\", UriKind.Absolute, out var absoluteUri))\n {\n throw new InvalidOperationException($\"Could not create absolute URI for resource metadata. Base URL: {baseUrl}, Relative Path: {relativePath}\");\n }\n\n return absoluteUri.ToString();\n }\n\n private async Task HandleResourceMetadataRequestAsync()\n {\n var resourceMetadata = Options.ResourceMetadata;\n\n if (Options.Events.OnResourceMetadataRequest is not null)\n {\n var context = new ResourceMetadataRequestContext(Request.HttpContext, Scheme, Options)\n {\n ResourceMetadata = CloneResourceMetadata(resourceMetadata),\n };\n\n await Options.Events.OnResourceMetadataRequest(context);\n\n if (context.Result is not null)\n {\n if (context.Result.Handled)\n {\n return true;\n }\n else if (context.Result.Skipped)\n {\n return false;\n }\n else if (context.Result.Failure is not null)\n {\n throw new AuthenticationFailureException(\"An error occurred from the OnResourceMetadataRequest event.\", context.Result.Failure);\n }\n }\n\n resourceMetadata = context.ResourceMetadata;\n }\n\n if (resourceMetadata == null)\n {\n throw new InvalidOperationException(\n \"ResourceMetadata has not been configured. Please set McpAuthenticationOptions.ResourceMetadata or ensure context.ResourceMetadata is set inside McpAuthenticationOptions.Events.OnResourceMetadataRequest.\"\n );\n }\n\n await Results.Json(resourceMetadata, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ProtectedResourceMetadata))).ExecuteAsync(Context);\n return true;\n }\n\n /// \n // If no forwarding is configured, this handler doesn't perform authentication\n protected override async Task HandleAuthenticateAsync() => AuthenticateResult.NoResult();\n\n /// \n protected override Task HandleChallengeAsync(AuthenticationProperties properties)\n {\n // Get the absolute URI for the resource metadata\n string rawPrmDocumentUri = GetAbsoluteResourceMetadataUri();\n\n properties ??= new AuthenticationProperties();\n\n // Store the resource_metadata in properties in case other handlers need it\n properties.Items[\"resource_metadata\"] = rawPrmDocumentUri;\n\n // Add the WWW-Authenticate header with Bearer scheme and resource metadata\n string headerValue = $\"Bearer realm=\\\"{Scheme.Name}\\\", resource_metadata=\\\"{rawPrmDocumentUri}\\\"\";\n Response.Headers.Append(\"WWW-Authenticate\", headerValue);\n\n return base.HandleChallengeAsync(properties);\n }\n\n internal static ProtectedResourceMetadata? CloneResourceMetadata(ProtectedResourceMetadata? resourceMetadata)\n {\n if (resourceMetadata is null)\n {\n return null;\n }\n\n return new ProtectedResourceMetadata\n {\n Resource = resourceMetadata.Resource,\n AuthorizationServers = [.. resourceMetadata.AuthorizationServers],\n BearerMethodsSupported = [.. resourceMetadata.BearerMethodsSupported],\n ScopesSupported = [.. resourceMetadata.ScopesSupported],\n JwksUri = resourceMetadata.JwksUri,\n ResourceSigningAlgValuesSupported = resourceMetadata.ResourceSigningAlgValuesSupported is not null ? [.. resourceMetadata.ResourceSigningAlgValuesSupported] : null,\n ResourceName = resourceMetadata.ResourceName,\n ResourceDocumentation = resourceMetadata.ResourceDocumentation,\n ResourcePolicyUri = resourceMetadata.ResourcePolicyUri,\n ResourceTosUri = resourceMetadata.ResourceTosUri,\n TlsClientCertificateBoundAccessTokens = resourceMetadata.TlsClientCertificateBoundAccessTokens,\n AuthorizationDetailsTypesSupported = resourceMetadata.AuthorizationDetailsTypesSupported is not null ? [.. resourceMetadata.AuthorizationDetailsTypesSupported] : null,\n DpopSigningAlgValuesSupported = resourceMetadata.DpopSigningAlgValuesSupported is not null ? [.. resourceMetadata.DpopSigningAlgValuesSupported] : null,\n DpopBoundAccessTokensRequired = resourceMetadata.DpopBoundAccessTokensRequired\n };\n }\n\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingMessage.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued to or received from an LLM API within the Model Context Protocol.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be text or images.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent prompts or queries for LLM sampling. They form the core data structure for text generation requests\n/// within the Model Context Protocol.\n/// \n/// \n/// While similar to , the is focused on direct LLM sampling\n/// operations rather than the enhanced resource embedding capabilities provided by .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class SamplingMessage\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the role of the message sender, indicating whether it's from a \"user\" or an \"assistant\".\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a request from the server,\n/// containing available roots.\n/// \n/// \n/// \n/// This result is returned when a server sends a request to discover \n/// available roots on the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListRootsResult : Result\n{\n /// \n /// Gets or sets the list of root URIs provided by the client.\n /// \n /// \n /// This collection contains all available root URIs and their associated metadata.\n /// Each root serves as an entry point for resource navigation in the Model Context Protocol.\n /// \n [JsonPropertyName(\"roots\")]\n public required IReadOnlyList Roots { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable resource used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP resource for use in the server (as opposed\n/// to or , which provide the protocol representations of a resource). Instances of \n/// can be added into a to be picked up automatically when\n/// is used to create an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithResourcesFromAssembly and\n/// . The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the URI received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// is used to represent both direct resources (e.g. \"resource://example\") and templated\n/// resources (e.g. \"resource://example/{id}\").\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerResource : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerResource()\n {\n }\n\n /// Gets whether this resource is a URI template with parameters as opposed to a direct resource.\n public bool IsTemplated => ProtocolResourceTemplate.UriTemplate.Contains('{');\n\n /// Gets the protocol type for this instance.\n /// \n /// \n /// The property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n /// \n /// Every valid resource URI is a valid resource URI template, and thus this property always returns an instance.\n /// In contrast, the property may return if the resource template\n /// contains a parameter, in which case the resource template URI is not a valid resource URI.\n /// \n /// \n public abstract ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolResourceTemplate property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n public virtual Resource? ProtocolResource => ProtocolResourceTemplate.AsResource();\n\n /// \n /// Gets the resource, rendering it with the provided request parameters and returning the resource result.\n /// \n /// \n /// The request context containing information about the resource invocation, including any arguments\n /// passed to the resource. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the resource content and messages. If and only if this doesn't match the ,\n /// the method returns .\n /// \n /// is .\n /// The resource implementation returned or an unsupported result type.\n public abstract ValueTask ReadAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerResource Create(\n MethodInfo method, \n object? target = null,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerResource Create(\n AIFunction function,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(function, options);\n\n /// \n public override string ToString() => ProtocolResourceTemplate.UriTemplate;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolResourceTemplate.UriTemplate;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptMessage.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message within the Model Context Protocol (MCP) system, used for communication between clients and AI models.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be\n/// text, images, audio, or embedded resources.\n/// \n/// \n/// This class is similar to , but with enhanced support for embedding resources from the MCP server.\n/// It serves as a core data structure in the MCP message exchange flow, particularly in prompt formation and model responses.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent complete conversations or prompt sequences. They can be converted to and from \n/// objects using the extension methods and\n/// .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptMessage\n{\n /// \n /// Gets or sets the content of the message, which can be text, image, audio, or an embedded resource.\n /// \n /// \n /// The object contains all the message payload, whether it's simple text,\n /// base64-encoded binary data (for images/audio), or a reference to an embedded resource.\n /// The property indicates the specific content type.\n /// \n [JsonPropertyName(\"content\")]\n public ContentBlock Content { get; set; } = new TextContentBlock { Text = \"\" };\n\n /// \n /// Gets or sets the role of the message sender, specifying whether it's from a \"user\" or an \"assistant\".\n /// \n /// \n /// In the Model Context Protocol, each message must have a clear role assignment to maintain\n /// the conversation flow. User messages represent queries or inputs from users, while assistant\n /// messages represent responses generated by AI models.\n /// \n [JsonPropertyName(\"role\")]\n public Role Role { get; set; } = Role.User;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of resources created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating resources programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerResourceCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the URI template of the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the from the attribute will be used. If that's not present,\n /// a URI template will be inferred from the member's signature.\n /// \n public string? UriTemplate { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the name from the attribute will be used. If that's not present, a name based on the members's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the member,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the MIME (media) type of the .\n /// \n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerResourceCreateOptions Clone() =>\n new McpServerResourceCreateOptions\n {\n Services = Services,\n UriTemplate = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptResult.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// \n/// For integration with AI client libraries, can be converted to\n/// a collection of objects using the extension method.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class GetPromptResult : Result\n{\n /// \n /// Gets or sets an optional description for the prompt.\n /// \n /// \n /// \n /// This description provides contextual information about the prompt's purpose and use cases.\n /// It helps developers understand what the prompt is designed for and how it should be used.\n /// \n /// \n /// When returned from a server in response to a request,\n /// this description can be used by client applications to provide context about the prompt or to\n /// display in user interfaces.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets the prompt that the server offers.\n /// \n [JsonPropertyName(\"messages\")]\n public IList Messages { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptArgument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument that a prompt can accept for templating and customization.\n/// \n/// \n/// \n/// The class defines metadata for arguments that can be provided\n/// to a prompt. These arguments are used to customize or parameterize prompts when they are \n/// retrieved using requests.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptArgument : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the argument's purpose and expected values.\n /// \n /// \n /// This description helps developers understand what information should be provided\n /// for this argument and how it will affect the generated prompt.\n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets an indication as to whether this argument must be provided when requesting the prompt.\n /// \n /// \n /// When set to , the client must include this argument when making a request.\n /// If a required argument is missing, the server should respond with an error.\n /// \n [JsonPropertyName(\"required\")]\n public bool? Required { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/UnconditionalSuppressMessageAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a\n/// single code artifact.\n/// \n/// \n/// is different than\n/// in that it doesn't have a\n/// . So it is always preserved in the compiled assembly.\n/// \n[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\ninternal sealed class UnconditionalSuppressMessageAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the \n /// class, specifying the category of the tool and the identifier for an analysis rule.\n /// \n /// The category for the attribute.\n /// The identifier of the analysis rule the attribute applies to.\n public UnconditionalSuppressMessageAttribute(string category, string checkId)\n {\n Category = category;\n CheckId = checkId;\n }\n\n /// \n /// Gets the category identifying the classification of the attribute.\n /// \n /// \n /// The property describes the tool or tool analysis category\n /// for which a message suppression attribute applies.\n /// \n public string Category { get; }\n\n /// \n /// Gets the identifier of the analysis tool rule to be suppressed.\n /// \n /// \n /// Concatenated together, the and \n /// properties form a unique check identifier.\n /// \n public string CheckId { get; }\n\n /// \n /// Gets or sets the scope of the code that is relevant for the attribute.\n /// \n /// \n /// The Scope property is an optional argument that specifies the metadata scope for which\n /// the attribute is relevant.\n /// \n public string? Scope { get; set; }\n\n /// \n /// Gets or sets a fully qualified path that represents the target of the attribute.\n /// \n /// \n /// The property is an optional argument identifying the analysis target\n /// of the attribute. An example value is \"System.IO.Stream.ctor():System.Void\".\n /// Because it is fully qualified, it can be long, particularly for targets such as parameters.\n /// The analysis tool user interface should be capable of automatically formatting the parameter.\n /// \n public string? Target { get; set; }\n\n /// \n /// Gets or sets an optional argument expanding on exclusion criteria.\n /// \n /// \n /// The property is an optional argument that specifies additional\n /// exclusion where the literal metadata target is not sufficiently precise. For example,\n /// the cannot be applied within a method,\n /// and it may be desirable to suppress a violation against a statement in the method that will\n /// give a rule violation, but not against all statements in the method.\n /// \n public string? MessageId { get; set; }\n\n /// \n /// Gets or sets the justification for suppressing the code analysis message.\n /// \n public string? Justification { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's response to a request, \n/// containing suggested values for a given argument.\n/// \n/// \n/// \n/// is returned by the server in response to a \n/// request from the client. It provides suggested completions or valid values for a specific argument in a tool or resource reference.\n/// \n/// \n/// The result contains a object with suggested values, pagination information,\n/// and the total number of available completions. This is similar to auto-completion functionality in code editors.\n/// \n/// \n/// Clients typically use this to implement auto-suggestion features when users are inputting parameters\n/// for tool calls or resource references.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteResult : Result\n{\n /// \n /// Gets or sets the completion object containing the suggested values and pagination information.\n /// \n /// \n /// If no completions are available for the given input, the \n /// collection will be empty.\n /// \n [JsonPropertyName(\"completion\")]\n public Completion Completion { get; set; } = new Completion();\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/DynamicClientRegistrationResponse.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration response for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationResponse\n{\n /// \n /// Gets or sets the client identifier.\n /// \n [JsonPropertyName(\"client_id\")]\n public required string ClientId { get; init; }\n\n /// \n /// Gets or sets the client secret.\n /// \n [JsonPropertyName(\"client_secret\")]\n public string? ClientSecret { get; init; }\n\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public string[]? RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the client ID issued timestamp.\n /// \n [JsonPropertyName(\"client_id_issued_at\")]\n public long? ClientIdIssuedAt { get; init; }\n\n /// \n /// Gets or sets the client secret expiration time.\n /// \n [JsonPropertyName(\"client_secret_expires_at\")]\n public long? ClientSecretExpiresAt { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Root.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a root URI and its metadata in the Model Context Protocol.\n/// \n/// \n/// Root URIs serve as entry points for resource navigation, typically representing\n/// top-level directories or container resources that can be accessed and traversed.\n/// Roots provide a hierarchical structure for organizing and accessing resources within the protocol.\n/// Each root has a URI that uniquely identifies it and optional metadata like a human-readable name.\n/// \npublic sealed class Root\n{\n /// \n /// Gets or sets the URI of the root.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for the root.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n\n /// \n /// Gets or sets additional metadata for the root.\n /// \n /// \n /// This is reserved by the protocol for future use.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonElement? Meta { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientTransportOptions.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class StdioClientTransportOptions\n{\n /// \n /// Gets or sets the command to execute to start the server process.\n /// \n public required string Command\n {\n get;\n set\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Command cannot be null or empty.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the arguments to pass to the server process when it is started.\n /// \n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the working directory for the server process.\n /// \n public string? WorkingDirectory { get; set; }\n\n /// \n /// Gets or sets environment variables to set for the server process.\n /// \n /// \n /// \n /// This property allows you to specify environment variables that will be set in the server process's\n /// environment. This is useful for passing configuration, authentication information, or runtime flags\n /// to the server without modifying its code.\n /// \n /// \n /// By default, when starting the server process, the server process will inherit the current environment's variables,\n /// as discovered via . After those variables are found, the entries\n /// in this dictionary are used to augment and overwrite the entries read from the environment.\n /// That includes removing the variables for any of this collection's entries with a null value.\n /// \n /// \n public IDictionary? EnvironmentVariables { get; set; }\n\n /// \n /// Gets or sets the timeout to wait for the server to shut down gracefully.\n /// \n /// \n /// \n /// This property dictates how long the client should wait for the server process to exit cleanly during shutdown\n /// before forcibly terminating it. This balances between giving the server enough time to clean up \n /// resources and not hanging indefinitely if a server process becomes unresponsive.\n /// \n /// \n /// The default is five seconds.\n /// \n /// \n public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5);\n\n /// \n /// Gets or sets a callback that is invoked for each line of stderr received from the server process.\n /// \n public Action? StandardErrorLines { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientSessionTransport.cs", "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 protected override async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)\n {\n // Only clean up once.\n if (Interlocked.Exchange(ref _cleanedUp, 1) != 0)\n {\n return;\n }\n\n // We've not yet forcefully terminated the server. If it's already shut down, something went wrong,\n // so create an exception with details about that.\n error ??= await GetUnexpectedExitExceptionAsync(cancellationToken).ConfigureAwait(false);\n\n // Now terminate the server process.\n try\n {\n StdioClientTransport.DisposeProcess(_process, processRunning: true, _options.ShutdownTimeout, Name);\n }\n catch (Exception ex)\n {\n LogTransportShutdownFailed(Name, ex);\n }\n\n // And handle cleanup in the base type.\n await base.CleanupAsync(error, cancellationToken);\n }\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"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client,\n/// containing available resource templates.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover \n/// available resource templates on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resource templates.\n/// The server can provide the property to indicate there are more\n/// resource templates available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourceTemplatesResult : PaginatedResult\n{\n /// \n /// Gets or sets a list of resource templates that the server offers.\n /// \n /// \n /// This collection contains all the resource templates returned in the current page of results.\n /// Each provides metadata about resources available on the server,\n /// including URI templates, names, descriptions, and MIME types.\n /// \n [JsonPropertyName(\"resourceTemplates\")]\n public IList ResourceTemplates { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from \n/// a client to ask a server for auto-completion suggestions.\n/// \n/// \n/// \n/// is used in the Model Context Protocol completion workflow\n/// to provide intelligent suggestions for partial inputs related to resources, prompts, or other referenceable entities.\n/// The completion mechanism in MCP allows clients to request suggestions based on partial inputs.\n/// The server will respond with a containing matching values.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteRequestParams : RequestParams\n{\n /// \n /// Gets or sets the reference's information.\n /// \n [JsonPropertyName(\"ref\")]\n public required Reference Ref { get; init; }\n\n /// \n /// Gets or sets the argument information for the completion request, specifying what is being completed\n /// and the current partial input.\n /// \n [JsonPropertyName(\"argument\")]\n public required Argument Argument { get; init; }\n\n /// \n /// Gets or sets additional, optional context for completions.\n /// \n [JsonPropertyName(\"context\")]\n public CompleteContext? Context { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as prompts in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as prompts that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerPromptAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPromptAttribute()\n {\n }\n\n /// Gets the name of the prompt.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the prompt.\n public string? Title { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Completion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a completion object in the server's response to a request.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Completion\n{\n /// \n /// Gets or sets an array of completion values (auto-suggestions) for the requested input.\n /// \n /// \n /// This collection contains the actual text strings to be presented to users as completion suggestions.\n /// The array will be empty if no suggestions are available for the current input.\n /// Per the specification, this should not exceed 100 items.\n /// \n [JsonPropertyName(\"values\")]\n public IList Values { get; set; } = [];\n\n /// \n /// Gets or sets the total number of completion options available.\n /// \n /// \n /// This can exceed the number of values actually sent in the response.\n /// \n [JsonPropertyName(\"total\")]\n public int? Total { get; set; }\n\n /// \n /// Gets or sets an indicator as to whether there are additional completion options beyond \n /// those provided in the current response, even if the exact total is unknown.\n /// \n [JsonPropertyName(\"hasMore\")]\n public bool? HasMore { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Resource.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource that the server is capable of reading.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Resource : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource. Clients can use this information to filter or prioritize resources for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourcesCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the resources capability configuration.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ResourcesCapability\n{\n /// \n /// Gets or sets whether this server supports subscribing to resource updates.\n /// \n [JsonPropertyName(\"subscribe\")]\n public bool? Subscribe { get; set; }\n\n /// \n /// Gets or sets whether this server supports notifications for changes to the resource list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when resources are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their resource cache.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is called when clients request available resource templates that can be used\n /// to create resources within the Model Context Protocol server.\n /// Resource templates define the structure and URI patterns for resources accessible in the system,\n /// allowing clients to discover available resource types and their access patterns.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler responds to client requests for available resources and returns information about resources accessible through the server.\n /// The implementation should return a with the matching resources.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is responsible for retrieving the content of a specific resource identified by its URI in the Model Context Protocol.\n /// When a client sends a resources/read request, this handler is invoked with the resource URI.\n /// The handler should implement logic to locate and retrieve the requested resource, then return\n /// its contents in a ReadResourceResult object.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be subscribed to. The implementation should register the client's interest in receiving updates\n /// for the specified resource.\n /// Subscriptions allow clients to receive real-time notifications when resources change, without\n /// requiring polling.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be unsubscribed from. The implementation should remove the client's registration for receiving updates\n /// about the specified resource.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets a collection of resources served by the server.\n /// \n /// \n /// \n /// Resources specified via augment the , \n /// and handlers, if provided. Resources with template expressions in their URI templates are considered resource templates\n /// and are listed via ListResourceTemplate, whereas resources without template parameters are considered static resources and are listed with ListResources.\n /// \n /// \n /// ReadResource requests will first check the for the exact resource being requested. If no match is found, they'll proceed to\n /// try to match the resource against each resource template in . If no match is still found, the request will fall back to\n /// any handler registered for .\n /// \n /// \n [JsonIgnore]\n public McpServerResourceCollection? ResourceCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the tools capability configuration.\n/// See the schema for details.\n/// \npublic sealed class ToolsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the tool list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when tools are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their tool cache. This capability enables clients to stay synchronized with server-side \n /// changes to available tools.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// When used in conjunction with , both the tools from this handler\n /// and the tools from the collection will be combined to form the complete list of available tools.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the .\n /// The handler should implement logic to execute the requested tool and return appropriate results. \n /// It receives a containing information about the tool \n /// being called and its arguments, and should return a with the execution results.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets a collection of tools served by the server.\n /// \n /// \n /// Tools will specified via augment the and\n /// , if provided. ListTools requests will output information about every tool\n /// in and then also any tools output by , if it's\n /// non-. CallTool requests will first check for the tool\n /// being requested, and if the tool is not found in the , any specified \n /// will be invoked as a fallback.\n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? ToolCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SetLevelRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to enable or adjust logging.\n/// \n/// \n/// This request allows clients to configure the level of logging information they want to receive from the server.\n/// The server will send notifications for log events at the specified level and all higher (more severe) levels.\n/// \npublic sealed class SetLevelRequestParams : RequestParams\n{\n /// \n /// Gets or sets the level of logging that the client wants to receive from the server. \n /// \n [JsonPropertyName(\"level\")]\n public required LoggingLevel Level { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Prompt.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a prompt that the server offers.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Prompt : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets an optional description of what this prompt provides.\n /// \n /// \n /// \n /// This description helps developers understand the purpose and use cases for the prompt.\n /// It should explain what the prompt is designed to accomplish and any important context.\n /// \n /// \n /// The description is typically used in documentation, UI displays, and for providing context\n /// to client applications that may need to choose between multiple available prompts.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a list of arguments that this prompt accepts for templating and customization.\n /// \n /// \n /// \n /// This list defines the arguments that can be provided when requesting the prompt.\n /// Each argument specifies metadata like name, description, and whether it's required.\n /// \n /// \n /// When a client makes a request, it can provide values for these arguments\n /// which will be substituted into the prompt template or otherwise used to render the prompt.\n /// \n /// \n [JsonPropertyName(\"arguments\")]\n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/UnsubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Sent from the client to cancel resource update notifications from the server for a specific resource.\n/// \n/// \n/// \n/// After a client has subscribed to resource updates using , \n/// this message can be sent to stop receiving notifications for a specific resource. \n/// This is useful for conserving resources and network bandwidth when \n/// the client no longer needs to track changes to a particular resource.\n/// \n/// \n/// The unsubscribe operation is idempotent, meaning it can be called multiple times \n/// for the same resource without causing errors, even if there is no active subscription.\n/// \n/// \npublic sealed class UnsubscribeRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to unsubscribe from. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the client's response to an elicitation request.\n/// \npublic sealed class ElicitResult : Result\n{\n /// \n /// Gets or sets the user action in response to the elicitation.\n /// \n /// \n /// \n /// \n /// \"accept\"\n /// User submitted the form/confirmed the action\n /// \n /// \n /// \"decline\"\n /// User explicitly declined the action\n /// \n /// \n /// \"cancel\"\n /// User dismissed without making an explicit choice\n /// \n /// \n /// \n [JsonPropertyName(\"action\")]\n public string Action { get; set; } = \"cancel\";\n\n /// \n /// Gets or sets the submitted form data.\n /// \n /// \n /// \n /// This is typically omitted if the action is \"cancel\" or \"decline\".\n /// \n /// \n /// Values in the dictionary should be of types , ,\n /// , or .\n /// \n /// \n [JsonPropertyName(\"content\")]\n public IDictionary? Content { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common notification methods used in the MCP protocol.\n/// \npublic static class NotificationMethods\n{\n /// \n /// The name of notification sent by a server when the list of available tools changes.\n /// \n /// \n /// This notification informs clients that the set of available tools has been modified.\n /// Changes may include tools being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their tool list by calling the appropriate \n /// method to get the updated list of tools.\n /// \n public const string ToolListChangedNotification = \"notifications/tools/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available prompts changes.\n /// \n /// \n /// This notification informs clients that the set of available prompts has been modified.\n /// Changes may include prompts being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their prompt list by calling the appropriate \n /// method to get the updated list of prompts.\n /// \n public const string PromptListChangedNotification = \"notifications/prompts/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available resources changes.\n /// \n /// \n /// This notification informs clients that the set of available resources has been modified.\n /// Changes may include resources being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their resource list by calling the appropriate \n /// method to get the updated list of resources.\n /// \n public const string ResourceListChangedNotification = \"notifications/resources/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a resource is updated.\n /// \n /// \n /// This notification is used to inform clients about changes to a specific resource they have subscribed to.\n /// When a resource is updated, the server sends this notification to all clients that have subscribed to that resource.\n /// \n public const string ResourceUpdatedNotification = \"notifications/resources/updated\";\n\n /// \n /// The name of the notification sent by the client when roots have been updated.\n /// \n /// \n /// \n /// This notification informs the server that the client's \"roots\" have changed. \n /// Roots define the boundaries of where servers can operate within the filesystem, \n /// allowing them to understand which directories and files they have access to. Servers \n /// can request the list of roots from supporting clients and receive notifications when that list changes.\n /// \n /// \n /// After receiving this notification, servers may refresh their knowledge of roots by calling the appropriate \n /// method to get the updated list of roots from the client.\n /// \n /// \n public const string RootsListChangedNotification = \"notifications/roots/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a log message is generated.\n /// \n /// \n /// \n /// This notification is used by the server to send log messages to clients. Log messages can include\n /// different severity levels, such as debug, info, warning, or error, and an optional logger name to\n /// identify the source component.\n /// \n /// \n /// The minimum logging level that triggers notifications can be controlled by clients using the\n /// request. If no level has been set by a client, \n /// the server may determine which messages to send based on its own configuration.\n /// \n /// \n public const string LoggingMessageNotification = \"notifications/message\";\n\n /// \n /// The name of the notification sent from the client to the server after initialization has finished.\n /// \n /// \n /// \n /// This notification is sent by the client after it has received and processed the server's response to the \n /// request. It signals that the client is ready to begin normal operation \n /// and that the initialization phase is complete.\n /// \n /// \n /// After receiving this notification, the server can begin sending notifications and processing\n /// further requests from the client.\n /// \n /// \n public const string InitializedNotification = \"notifications/initialized\";\n\n /// \n /// The name of the notification sent to inform the receiver of a progress update for a long-running request.\n /// \n /// \n /// \n /// This notification provides updates on the progress of long-running operations. It includes\n /// a progress token that associates the notification with a specific request, the current progress value,\n /// and optionally, a total value and a descriptive message.\n /// \n /// \n /// Progress notifications may be sent by either the client or the server, depending on the context.\n /// Progress notifications enable clients to display progress indicators for operations that might take\n /// significant time to complete, such as large file uploads, complex computations, or resource-intensive\n /// processing tasks.\n /// \n /// \n public const string ProgressNotification = \"notifications/progress\";\n\n /// \n /// The name of the notification sent to indicate that a previously-issued request should be canceled.\n /// \n /// \n /// \n /// From the issuer's perspective, the request should still be in-flight. However, due to communication latency,\n /// it is always possible that this notification may arrive after the request has already finished.\n /// \n /// \n /// This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n /// \n /// \n /// A client must not attempt to cancel its `initialize` request.\n /// \n /// \n public const string CancelledNotification = \"notifications/cancelled\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ReadResourceResult : Result\n{\n /// \n /// Gets or sets a list of objects that this resource contains.\n /// \n /// \n /// This property contains the actual content of the requested resource, which can be\n /// either text-based () or binary ().\n /// The type of content included depends on the resource being accessed.\n /// \n [JsonPropertyName(\"contents\")]\n public IList Contents { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration request for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationRequest\n{\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public required string[] RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the human-readable name of the client.\n /// \n [JsonPropertyName(\"client_name\")]\n public string? ClientName { get; init; }\n\n /// \n /// Gets or sets the URL of the client's home page.\n /// \n [JsonPropertyName(\"client_uri\")]\n public string? ClientUri { get; init; }\n\n /// \n /// Gets or sets the scope values that the client will use.\n /// \n [JsonPropertyName(\"scope\")]\n public string? Scope { get; init; }\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/Client/SseClientTransportOptions.cs", "using ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class SseClientTransportOptions\n{\n /// \n /// Gets or sets the base address of the server for SSE connections.\n /// \n public required Uri Endpoint\n {\n get;\n set\n {\n if (value is null)\n {\n throw new ArgumentNullException(nameof(value), \"Endpoint cannot be null.\");\n }\n if (!value.IsAbsoluteUri)\n {\n throw new ArgumentException(\"Endpoint must be an absolute URI.\", nameof(value));\n }\n if (value.Scheme != Uri.UriSchemeHttp && value.Scheme != Uri.UriSchemeHttps)\n {\n throw new ArgumentException(\"Endpoint must use HTTP or HTTPS scheme.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the transport mode to use for the connection. Defaults to .\n /// \n /// \n /// \n /// When set to (the default), the client will first attempt to use\n /// Streamable HTTP transport and automatically fall back to SSE transport if the server doesn't support it.\n /// \n /// \n /// Streamable HTTP transport specification.\n /// HTTP with SSE transport specification.\n /// \n /// \n public HttpTransportMode TransportMode { get; set; } = HttpTransportMode.AutoDetect;\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets a timeout used to establish the initial connection to the SSE server. Defaults to 30 seconds.\n /// \n /// \n /// This timeout controls how long the client waits for:\n /// \n /// The initial HTTP connection to be established with the SSE server\n /// The endpoint event to be received, which indicates the message endpoint URL\n /// \n /// If the timeout expires before the connection is established, a will be thrown.\n /// \n public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);\n\n /// \n /// Gets custom HTTP headers to include in requests to the SSE server.\n /// \n /// \n /// Use this property to specify custom HTTP headers that should be sent with each request to the server.\n /// \n public IDictionary? AdditionalHeaders { get; set; }\n\n /// \n /// Gets sor sets the authorization provider to use for authentication.\n /// \n public ClientOAuthOptions? OAuth { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's capability to provide predefined prompt templates that clients can use.\n/// \n/// \n/// \n/// The prompts capability allows a server to expose a collection of predefined prompt templates that clients\n/// can discover and use. These prompts can be static (defined in the ) or\n/// dynamically generated through handlers.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the prompt list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when prompts are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their prompt cache. This capability enables clients to stay synchronized with server-side changes \n /// to available prompts.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests a list of available prompts from the server\n /// via a request. Results from this handler are returned\n /// along with any prompts defined in .\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt by name and provides arguments \n /// for the prompt if needed. The handler receives the request context containing the prompt name and any arguments, \n /// and should return a with the prompt messages and other details.\n /// \n /// \n /// This handler will be invoked if the requested prompt name is not found in the ,\n /// allowing for dynamic prompt generation or retrieval from external sources.\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets a collection of prompts that will be served by the server.\n /// \n /// \n /// \n /// The contains the predefined prompts that clients can request from the server.\n /// This collection works in conjunction with and \n /// when those are provided:\n /// \n /// \n /// - For requests: The server returns all prompts from this collection \n /// plus any additional prompts provided by the if it's set.\n /// \n /// \n /// - For requests: The server first checks this collection for the requested prompt.\n /// If not found, it will invoke the as a fallback if one is set.\n /// \n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? PromptCollection { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/NullableAttributes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n /// Specifies that null is allowed as an input even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class AllowNullAttribute : Attribute;\n\n /// Specifies that null is disallowed as an input even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class DisallowNullAttribute : Attribute;\n\n /// Specifies that an output may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class MaybeNullAttribute : Attribute;\n\n /// Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class NotNullAttribute : Attribute;\n\n /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class MaybeNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter may be null.\n /// \n public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class NotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter will not be null.\n /// \n public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that the output will be non-null if the named parameter is non-null.\n [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]\n internal sealed class NotNullIfNotNullAttribute : Attribute\n {\n /// Initializes the attribute with the associated parameter name.\n /// \n /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.\n /// \n public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;\n\n /// Gets the associated parameter name.\n public string ParameterName { get; }\n }\n\n /// Applied to a method that will never return under any circumstance.\n [AttributeUsage(AttributeTargets.Method, Inherited = false)]\n internal sealed class DoesNotReturnAttribute : Attribute;\n\n /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class DoesNotReturnIfAttribute : Attribute\n {\n /// Initializes the attribute with the specified parameter value.\n /// \n /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to\n /// the associated parameter matches this value.\n /// \n public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;\n\n /// Gets the condition parameter value.\n public bool ParameterValue { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullAttribute : Attribute\n {\n /// Initializes the attribute with a field or property member.\n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullAttribute(string member) => Members = [member];\n\n /// Initializes the attribute with the list of field and property members.\n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullAttribute(params string[] members) => Members = members;\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition and a field or property member.\n /// \n /// The return value condition. If the method returns this value, the associated field or property member will not be null.\n /// \n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, string member)\n {\n ReturnValue = returnValue;\n Members = [member];\n }\n\n /// Initializes the attribute with the specified return value condition and list of field and property members.\n /// \n /// The return value condition. If the method returns this value, the associated field and property members will not be null.\n /// \n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, params string[] members)\n {\n ReturnValue = returnValue;\n Members = members;\n }\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientFactory.cs", "using Microsoft.Extensions.Logging;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides factory methods for creating Model Context Protocol (MCP) clients.\n/// \n/// \n/// This factory class is the primary way to instantiate instances\n/// that connect to MCP servers. It handles the creation and connection\n/// of appropriate implementations through the supplied transport.\n/// \npublic static partial class McpClientFactory\n{\n /// Creates an , connecting it to the specified server.\n /// The transport instance used to communicate with the server.\n /// \n /// A client configuration object which specifies client capabilities and protocol version.\n /// If , details based on the current process will be employed.\n /// \n /// A logger factory for creating loggers for clients.\n /// The to monitor for cancellation requests. The default is .\n /// An that's connected to the specified server.\n /// is .\n /// is .\n public static async Task CreateAsync(\n IClientTransport clientTransport,\n McpClientOptions? clientOptions = null,\n ILoggerFactory? loggerFactory = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(clientTransport);\n\n McpClient client = new(clientTransport, clientOptions, loggerFactory);\n try\n {\n await client.ConnectAsync(cancellationToken).ConfigureAwait(false);\n if (loggerFactory?.CreateLogger(typeof(McpClientFactory)) is ILogger logger)\n {\n logger.LogClientCreated(client.EndpointName);\n }\n }\n catch\n {\n await client.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n\n return client;\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} client created and connected.\")]\n private static partial void LogClientCreated(this ILogger logger, string endpointName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a resource provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting resource data.\n/// See the schema for details.\n/// \npublic sealed class ReadResourceRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method or property should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods or properties that should be exposed as resources in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods or properties become available as resources that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerResourceAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerResourceAttribute()\n {\n }\n\n /// Gets or sets the URI template of the resource.\n /// \n /// If , a URI will be derived from and the method's parameter names.\n /// This template may, but doesn't have to, include parameters; if it does, this \n /// will be considered a \"resource template\", and if it doesn't, it will be considered a \"direct resource\".\n /// The former will be listed with requests and the latter\n /// with requests.\n /// \n public string? UriTemplate { get; set; }\n\n /// Gets or sets the name of the resource.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the resource.\n public string? Title { get; set; }\n\n /// Gets or sets the MIME (media) type of the resource.\n public string? MimeType { get; set; }\n}\n"], ["/csharp-sdk/samples/QuickstartClient/Program.cs", "using Anthropic.SDK;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Client;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Configuration\n .AddEnvironmentVariables()\n .AddUserSecrets();\n\nvar (command, arguments) = GetCommandAndArguments(args);\n\nvar clientTransport = new StdioClientTransport(new()\n{\n Name = \"Demo Server\",\n Command = command,\n Arguments = arguments,\n});\n\nawait using var mcpClient = await McpClientFactory.CreateAsync(clientTransport);\n\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\"Connected to server with tools: {tool.Name}\");\n}\n\nusing var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration[\"ANTHROPIC_API_KEY\"]))\n .Messages\n .AsBuilder()\n .UseFunctionInvocation()\n .Build();\n\nvar options = new ChatOptions\n{\n MaxOutputTokens = 1000,\n ModelId = \"claude-3-5-sonnet-20241022\",\n Tools = [.. tools]\n};\n\nConsole.ForegroundColor = ConsoleColor.Green;\nConsole.WriteLine(\"MCP Client Started!\");\nConsole.ResetColor();\n\nPromptForInput();\nwhile(Console.ReadLine() is string query && !\"exit\".Equals(query, StringComparison.OrdinalIgnoreCase))\n{\n if (string.IsNullOrWhiteSpace(query))\n {\n PromptForInput();\n continue;\n }\n\n await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))\n {\n Console.Write(message);\n }\n Console.WriteLine();\n\n PromptForInput();\n}\n\nstatic void PromptForInput()\n{\n Console.WriteLine(\"Enter a command (or 'exit' to quit):\");\n Console.ForegroundColor = ConsoleColor.Cyan;\n Console.Write(\"> \");\n Console.ResetColor();\n}\n\n/// \n/// Determines the command (executable) to run and the script/path to pass to it. This allows different\n/// languages/runtime environments to be used as the MCP server.\n/// \n/// \n/// This method uses the file extension of the first argument to determine the command, if it's py, it'll run python,\n/// if it's js, it'll run node, if it's a directory or a csproj file, it'll run dotnet.\n/// \n/// If no arguments are provided, it defaults to running the QuickstartWeatherServer project from the current repo.\n/// \n/// This method would only be required if you're creating a generic client, such as we use for the quickstart.\n/// \nstatic (string command, string[] arguments) GetCommandAndArguments(string[] args)\n{\n return args switch\n {\n [var script] when script.EndsWith(\".py\") => (\"python\", args),\n [var script] when script.EndsWith(\".js\") => (\"node\", args),\n [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(\".csproj\")) => (\"dotnet\", [\"run\", \"--project\", script]),\n _ => (\"dotnet\", [\"run\", \"--project\", Path.Combine(GetCurrentSourceDirectory(), \"../QuickstartWeatherServer\")])\n };\n}\n\nstatic string GetCurrentSourceDirectory([CallerFilePath] string? currentFile = null)\n{\n Debug.Assert(!string.IsNullOrWhiteSpace(currentFile));\n return Path.GetDirectoryName(currentFile) ?? throw new InvalidOperationException(\"Unable to determine source directory.\");\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for paginated requests.\n/// \n/// \n/// See the schema for details\n/// \npublic abstract class PaginatedRequestParams : RequestParams\n{\n /// Prevent external derivations.\n private protected PaginatedRequestParams()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the current pagination position.\n /// \n /// \n /// If provided, the server should return results starting after this cursor.\n /// This value should be obtained from the \n /// property of a previous request's response.\n /// \n [JsonPropertyName(\"cursor\")]\n public string? Cursor { get; init; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/dd75c45c123055baacd7aa4418f425f412797a29/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs\n// and then modified to build on netstandard2.0.\n\n#if !NET\nusing System.Buffers;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Provides a handler used by the language compiler to process interpolated strings into instances.\n internal ref struct DefaultInterpolatedStringHandler\n {\n // Implementation note:\n // As this type lives in CompilerServices and is only intended to be targeted by the compiler,\n // public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input\n // when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException.\n\n /// Expected average length of formatted data used for an individual interpolation expression result.\n /// \n /// This is inherited from string.Format, and could be changed based on further data.\n /// string.Format actually uses `format.Length + args.Length * 8`, but format.Length\n /// includes the format items themselves, e.g. \"{0}\", and since it's rare to have double-digit\n /// numbers of items, we bump the 8 up to 11 to account for the three extra characters in \"{d}\",\n /// since the compiler-provided base length won't include the equivalent character count.\n /// \n private const int GuessedLengthPerHole = 11;\n /// Minimum size array to rent from the pool.\n /// Same as stack-allocation size used today by string.Format.\n private const int MinimumArrayPoolLength = 256;\n\n /// Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.\n private readonly IFormatProvider? _provider;\n /// Array rented from the array pool and used to back .\n private char[]? _arrayToReturnToPool;\n /// The span to write into.\n private Span _chars;\n /// Position at which to write the next character.\n private int _pos;\n /// Whether provides an ICustomFormatter.\n /// \n /// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive\n /// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field\n /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider\n /// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a\n /// formatter, we pay for the extra interface call on each AppendFormatted that needs it.\n /// \n private readonly bool _hasCustomFormatter;\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)\n {\n _provider = null;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = false;\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)\n {\n _provider = provider;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer)\n {\n _provider = provider;\n _chars = initialBuffer;\n _arrayToReturnToPool = null;\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Derives a default length with which to seed the handler.\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant\n internal static int GetDefaultLength(int literalLength, int formattedCount) =>\n Math.Max(MinimumArrayPoolLength, literalLength + (formattedCount * GuessedLengthPerHole));\n\n /// Gets the built .\n /// The built string.\n public override string ToString() => Text.ToString();\n\n /// Gets the built and clears the handler.\n /// The built string.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after\n /// is called on any one of them.\n /// \n public string ToStringAndClear()\n {\n string result = Text.ToString();\n Clear();\n return result;\n }\n\n /// Clears the handler.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after \n /// is called on any one of them.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Clear()\n {\n char[]? toReturn = _arrayToReturnToPool;\n\n // Defensive clear\n _arrayToReturnToPool = null;\n _chars = default;\n _pos = 0;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n /// Gets a span of the characters appended to the handler.\n public ReadOnlySpan Text => _chars.Slice(0, _pos);\n\n /// Writes the specified string to the handler.\n /// The string to write.\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void AppendLiteral(string value)\n {\n if (value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopyString(value);\n }\n }\n\n #region AppendFormatted\n // Design note:\n // The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression;\n // if it can't find an appropriate overload, for handlers in general it'll simply fail to compile.\n // (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to\n // its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case,\n // interpolated strings will still work, but it has the downside that a developer generally won't know\n // if the fallback is happening and they're paying more.)\n //\n // At a minimum, then, we would need an overload that accepts:\n // (object value, int alignment = 0, string? format = null)\n // Such an overload would provide the same expressiveness as string.Format. However, this has several\n // shortcomings:\n // - Every value type in an interpolation expression would be boxed.\n // - ReadOnlySpan could not be used in interpolation expressions.\n // - Every AppendFormatted call would have three arguments at the call site, bloating the IL further.\n // - Every invocation would be more expensive, due to lack of specialization, every call needing to account\n // for alignment and format, etc.\n //\n // To address that, we could just have overloads for T and ReadOnlySpan:\n // (T)\n // (T, int alignment)\n // (T, string? format)\n // (T, int alignment, string? format)\n // (ReadOnlySpan)\n // (ReadOnlySpan, int alignment)\n // (ReadOnlySpan, string? format)\n // (ReadOnlySpan, int alignment, string? format)\n // but this also has shortcomings:\n // - Some expressions that would have worked with an object overload will now force a fallback to string.Format\n // (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler\n // can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully\n // be passed as an argument of type `object` but not of type `T`.\n // - Reference types get no benefit from going through the generic code paths, and actually incur some overheads\n // from doing so.\n // - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate\n // at compile time for value types but don't (currently) if the Nullable goes through the same code paths\n // (see https://github.com/dotnet/runtime/issues/50915).\n //\n // We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common handler\n // and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads for each of:\n // (T, ...) where T : struct\n // (T?, ...) where T : struct\n // (object, ...)\n // (ReadOnlySpan, ...)\n // (string, ...)\n // but this also has shortcomings, most importantly:\n // - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object overload.\n // This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, so without those\n // they'd all map to the object overloads as well.\n // - Any reference type with an implicit cast to ROS will fail to compile due to ambiguities between the overloads. string\n // is one such type, hence needing dedicated overloads for it that can be bound to more tightly.\n //\n // A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, would be the set:\n // (T, ...) with no constraint\n // (ReadOnlySpan) and (ReadOnlySpan, int)\n // (object, int alignment = 0, string? format = null)\n // (string) and (string, int)\n // This would address most of the concerns, at the expense of:\n // - Most reference types going through the generic code paths and so being a bit more expensive.\n // - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed.\n // We could choose to add a T? where T : struct set of overloads if necessary.\n // Strings don't require their own overloads here, but as they're expected to be very common and as we can\n // optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't\n // need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them.\n //\n // Hole values are formatted according to the following policy:\n // 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if the value is null).\n // 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat.\n // 3. If the type implements IFormattable, use IFormattable.ToString.\n // 4. Otherwise, use object.ToString.\n // This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this doesn't\n // apply is ReadOnlySpan, which isn't supported by either string.Format nor StringBuilder.AppendFormat, but more\n // importantly which can't be boxed to be passed to ICustomFormatter.Format.\n\n #region AppendFormatted T\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The type of the value to write.\n public void AppendFormatted(T value)\n {\n // This method could delegate to AppendFormatted with a null format, but explicitly passing\n // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined,\n // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format.\n\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n return;\n }\n\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n public void AppendFormatted(T value, string? format)\n {\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format);\n return;\n }\n\n // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter\n // requires the former. For value types, it won't matter as the type checks devolve into\n // JIT-time constants. For reference types, they're more likely to implement IFormattable\n // than they are to implement ISpanFormattable: if they don't implement either, we save an\n // interface check over first checking for ISpanFormattable and then for IFormattable, and\n // if it only implements IFormattable, we come out even: only if it implements both do we\n // end up paying for an extra interface check.\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment)\n {\n int startingPos = _pos;\n AppendFormatted(value);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment, string? format)\n {\n int startingPos = _pos;\n AppendFormatted(value, format);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n #endregion\n\n #region AppendFormatted ReadOnlySpan\n /// Writes the specified character span to the handler.\n /// The span to write.\n public void AppendFormatted(scoped ReadOnlySpan value)\n {\n // Fast path for when the value fits in the current buffer\n if (value.TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopySpan(value);\n }\n }\n\n /// Writes the specified string of chars to the handler.\n /// The span to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(scoped ReadOnlySpan value, int alignment = 0, string? format = null)\n {\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingRequired = alignment - value.Length;\n if (paddingRequired <= 0)\n {\n // The value is as large or larger than the required amount of padding,\n // so just write the value.\n AppendFormatted(value);\n return;\n }\n\n // Write the value along with the appropriate padding.\n EnsureCapacityForAdditionalChars(value.Length + paddingRequired);\n if (leftAlign)\n {\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n }\n else\n {\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n #endregion\n\n #region AppendFormatted string\n /// Writes the specified value to the handler.\n /// The value to write.\n public void AppendFormatted(string? value)\n {\n // Fast-path for no custom formatter and a non-null string that fits in the current destination buffer.\n if (!_hasCustomFormatter &&\n value is not null &&\n value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n AppendFormattedSlow(value);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// \n /// Slow path to handle a custom formatter, potentially null value,\n /// or a string that doesn't fit in the current buffer.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendFormattedSlow(string? value)\n {\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n }\n else if (value is not null)\n {\n EnsureCapacityForAdditionalChars(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>\n // Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload\n // simply to disambiguate between ROS and object, just in case someone does specify a format, as\n // string is implicitly convertible to both. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n\n #region AppendFormatted object\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>\n // This overload is expected to be used rarely, only if either a) something strongly typed as object is\n // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It\n // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n #endregion\n\n /// Gets whether the provider provides a custom formatter.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites\n internal static bool HasCustomFormatter(IFormatProvider provider)\n {\n Debug.Assert(provider is not null);\n Debug.Assert(provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, \"Expected CultureInfo to not provide a custom formatter\");\n return\n provider!.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case\n provider.GetFormat(typeof(ICustomFormatter)) != null;\n }\n\n /// Formats the value using the custom formatter from the provider.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendCustomFormatter(T value, string? format)\n {\n // This case is very rare, but we need to handle it prior to the other checks in case\n // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.\n // We do the cast here rather than in the ctor, even though this could be executed multiple times per\n // formatting, to make the cast pay for play.\n Debug.Assert(_hasCustomFormatter);\n Debug.Assert(_provider != null);\n\n ICustomFormatter? formatter = (ICustomFormatter?)_provider!.GetFormat(typeof(ICustomFormatter));\n Debug.Assert(formatter != null, \"An incorrectly written provider said it implemented ICustomFormatter, and then didn't\");\n\n if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted)\n {\n AppendLiteral(customFormatted);\n }\n }\n\n /// Handles adding any padding required for aligning a formatted value in an interpolation expression.\n /// The position at which the written value started.\n /// Non-zero minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)\n {\n Debug.Assert(startingPos >= 0 && startingPos <= _pos);\n Debug.Assert(alignment != 0);\n\n int charsWritten = _pos - startingPos;\n\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingNeeded = alignment - charsWritten;\n if (paddingNeeded > 0)\n {\n EnsureCapacityForAdditionalChars(paddingNeeded);\n\n if (leftAlign)\n {\n _chars.Slice(_pos, paddingNeeded).Fill(' ');\n }\n else\n {\n _chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded));\n _chars.Slice(startingPos, paddingNeeded).Fill(' ');\n }\n\n _pos += paddingNeeded;\n }\n }\n\n /// Ensures has the capacity to store beyond .\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void EnsureCapacityForAdditionalChars(int additionalChars)\n {\n if (_chars.Length - _pos < additionalChars)\n {\n Grow(additionalChars);\n }\n }\n\n /// Fallback for fast path in when there's not enough space in the destination.\n /// The string to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopyString(string value)\n {\n Grow(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Fallback for for when not enough space exists in the current buffer.\n /// The span to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopySpan(scoped ReadOnlySpan value)\n {\n Grow(value.Length);\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Grows to have the capacity to store at least beyond .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow(int additionalChars)\n {\n // This method is called when the remaining space (_chars.Length - _pos) is\n // insufficient to store a specific number of additional characters. Thus, we\n // need to grow to at least that new total. GrowCore will handle growing by more\n // than that if possible.\n Debug.Assert(additionalChars > _chars.Length - _pos);\n GrowCore((uint)_pos + (uint)additionalChars);\n }\n\n /// Grows the size of .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow()\n {\n // This method is called when the remaining space in _chars isn't sufficient to continue\n // the operation. Thus, we need at least one character beyond _chars.Length. GrowCore\n // will handle growing by more than that if possible.\n GrowCore((uint)_chars.Length + 1);\n }\n\n /// Grow the size of to at least the specified .\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines\n private void GrowCore(uint requiredMinCapacity)\n {\n // We want the max of how much space we actually required and doubling our capacity (without going beyond the max allowed length). We\n // also want to avoid asking for small arrays, to reduce the number of times we need to grow, and since we're working with unsigned\n // ints that could technically overflow if someone tried to, for example, append a huge string to a huge string, we also clamp to int.MaxValue.\n // Even if the array creation fails in such a case, we may later fail in ToStringAndClear.\n\n const int StringMaxLength = 0x3FFFFFDF;\n uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, StringMaxLength));\n int arraySize = (int)Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue);\n\n char[] newArray = ArrayPool.Shared.Rent(arraySize);\n _chars.Slice(0, _pos).CopyTo(newArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = newArray;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n private static uint Clamp(uint value, uint min, uint max)\n {\n Debug.Assert(min <= max);\n\n if (value < min)\n {\n return min;\n }\n else if (value > max)\n {\n return max;\n }\n\n return value;\n }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to request real-time notifications from the server whenever a particular resource changes.\n/// \n/// \n/// \n/// The subscription mechanism allows clients to be notified about changes to specific resources\n/// identified by their URI. When a subscribed resource changes, the server sends a notification\n/// to the client with the updated resource information.\n/// \n/// \n/// Subscriptions remain active until explicitly canceled using \n/// or until the connection is terminated.\n/// \n/// \n/// The server may refuse or limit subscriptions based on its capabilities or resource constraints.\n/// \n/// \npublic sealed class SubscribeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the URI of the resource to subscribe to.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses depenency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await thisServer.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available prompts.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available prompts on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many prompts.\n/// The server can provide the property to indicate there are more\n/// prompts available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListPromptsResult : PaginatedResult\n{\n /// \n /// A list of prompts or prompt templates that the server offers.\n /// \n [JsonPropertyName(\"prompts\")]\n public IList Prompts { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available resources.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available resources on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resources.\n/// The server can provide the property to indicate there are more\n/// resources available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourcesResult : PaginatedResult\n{\n /// \n /// A list of resources that the server offers.\n /// \n [JsonPropertyName(\"resources\")]\n public IList Resources { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpServerTransportOptions.cs", "using Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\n/// \n/// Configuration options for .\n/// which implements the Streaming HTTP transport for the Model Context Protocol.\n/// See the protocol specification for details on the Streamable HTTP transport. \n/// \npublic class HttpServerTransportOptions\n{\n /// \n /// Gets or sets an optional asynchronous callback to configure per-session \n /// with access to the of the request that initiated the session.\n /// \n public Func? ConfigureSessionOptions { get; set; }\n\n /// \n /// Gets or sets an optional asynchronous callback for running new MCP sessions manually.\n /// This is useful for running logic before a sessions starts and after it completes.\n /// \n public Func? RunSessionHandler { get; set; }\n\n /// \n /// Gets or sets whether the server should run in a stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process.\n /// \n /// \n /// If , the \"/sse\" endpoint will be disabled, and client information will be round-tripped as part\n /// of the \"MCP-Session-Id\" header instead of stored in memory. Unsolicited server-to-client messages and all server-to-client\n /// requests are also unsupported, because any responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// Defaults to .\n /// \n public bool Stateless { get; set; }\n\n /// \n /// Gets or sets whether the server should use a single execution context for the entire session.\n /// If , handlers like tools get called with the \n /// belonging to the corresponding HTTP request which can change throughout the MCP session.\n /// If , handlers will get called with the same \n /// used to call and .\n /// \n /// \n /// Enabling a per-session can be useful for setting variables\n /// that persist for the entire session, but it prevents you from using IHttpContextAccessor in handlers.\n /// Defaults to .\n /// \n public bool PerSessionExecutionContext { get; set; }\n\n /// \n /// Gets or sets the duration of time the server will wait between any active requests before timing out an MCP session.\n /// \n /// \n /// This is checked in background every 5 seconds. A client trying to resume a session will receive a 404 status code\n /// and should restart their session. A client can keep their session open by keeping a GET request open.\n /// Defaults to 2 hours.\n /// \n public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromHours(2);\n\n /// \n /// Gets or sets maximum number of idle sessions to track in memory. This is used to limit the number of sessions that can be idle at once.\n /// \n /// \n /// Past this limit, the server will log a critical error and terminate the oldest idle sessions even if they have not reached\n /// their until the idle session count is below this limit. Clients that keep their session open by\n /// keeping a GET request open will not count towards this limit.\n /// Defaults to 100,000 sessions.\n /// \n public int MaxIdleSessionCount { get; set; } = 100_000;\n\n /// \n /// Used for testing the .\n /// \n public TimeProvider TimeProvider { get; set; } = TimeProvider.System;\n}\n"], ["/csharp-sdk/samples/ProtectedMCPClient/Program.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Text;\nusing System.Web;\n\nvar serverUrl = \"http://localhost:7071/\";\n\nConsole.WriteLine(\"Protected MCP Client\");\nConsole.WriteLine($\"Connecting to weather server at {serverUrl}...\");\nConsole.WriteLine();\n\n// We can customize a shared HttpClient with a custom handler if desired\nvar sharedHandler = new SocketsHttpHandler\n{\n PooledConnectionLifetime = TimeSpan.FromMinutes(2),\n PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1)\n};\nvar httpClient = new HttpClient(sharedHandler);\n\nvar consoleLoggerFactory = LoggerFactory.Create(builder =>\n{\n builder.AddConsole();\n});\n\nvar transport = new SseClientTransport(new()\n{\n Endpoint = new Uri(serverUrl),\n Name = \"Secure Weather Client\",\n OAuth = new()\n {\n ClientName = \"ProtectedMcpClient\",\n RedirectUri = new Uri(\"http://localhost:1179/callback\"),\n AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,\n }\n}, httpClient, consoleLoggerFactory);\n\nvar client = await McpClientFactory.CreateAsync(transport, loggerFactory: consoleLoggerFactory);\n\nvar tools = await client.ListToolsAsync();\nif (tools.Count == 0)\n{\n Console.WriteLine(\"No tools available on the server.\");\n return;\n}\n\nConsole.WriteLine($\"Found {tools.Count} tools on the server.\");\nConsole.WriteLine();\n\nif (tools.Any(t => t.Name == \"get_alerts\"))\n{\n Console.WriteLine(\"Calling get_alerts tool...\");\n\n var result = await client.CallToolAsync(\n \"get_alerts\",\n new Dictionary { { \"state\", \"WA\" } }\n );\n\n Console.WriteLine(\"Result: \" + ((TextContentBlock)result.Content[0]).Text);\n Console.WriteLine();\n}\n\n/// Handles the OAuth authorization URL by starting a local HTTP server and opening a browser.\n/// This implementation demonstrates how SDK consumers can provide their own authorization flow.\n/// \n/// The authorization URL to open in the browser.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// The authorization code extracted from the callback, or null if the operation failed.\nstatic async Task HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken)\n{\n Console.WriteLine(\"Starting OAuth authorization flow...\");\n Console.WriteLine($\"Opening browser to: {authorizationUrl}\");\n\n var listenerPrefix = redirectUri.GetLeftPart(UriPartial.Authority);\n if (!listenerPrefix.EndsWith(\"/\")) listenerPrefix += \"/\";\n\n using var listener = new HttpListener();\n listener.Prefixes.Add(listenerPrefix);\n\n try\n {\n listener.Start();\n Console.WriteLine($\"Listening for OAuth callback on: {listenerPrefix}\");\n\n OpenBrowser(authorizationUrl);\n\n var context = await listener.GetContextAsync();\n var query = HttpUtility.ParseQueryString(context.Request.Url?.Query ?? string.Empty);\n var code = query[\"code\"];\n var error = query[\"error\"];\n\n string responseHtml = \"

Authentication complete

You can close this window now.

\";\n byte[] buffer = Encoding.UTF8.GetBytes(responseHtml);\n context.Response.ContentLength64 = buffer.Length;\n context.Response.ContentType = \"text/html\";\n context.Response.OutputStream.Write(buffer, 0, buffer.Length);\n context.Response.Close();\n\n if (!string.IsNullOrEmpty(error))\n {\n Console.WriteLine($\"Auth error: {error}\");\n return null;\n }\n\n if (string.IsNullOrEmpty(code))\n {\n Console.WriteLine(\"No authorization code received\");\n return null;\n }\n\n Console.WriteLine(\"Authorization code received successfully.\");\n return code;\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error getting auth code: {ex.Message}\");\n return null;\n }\n finally\n {\n if (listener.IsListening) listener.Stop();\n }\n}\n\n/// \n/// Opens the specified URL in the default browser.\n/// \n/// The URL to open.\nstatic void OpenBrowser(Uri url)\n{\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = url.ToString(),\n UseShellExecute = true\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error opening browser. {ex.Message}\");\n Console.WriteLine($\"Please manually open this URL: {url}\");\n }\n}"], ["/csharp-sdk/samples/EverythingServer/Program.cs", "using EverythingServer;\nusing EverythingServer.Prompts;\nusing EverythingServer.Resources;\nusing EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Resources;\nusing OpenTelemetry.Trace;\n\nvar builder = Host.CreateApplicationBuilder(args);\nbuilder.Logging.AddConsole(consoleLogOptions =>\n{\n // Configure all logs to go to stderr\n consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nHashSet subscriptions = [];\nvar _minimumLoggingLevel = LoggingLevel.Debug;\n\nbuilder.Services\n .AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithPrompts()\n .WithPrompts()\n .WithResources()\n .WithSubscribeToResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n\n if (uri is not null)\n {\n subscriptions.Add(uri);\n\n await ctx.Server.SampleAsync([\n new ChatMessage(ChatRole.System, \"You are a helpful test server\"),\n new ChatMessage(ChatRole.User, $\"Resource {uri}, context: A new subscription was started\"),\n ],\n options: new ChatOptions\n {\n MaxOutputTokens = 100,\n Temperature = 0.7f,\n },\n cancellationToken: ct);\n }\n\n return new EmptyResult();\n })\n .WithUnsubscribeFromResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n if (uri is not null)\n {\n subscriptions.Remove(uri);\n }\n return new EmptyResult();\n })\n .WithCompleteHandler(async (ctx, ct) =>\n {\n var exampleCompletions = new Dictionary>\n {\n { \"style\", [\"casual\", \"formal\", \"technical\", \"friendly\"] },\n { \"temperature\", [\"0\", \"0.5\", \"0.7\", \"1.0\"] },\n { \"resourceId\", [\"1\", \"2\", \"3\", \"4\", \"5\"] }\n };\n\n if (ctx.Params is not { } @params)\n {\n throw new NotSupportedException($\"Params are required.\");\n }\n\n var @ref = @params.Ref;\n var argument = @params.Argument;\n\n if (@ref is ResourceTemplateReference rtr)\n {\n var resourceId = rtr.Uri?.Split(\"/\").Last();\n\n if (resourceId is null)\n {\n return new CompleteResult();\n }\n\n var values = exampleCompletions[\"resourceId\"].Where(id => id.StartsWith(argument.Value));\n\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n if (@ref is PromptReference pr)\n {\n if (!exampleCompletions.TryGetValue(argument.Name, out IEnumerable? value))\n {\n throw new NotSupportedException($\"Unknown argument name: {argument.Name}\");\n }\n\n var values = value.Where(value => value.StartsWith(argument.Value));\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n throw new NotSupportedException($\"Unknown reference type: {@ref.Type}\");\n })\n .WithSetLoggingLevelHandler(async (ctx, ct) =>\n {\n if (ctx.Params?.Level is null)\n {\n throw new McpException(\"Missing required argument 'level'\", McpErrorCode.InvalidParams);\n }\n\n _minimumLoggingLevel = ctx.Params.Level;\n\n await ctx.Server.SendNotificationAsync(\"notifications/message\", new\n {\n Level = \"debug\",\n Logger = \"test-server\",\n Data = $\"Logging level set to {_minimumLoggingLevel}\",\n }, cancellationToken: ct);\n\n return new EmptyResult();\n });\n\nResourceBuilder resource = ResourceBuilder.CreateDefault().AddService(\"everything-server\");\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithMetrics(b => b.AddMeter(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithLogging(b => b.SetResourceBuilder(resource))\n .UseOtlpExporter();\n\nbuilder.Services.AddSingleton(subscriptions);\nbuilder.Services.AddHostedService();\nbuilder.Services.AddHostedService();\n\nbuilder.Services.AddSingleton>(_ => () => _minimumLoggingLevel);\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolAnnotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional properties describing a to clients.\n/// \n/// \n/// All properties in are hints.\n/// They are not guaranteed to provide a faithful description of tool behavior (including descriptive properties like `title`).\n/// Clients should never make tool use decisions based on received from untrusted servers.\n/// \npublic sealed class ToolAnnotations\n{\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"destructiveHint\")]\n public bool? DestructiveHint { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"idempotentHint\")]\n public bool? IdempotentHint { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"openWorldHint\")]\n public bool? OpenWorldHint { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"readOnlyHint\")]\n public bool? ReadOnlyHint { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StreamClientTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides an implemented around a pair of input/output streams.\n/// \n/// \n/// This transport is useful for scenarios where you already have established streams for communication,\n/// such as custom network protocols, pipe connections, or for testing purposes. It works with any\n/// readable and writable streams.\n/// \npublic sealed class StreamClientTransport : IClientTransport\n{\n private readonly Stream _serverInput;\n private readonly Stream _serverOutput;\n private readonly ILoggerFactory? _loggerFactory;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The stream representing the connected server's input. \n /// Writes to this stream will be sent to the server.\n /// \n /// \n /// The stream representing the connected server's output.\n /// Reads from this stream will receive messages from the server.\n /// \n /// A logger factory for creating loggers.\n public StreamClientTransport(\n Stream serverInput, Stream serverOutput, ILoggerFactory? loggerFactory = null)\n {\n Throw.IfNull(serverInput);\n Throw.IfNull(serverOutput);\n\n _serverInput = serverInput;\n _serverOutput = serverOutput;\n _loggerFactory = loggerFactory;\n }\n\n /// \n public string Name => \"in-memory-stream\";\n\n /// \n public Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n return Task.FromResult(new StreamClientSessionTransport(\n _serverInput,\n _serverOutput,\n encoding: null,\n \"Client (stream)\",\n _loggerFactory));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available tools.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available tools on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many tools.\n/// The server can provide the property to indicate there are more\n/// tools available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListToolsResult : PaginatedResult\n{\n /// \n /// The server's response to a tools/list request from the client.\n /// \n [JsonPropertyName(\"tools\")]\n public IList Tools { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client capability that enables root resource discovery in the Model Context Protocol.\n/// \n/// \n/// \n/// When present in , it indicates that the client supports listing\n/// root URIs that serve as entry points for resource navigation.\n/// \n/// \n/// The roots capability establishes a mechanism for servers to discover and access the hierarchical \n/// structure of resources provided by a client. Root URIs represent top-level entry points from which\n/// servers can navigate to access specific resources.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsCapability\n{\n /// \n /// Gets or sets whether the client supports notifications for changes to the roots list.\n /// \n /// \n /// When set to , the client can notify servers when roots are added, \n /// removed, or modified, allowing servers to refresh their roots cache accordingly.\n /// This enables servers to stay synchronized with client-side changes to available roots.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client sends a request to retrieve available roots.\n /// The handler receives request parameters and should return a containing the collection of available roots.\n /// \n [JsonIgnore]\n public Func>? RootsHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/IdleTrackingBackgroundService.cs", "using System.Runtime.InteropServices;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed partial class IdleTrackingBackgroundService(\n StreamableHttpHandler handler,\n IOptions options,\n IHostApplicationLifetime appLifetime,\n ILogger logger) : BackgroundService\n{\n // The compiler will complain about the parameter being unused otherwise despite the source generator.\n private readonly ILogger _logger = logger;\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n // Still run loop given infinite IdleTimeout to enforce the MaxIdleSessionCount and assist graceful shutdown.\n if (options.Value.IdleTimeout != Timeout.InfiniteTimeSpan)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.IdleTimeout, TimeSpan.Zero);\n }\n\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.MaxIdleSessionCount, 0);\n\n try\n {\n var timeProvider = options.Value.TimeProvider;\n using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);\n\n var idleTimeoutTicks = options.Value.IdleTimeout.Ticks;\n var maxIdleSessionCount = options.Value.MaxIdleSessionCount;\n\n // Create two lists that will be reused between runs.\n // This assumes that the number of idle sessions is not breached frequently.\n // If the idle sessions often breach the maximum, a priority queue could be considered.\n var idleSessionsTimestamps = new List();\n var idleSessionSessionIds = new List();\n\n while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))\n {\n var idleActivityCutoff = idleTimeoutTicks switch\n {\n < 0 => long.MinValue,\n var ticks => timeProvider.GetTimestamp() - ticks,\n };\n\n foreach (var (_, session) in handler.Sessions)\n {\n if (session.IsActive || session.SessionClosed.IsCancellationRequested)\n {\n // There's a request currently active or the session is already being closed.\n continue;\n }\n\n if (session.LastActivityTicks < idleActivityCutoff)\n {\n RemoveAndCloseSession(session.Id);\n continue;\n }\n\n // Add the timestamp and the session\n idleSessionsTimestamps.Add(session.LastActivityTicks);\n idleSessionSessionIds.Add(session.Id);\n\n // Emit critical log at most once every 5 seconds the idle count it exceeded,\n // since the IdleTimeout will no longer be respected.\n if (idleSessionsTimestamps.Count == maxIdleSessionCount + 1)\n {\n LogMaxSessionIdleCountExceeded(maxIdleSessionCount);\n }\n }\n\n if (idleSessionsTimestamps.Count > maxIdleSessionCount)\n {\n var timestamps = CollectionsMarshal.AsSpan(idleSessionsTimestamps);\n\n // Sort only if the maximum is breached and sort solely by the timestamp. Sort both collections.\n timestamps.Sort(CollectionsMarshal.AsSpan(idleSessionSessionIds));\n\n var sessionsToPrune = CollectionsMarshal.AsSpan(idleSessionSessionIds)[..^maxIdleSessionCount];\n foreach (var id in sessionsToPrune)\n {\n RemoveAndCloseSession(id);\n }\n }\n\n idleSessionsTimestamps.Clear();\n idleSessionSessionIds.Clear();\n }\n }\n catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)\n {\n }\n finally\n {\n try\n {\n List disposeSessionTasks = [];\n\n foreach (var (sessionKey, _) in handler.Sessions)\n {\n if (handler.Sessions.TryRemove(sessionKey, out var session))\n {\n disposeSessionTasks.Add(DisposeSessionAsync(session));\n }\n }\n\n await Task.WhenAll(disposeSessionTasks);\n }\n finally\n {\n if (!stoppingToken.IsCancellationRequested)\n {\n // Something went terribly wrong. A very unexpected exception must be bubbling up, but let's ensure we also stop the application,\n // so that it hopefully gets looked at and restarted. This shouldn't really be reachable.\n appLifetime.StopApplication();\n IdleTrackingBackgroundServiceStoppedUnexpectedly();\n }\n }\n }\n }\n\n private void RemoveAndCloseSession(string sessionId)\n {\n if (!handler.Sessions.TryRemove(sessionId, out var session))\n {\n return;\n }\n\n LogSessionIdle(session.Id);\n // Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown.\n _ = DisposeSessionAsync(session);\n }\n\n private async Task DisposeSessionAsync(HttpMcpSession session)\n {\n try\n {\n await session.DisposeAsync();\n }\n catch (Exception ex)\n {\n LogSessionDisposeError(session.Id, ex);\n }\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Closing idle session {sessionId}.\")]\n private partial void LogSessionIdle(string sessionId);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"Error disposing session {sessionId}.\")]\n private partial void LogSessionDisposeError(string sessionId, Exception ex);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"Exceeded maximum of {maxIdleSessionCount} idle sessions. Now closing sessions active more recently than configured IdleTimeout.\")]\n private partial void LogMaxSessionIdleCountExceeded(int maxIdleSessionCount);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"The IdleTrackingBackgroundService has stopped unexpectedly.\")]\n private partial void IdleTrackingBackgroundServiceStoppedUnexpectedly();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/IBaseMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// Provides a base interface for metadata with name (identifier) and title (display name) properties.\npublic interface IBaseMetadata\n{\n /// \n /// Gets or sets the unique identifier for this item.\n /// \n [JsonPropertyName(\"name\")]\n string Name { get; set; }\n\n /// \n /// Gets or sets a title.\n /// \n /// \n /// This is intended for UI and end-user contexts. It is optimized to be human-readable and easily understood,\n /// even by those unfamiliar with domain-specific terminology.\n /// If not provided, may be used for display (except for tools, where , if present, \n /// should be given precedence over using ).\n /// \n [JsonPropertyName(\"title\")]\n string? Title { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresDynamicCodeAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires the ability to generate new code at runtime,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when compiling ahead of time.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresDynamicCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of dynamic code.\n /// \n public RequiresDynamicCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of dynamic code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires dynamic code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/samples/EverythingServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test://direct/text/resource\", Name = \"Direct Text Resource\", MimeType = \"text/plain\")]\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n\n [McpServerResource(UriTemplate = \"test://template/resource/{id}\", Name = \"Template Resource\")]\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id)\n {\n int index = id - 1;\n if ((uint)index >= ResourceGenerator.Resources.Count)\n {\n throw new NotSupportedException($\"Unknown resource: {requestContext.Params?.Uri}\");\n }\n\n var resource = ResourceGenerator.Resources[index];\n return resource.MimeType == \"text/plain\" ?\n new TextResourceContents\n {\n Text = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n } :\n new BlobResourceContents\n {\n Blob = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Annotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents annotations that can be attached to content, resources, and resource templates.\n/// \n/// \n/// Annotations enable filtering and prioritization of content for different audiences.\n/// See the schema for details.\n/// \npublic sealed class Annotations\n{\n /// \n /// Gets or sets the intended audience for this content as an array of values.\n /// \n [JsonPropertyName(\"audience\")]\n public IList? Audience { get; init; }\n\n /// \n /// Gets or sets a value indicating how important this data is for operating the server.\n /// \n /// \n /// The value is a floating-point number between 0 and 1, where 0 represents the lowest priority\n /// 1 represents highest priority.\n /// \n [JsonPropertyName(\"priority\")]\n public float? Priority { get; init; }\n\n /// \n /// Gets or sets the moment the resource was last modified.\n /// \n /// \n /// The corresponding JSON should be an ISO 8601 formatted string (e.g., \\\"2025-01-12T15:00:58Z\\\").\n /// Examples: last activity timestamp in an open file, timestamp when the resource was attached, etc.\n /// \n [JsonPropertyName(\"lastModified\")]\n public DateTimeOffset? LastModified { get; set; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresUnreferencedCode.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires dynamic access to code that is not referenced\n/// statically, for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when removing unreferenced\n/// code from an application.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresUnreferencedCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of unreferenced code.\n /// \n public RequiresUnreferencedCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of unreferenced code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires unreferenced code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceUpdatedNotificationParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a subscribed resource changes.\n/// \n/// \n/// \n/// When a client subscribes to resource updates using , the server will\n/// send notifications with this payload whenever the subscribed resource is modified. These notifications\n/// allow clients to maintain synchronized state without needing to poll the server for changes.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceUpdatedNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the URI of the resource that was updated.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingCapability.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Client;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to generate text or other content using an AI model.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to sampling requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to generate content\n/// using an AI model. The client must set a to process these requests.\n/// \n/// \npublic sealed class SamplingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to generate content\n /// using an AI model. The client must set this property for the sampling capability to work.\n /// \n /// \n /// The handler receives message parameters, a progress reporter for updates, and a \n /// cancellation token. It should return a containing the \n /// generated content.\n /// \n /// \n /// You can create a handler using the extension\n /// method with any implementation of .\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SamplingHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource defined on an MCP server. It allows\n/// retrieving the resource's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResource\n{\n private readonly IMcpClient _client;\n\n internal McpClientResource(IMcpClient client, Resource resource)\n {\n _client = client;\n ProtocolResource = resource;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Resource ProtocolResource { get; }\n\n /// Gets the URI of the resource.\n public string Uri => ProtocolResource.Uri;\n\n /// Gets the name of the resource.\n public string Name => ProtocolResource.Name;\n\n /// Gets the title of the resource.\n public string? Title => ProtocolResource.Title;\n\n /// Gets a description of the resource.\n public string? Description => ProtocolResource.Description;\n\n /// Gets a media (MIME) type of the resource.\n public string? MimeType => ProtocolResource.MimeType;\n\n /// \n /// Gets this resource's content by sending a request to the server.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource's result with content and messages.\n /// \n /// \n /// This is a convenience method that internally calls .\n /// \n /// \n public ValueTask ReadAsync(\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(Uri, cancellationToken);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelHint.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides hints to use for model selection.\n/// \n/// \n/// \n/// When multiple hints are specified in , they are evaluated in order,\n/// with the first match taking precedence. Clients should prioritize these hints over numeric priorities.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelHint\n{\n /// \n /// Gets or sets a hint for a model name.\n /// \n /// \n /// The specified string can be a partial or full model name. Clients may also \n /// map hints to equivalent models from different providers. Clients make the final model\n /// selection based on these preferences and their available models.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n}"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/SampleLlmTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses dependency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n ChatOptions options = new()\n {\n Instructions = \"You are a helpful test server.\",\n MaxOutputTokens = maxTokens,\n Temperature = 0.7f,\n };\n\n var samplingResponse = await thisServer.AsSamplingChatClient().GetResponseAsync(prompt, options, cancellationToken);\n\n return $\"LLM sampling result: {samplingResponse}\";\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResourceTemplate.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource template that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource template defined on an MCP server. It allows\n/// retrieving the resource template's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResourceTemplate\n{\n private readonly IMcpClient _client;\n\n internal McpClientResourceTemplate(IMcpClient client, ResourceTemplate resourceTemplate)\n {\n _client = client;\n ProtocolResourceTemplate = resourceTemplate;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource template,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the URI template of the resource template.\n public string UriTemplate => ProtocolResourceTemplate.UriTemplate;\n\n /// Gets the name of the resource template.\n public string Name => ProtocolResourceTemplate.Name;\n\n /// Gets the title of the resource template.\n public string? Title => ProtocolResourceTemplate.Title;\n\n /// Gets a description of the resource template.\n public string? Description => ProtocolResourceTemplate.Description;\n\n /// Gets a media (MIME) type of the resource template.\n public string? MimeType => ProtocolResourceTemplate.MimeType;\n\n /// \n /// Gets this resource template's content by formatting a URI from the template and supplied arguments\n /// and sending a request to the server.\n /// \n /// A dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource template's result with content and messages.\n public ValueTask ReadAsync(\n IReadOnlyDictionary arguments,\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(UriTemplate, arguments, cancellationToken);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParamsMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides metadata related to the request that provides additional protocol-level information.\n/// \n/// \n/// This class contains properties that are used by the Model Context Protocol\n/// for features like progress tracking and other protocol-specific capabilities.\n/// \npublic sealed class RequestParamsMetadata\n{\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n /// \n /// The receiver is not obligated to provide these notifications.\n /// \n [JsonPropertyName(\"progressToken\")]\n public ProgressToken? ProgressToken { get; set; } = default!;\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.Core/Protocol/ElicitationCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to provide server-requested additional information during interactions.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to elicitation requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to provide additional information\n/// during interactions. The client must set a to process these requests.\n/// \n/// \npublic sealed class ElicitationCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to provide additional\n /// information during interactions. The client must set this property for the elicitation capability to work.\n /// \n /// \n /// The handler receives message parameters and a cancellation token.\n /// It should return a containing the response to the elicitation request.\n /// \n /// \n [JsonIgnore]\n public Func>? ElicitationHandler { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMembersAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that certain members on a specified are accessed dynamically,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which members are being accessed during the execution\n/// of a program.\n///\n/// This attribute is valid on members whose type is or .\n///\n/// When this attribute is applied to a location of type , the assumption is\n/// that the string represents a fully qualified type name.\n///\n/// When this attribute is applied to a class, interface, or struct, the members specified\n/// can be accessed dynamically on instances returned from calling\n/// on instances of that class, interface, or struct.\n///\n/// If the attribute is applied to a method it's treated as a special case and it implies\n/// the attribute should be applied to the \"this\" parameter of the method. As such the attribute\n/// should only be used on instance methods of types assignable to System.Type (or string, but no methods\n/// will use it there).\n/// \n[AttributeUsage(\n AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |\n AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |\n AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,\n Inherited = false)]\ninternal sealed class DynamicallyAccessedMembersAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified member types.\n /// \n /// The types of members dynamically accessed.\n public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)\n {\n MemberTypes = memberTypes;\n }\n\n /// \n /// Gets the which specifies the type\n /// of members dynamically accessed.\n /// \n public DynamicallyAccessedMemberTypes MemberTypes { get; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ProtectedResourceMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the resource metadata for OAuth authorization as defined in RFC 9396.\n/// Defined by RFC 9728.\n/// \npublic sealed class ProtectedResourceMetadata\n{\n /// \n /// The resource URI.\n /// \n /// \n /// REQUIRED. The protected resource's resource identifier.\n /// \n [JsonPropertyName(\"resource\")]\n public required Uri Resource { get; set; }\n\n /// \n /// The list of authorization server URIs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of OAuth authorization server issuer identifiers\n /// for authorization servers that can be used with this protected resource.\n /// \n [JsonPropertyName(\"authorization_servers\")]\n public List AuthorizationServers { get; set; } = [];\n\n /// \n /// The supported bearer token methods.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the supported methods of sending an OAuth 2.0 bearer token\n /// to the protected resource. Defined values are [\"header\", \"body\", \"query\"].\n /// \n [JsonPropertyName(\"bearer_methods_supported\")]\n public List BearerMethodsSupported { get; set; } = [\"header\"];\n\n /// \n /// The supported scopes.\n /// \n /// \n /// RECOMMENDED. JSON array containing a list of scope values that are used in authorization\n /// requests to request access to this protected resource.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List ScopesSupported { get; set; } = [];\n\n /// \n /// URL of the protected resource's JSON Web Key (JWK) Set document.\n /// \n /// \n /// OPTIONAL. This contains public keys belonging to the protected resource, such as signing key(s)\n /// that the resource server uses to sign resource responses. This URL MUST use the https scheme.\n /// \n [JsonPropertyName(\"jwks_uri\")]\n public Uri? JwksUri { get; set; }\n\n /// \n /// List of the JWS signing algorithms supported by the protected resource for signing resource responses.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS signing algorithms (alg values) supported by the protected resource\n /// for signing resource responses. No default algorithms are implied if this entry is omitted. The value none MUST NOT be used.\n /// \n [JsonPropertyName(\"resource_signing_alg_values_supported\")]\n public List? ResourceSigningAlgValuesSupported { get; set; }\n\n /// \n /// Human-readable name of the protected resource intended for display to the end user.\n /// \n /// \n /// RECOMMENDED. It is recommended that protected resource metadata include this field.\n /// The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_name\")]\n public string? ResourceName { get; set; }\n\n /// \n /// The URI to the resource documentation.\n /// \n /// \n /// OPTIONAL. URL of a page containing human-readable information that developers might want or need to know\n /// when using the protected resource.\n /// \n [JsonPropertyName(\"resource_documentation\")]\n public Uri? ResourceDocumentation { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's requirements.\n /// \n /// \n /// OPTIONAL. Information about how the client can use the data provided by the protected resource.\n /// \n [JsonPropertyName(\"resource_policy_uri\")]\n public Uri? ResourcePolicyUri { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's terms of service.\n /// \n /// \n /// OPTIONAL. The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_tos_uri\")]\n public Uri? ResourceTosUri { get; set; }\n\n /// \n /// Boolean value indicating protected resource support for mutual-TLS client certificate-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"tls_client_certificate_bound_access_tokens\")]\n public bool? TlsClientCertificateBoundAccessTokens { get; set; }\n\n /// \n /// List of the authorization details type values supported by the resource server.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the authorization details type values supported by the resource server\n /// when the authorization_details request parameter is used.\n /// \n [JsonPropertyName(\"authorization_details_types_supported\")]\n public List? AuthorizationDetailsTypesSupported { get; set; }\n\n /// \n /// List of the JWS algorithm values supported by the resource server for validating DPoP proof JWTs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS alg values supported by the resource server\n /// for validating Demonstrating Proof of Possession (DPoP) proof JWTs.\n /// \n [JsonPropertyName(\"dpop_signing_alg_values_supported\")]\n public List? DpopSigningAlgValuesSupported { get; set; }\n\n /// \n /// Boolean value specifying whether the protected resource always requires the use of DPoP-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"dpop_bound_access_tokens_required\")]\n public bool? DpopBoundAccessTokensRequired { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/UriTemplate.cs", "#if NET\nusing System.Buffers;\n#endif\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol;\n\n/// Provides basic support for parsing and formatting URI templates.\n/// \n/// This implementation should correctly handle valid URI templates, but it has undefined output for invalid templates,\n/// e.g. it may treat portions of invalid templates as literals rather than throwing.\n/// \ninternal static partial class UriTemplate\n{\n /// Regex pattern for finding URI template expressions and parsing out the operator and varname.\n private const string UriTemplateExpressionPattern = \"\"\"\n { # opening brace\n (?[+#./;?&]?) # optional operator\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}) # varchar: letter, digit, underscore, or pct-encoded\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))* # optionally dot-separated subsequent varchars\n )\n (?: :[1-9][0-9]{0,3} )? # optional prefix modifier (1–4 digits)\n \\*? # optional explode\n (?:, # comma separator, followed by the same as above\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*\n )\n (?: :[1-9][0-9]{0,3} )?\n \\*?\n )* # zero or more additional vars\n } # closing brace\n \"\"\";\n\n /// Gets a regex for finding URI template expressions and parsing out the operator and varname.\n /// \n /// This regex is for parsing a static URI template.\n /// It is not for parsing a URI according to a template.\n /// \n#if NET\n [GeneratedRegex(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace)]\n private static partial Regex UriTemplateExpression();\n#else\n private static Regex UriTemplateExpression() => s_uriTemplateExpression;\n private static readonly Regex s_uriTemplateExpression = new(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n#endif\n\n#if NET\n /// SearchValues for characters that needn't be escaped when allowing reserved characters.\n private static readonly SearchValues s_appendWhenAllowReserved = SearchValues.Create(\n \"abcdefghijklmnopqrstuvwxyz\" + // ASCII lowercase letters\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" + // ASCII uppercase letters\n \"0123456789\" + // ASCII digits\n \"-._~\" + // unreserved characters\n \":/?#[]@!$&'()*+,;=\"); // reserved characters\n#endif\n\n /// Create a for matching a URI against a URI template.\n /// The template against which to match.\n /// A regex pattern that can be used to match the specified URI template.\n public static Regex CreateParser(string uriTemplate)\n {\n DefaultInterpolatedStringHandler pattern = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n pattern.AppendFormatted('^');\n\n int lastIndex = 0;\n for (Match m = UriTemplateExpression().Match(uriTemplate); m.Success; m = m.NextMatch())\n {\n pattern.AppendFormatted(Regex.Escape(uriTemplate[lastIndex..m.Index]));\n lastIndex = m.Index + m.Length;\n\n var captures = m.Groups[\"varname\"].Captures;\n List paramNames = new(captures.Count);\n foreach (Capture c in captures)\n {\n paramNames.Add(c.Value);\n }\n\n switch (m.Groups[\"operator\"].Value)\n {\n case \"#\": AppendExpression(ref pattern, paramNames, '#', \"[^,]+\"); break;\n case \"/\": AppendExpression(ref pattern, paramNames, '/', \"[^/?]+\"); break;\n default: AppendExpression(ref pattern, paramNames, null, \"[^/?&]+\"); break;\n \n case \"?\": AppendQueryExpression(ref pattern, paramNames, '?'); break;\n case \"&\": AppendQueryExpression(ref pattern, paramNames, '&'); break;\n }\n }\n\n pattern.AppendFormatted(Regex.Escape(uriTemplate.Substring(lastIndex)));\n pattern.AppendFormatted('$');\n\n return new Regex(\n pattern.ToStringAndClear(),\n RegexOptions.IgnoreCase | RegexOptions.CultureInvariant |\n#if NET\n RegexOptions.NonBacktracking);\n#else\n RegexOptions.Compiled, TimeSpan.FromSeconds(10));\n#endif\n\n // Appends a regex fragment to `pattern` that matches an optional query string starting\n // with the given `prefix` (? or &), and up to one occurrence of each name in\n // `paramNames`. Each parameter is made optional and captured by a named group\n // of the form “paramName=value”.\n static void AppendQueryExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char prefix)\n {\n Debug.Assert(prefix is '?' or '&');\n\n pattern.AppendFormatted(\"(?:\\\\\");\n pattern.AppendFormatted(prefix);\n\n if (paramNames.Count > 0)\n {\n AppendParameter(ref pattern, paramNames[0]);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\&?\");\n AppendParameter(ref pattern, paramNames[i]);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName)\n {\n paramName = Regex.Escape(paramName);\n pattern.AppendFormatted(\"(?:\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\"=(?<\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\">[^/?&]+))?\");\n }\n }\n\n pattern.AppendFormatted(\")?\");\n }\n\n // Chooses a regex character‐class (`valueChars`) based on the initial `prefix` to define which\n // characters make up a parameter value. Then, for each name in `paramNames`, it optionally\n // appends the escaped `prefix` (only on the first parameter, then switches to ','), and\n // adds an optional named capture group `(?valueChars)` to match and capture that value.\n static void AppendExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char? prefix, string valueChars)\n {\n Debug.Assert(prefix is '#' or '/' or null);\n\n if (paramNames.Count > 0)\n {\n if (prefix is not null)\n {\n pattern.AppendFormatted('\\\\');\n pattern.AppendFormatted(prefix);\n pattern.AppendFormatted('?');\n }\n\n AppendParameter(ref pattern, paramNames[0], valueChars);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\,?\");\n AppendParameter(ref pattern, paramNames[i], valueChars);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName, string valueChars)\n {\n pattern.AppendFormatted(\"(?<\");\n pattern.AppendFormatted(Regex.Escape(paramName));\n pattern.AppendFormatted('>');\n pattern.AppendFormatted(valueChars);\n pattern.AppendFormatted(\")?\");\n }\n }\n }\n }\n\n /// \n /// Expand a URI template using the given variable values.\n /// \n public static string FormatUri(string uriTemplate, IReadOnlyDictionary arguments)\n {\n Throw.IfNull(uriTemplate);\n\n ReadOnlySpan uriTemplateSpan = uriTemplate.AsSpan();\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n while (!uriTemplateSpan.IsEmpty)\n {\n // Find the next expression.\n int openBracePos = uriTemplateSpan.IndexOf('{');\n if (openBracePos < 0)\n {\n if (uriTemplate.Length == uriTemplateSpan.Length)\n {\n return uriTemplate;\n }\n\n builder.AppendFormatted(uriTemplateSpan);\n break;\n }\n\n // Append as a literal everything before the next expression.\n builder.AppendFormatted(uriTemplateSpan.Slice(0, openBracePos));\n uriTemplateSpan = uriTemplateSpan.Slice(openBracePos + 1);\n\n int closeBracePos = uriTemplateSpan.IndexOf('}');\n if (closeBracePos < 0)\n {\n throw new FormatException($\"Unmatched '{{' in URI template '{uriTemplate}'\");\n }\n\n ReadOnlySpan expression = uriTemplateSpan.Slice(0, closeBracePos);\n uriTemplateSpan = uriTemplateSpan.Slice(closeBracePos + 1);\n if (expression.IsEmpty)\n {\n continue;\n }\n\n // The start of the expression may be a modifier; if it is, slice it off the expression.\n char modifier = expression[0];\n (string Prefix, string Separator, bool Named, bool IncludeNameIfEmpty, bool IncludeSeparatorIfEmpty, bool AllowReserved, bool PrefixEmptyExpansions, int ExpressionSlice) modifierBehavior = modifier switch\n {\n '+' => (string.Empty, \",\", false, false, true, true, false, 1),\n '#' => (\"#\", \",\", false, false, true, true, true, 1),\n '.' => (\".\", \".\", false, false, true, false, true, 1),\n '/' => (\"/\", \"/\", false, false, true, false, false, 1),\n ';' => (\";\", \";\", true, true, false, false, false, 1),\n '?' => (\"?\", \"&\", true, true, true, false, false, 1),\n '&' => (\"&\", \"&\", true, true, true, false, false, 1),\n _ => (string.Empty, \",\", false, false, true, false, false, 0),\n };\n expression = expression.Slice(modifierBehavior.ExpressionSlice);\n\n List expansions = [];\n\n // Process each varspec in the comma-delimited list in the expression (if it doesn't have any\n // commas, it will be the whole expression).\n while (!expression.IsEmpty)\n {\n // Find the next name.\n int commaPos = expression.IndexOf(',');\n ReadOnlySpan name;\n if (commaPos < 0)\n {\n name = expression;\n expression = ReadOnlySpan.Empty;\n }\n else\n {\n name = expression.Slice(0, commaPos);\n expression = expression.Slice(commaPos + 1);\n }\n\n bool explode = false;\n int prefixLength = -1;\n\n // If the name ends with a *, it means we should explode the value into separate\n // name=value pairs. If it has a colon, it means we should only take the first N characters\n // of the value. If it has both, the * takes precedence and we ignore the colon.\n if (!name.IsEmpty && name[name.Length - 1] == '*')\n {\n explode = true;\n name = name.Slice(0, name.Length - 1);\n }\n else if (name.IndexOf(':') >= 0)\n {\n int colonPos = name.IndexOf(':');\n if (colonPos < 0)\n {\n throw new FormatException($\"Invalid varspec '{name.ToString()}'\");\n }\n\n if (!int.TryParse(name.Slice(colonPos + 1)\n#if !NET\n .ToString()\n#endif\n , out prefixLength))\n {\n throw new FormatException($\"Invalid prefix length in varspec '{name.ToString()}'\");\n }\n\n name = name.Slice(0, colonPos);\n }\n\n // Look up the value for this name. If it doesn't exist, skip it.\n string nameString = name.ToString();\n if (!arguments.TryGetValue(nameString, out var value) || value is null)\n {\n continue;\n }\n\n if (value is IEnumerable list)\n {\n var items = list.Select(i => Encode(i, modifierBehavior.AllowReserved));\n if (explode)\n {\n if (modifierBehavior.Named)\n {\n foreach (var item in items)\n {\n expansions.Add($\"{nameString}={item}\");\n }\n }\n else\n {\n foreach (var item in items)\n {\n expansions.Add(item);\n }\n }\n }\n else\n {\n var joined = string.Join(\",\", items);\n expansions.Add(joined.Length > 0 && modifierBehavior.Named ?\n $\"{nameString}={joined}\" :\n joined);\n }\n }\n else if (value is IReadOnlyDictionary assoc)\n {\n var pairs = assoc.Select(kvp => (\n Encode(kvp.Key, modifierBehavior.AllowReserved),\n Encode(kvp.Value, modifierBehavior.AllowReserved)\n ));\n\n if (explode)\n {\n foreach (var (k, v) in pairs)\n {\n expansions.Add($\"{k}={v}\");\n }\n }\n else\n {\n var joined = string.Join(\",\", pairs.Select(p => $\"{p.Item1},{p.Item2}\"));\n if (joined.Length > 0)\n {\n expansions.Add(modifierBehavior.Named ? $\"{nameString}={joined}\" : joined);\n }\n }\n }\n else\n {\n string s =\n value as string ??\n (value is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) : value.ToString()) ??\n string.Empty;\n\n s = Encode((uint)prefixLength < s.Length ? s.Substring(0, prefixLength) : s, modifierBehavior.AllowReserved);\n if (!modifierBehavior.Named)\n {\n expansions.Add(s);\n }\n else if (s.Length != 0 || modifierBehavior.IncludeNameIfEmpty)\n {\n expansions.Add(\n s.Length != 0 ? $\"{nameString}={s}\" :\n modifierBehavior.IncludeSeparatorIfEmpty ? $\"{nameString}=\" :\n nameString);\n }\n }\n }\n\n if (expansions.Count > 0 && \n (modifierBehavior.PrefixEmptyExpansions || !expansions.All(string.IsNullOrEmpty)))\n {\n builder.AppendLiteral(modifierBehavior.Prefix);\n AppendJoin(ref builder, modifierBehavior.Separator, expansions);\n }\n }\n\n return builder.ToStringAndClear();\n }\n\n private static void AppendJoin(ref DefaultInterpolatedStringHandler builder, string separator, IList values)\n {\n int count = values.Count;\n if (count > 0)\n {\n builder.AppendLiteral(values[0]);\n for (int i = 1; i < count; i++)\n {\n builder.AppendLiteral(separator);\n builder.AppendLiteral(values[i]);\n }\n }\n }\n\n private static string Encode(string value, bool allowReserved)\n {\n if (!allowReserved)\n {\n return Uri.EscapeDataString(value);\n }\n\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n int i = 0;\n#if NET\n i = value.AsSpan().IndexOfAnyExcept(s_appendWhenAllowReserved);\n if (i < 0)\n {\n return value;\n }\n\n builder.AppendFormatted(value.AsSpan(0, i));\n#endif\n\n for (; i < value.Length; ++i)\n {\n char c = value[i];\n if (((uint)((c | 0x20) - 'a') <= 'z' - 'a') ||\n ((uint)(c - '0') <= '9' - '0') ||\n \"-._~:/?#[]@!$&'()*+,;=\".Contains(c))\n {\n builder.AppendFormatted(c);\n }\n else if (c == '%' && i < value.Length - 2 && Uri.IsHexDigit(value[i + 1]) && Uri.IsHexDigit(value[i + 2]))\n {\n builder.AppendFormatted(value.AsSpan(i, 3));\n i += 2;\n }\n else\n {\n AppendHex(ref builder, c);\n }\n }\n\n return builder.ToStringAndClear();\n\n static void AppendHex(ref DefaultInterpolatedStringHandler builder, char c)\n {\n ReadOnlySpan hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];\n\n if (c <= 0x7F)\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[c >> 4]);\n builder.AppendFormatted(hexDigits[c & 0xF]);\n }\n else\n {\n#if NET\n Span utf8 = stackalloc byte[Encoding.UTF8.GetMaxByteCount(1)];\n foreach (byte b in utf8.Slice(0, new Rune(c).EncodeToUtf8(utf8)))\n#else\n foreach (byte b in Encoding.UTF8.GetBytes([c]))\n#endif\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[b >> 4]);\n builder.AppendFormatted(hexDigits[b & 0xF]);\n }\n }\n }\n }\n\n /// \n /// Defines an equality comparer for Uri templates as follows:\n /// 1. Non-templated Uris use regular System.Uri equality comparison (host name is case insensitive).\n /// 2. Templated Uris use regular string equality.\n /// \n /// We do this because non-templated resources are looked up directly from the resource dictionary\n /// and we need to make sure equality is implemented correctly. Templated Uris are resolved in a\n /// fallback step using linear traversal of the resource dictionary, so their equality is only\n /// there to distinguish between different templates.\n /// \n public sealed class UriTemplateComparer : IEqualityComparer\n {\n public static IEqualityComparer Instance { get; } = new UriTemplateComparer();\n\n public bool Equals(string? uriTemplate1, string? uriTemplate2)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate1, out Uri? uri1) &&\n TryParseAsNonTemplatedUri(uriTemplate2, out Uri? uri2))\n {\n return uri1 == uri2;\n }\n\n return string.Equals(uriTemplate1, uriTemplate2, StringComparison.Ordinal);\n }\n\n public int GetHashCode([DisallowNull] string uriTemplate)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate, out Uri? uri))\n {\n return uri.GetHashCode();\n }\n else\n {\n return StringComparer.Ordinal.GetHashCode(uriTemplate);\n }\n }\n\n private static bool TryParseAsNonTemplatedUri(string? uriTemplate, [NotNullWhen(true)] out Uri? uri)\n {\n if (uriTemplate is null || uriTemplate.Contains('{'))\n {\n uri = null;\n return false;\n }\n\n return Uri.TryCreate(uriTemplate, UriKind.Absolute, out uri);\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelPreferences.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's preferences for model selection, requested of the client during sampling.\n/// \n/// \n/// \n/// Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n/// rarely straightforward. Different models excel in different areas—some are\n/// faster but less capable, others are more capable but more expensive, and so\n/// on. This class allows servers to express their priorities across multiple\n/// dimensions to help clients make an appropriate selection for their use case.\n/// \n/// \n/// These preferences are always advisory. The client may ignore them. It is also\n/// up to the client to decide how to interpret these preferences and how to\n/// balance them against other considerations.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelPreferences\n{\n /// \n /// Gets or sets how much to prioritize cost when selecting a model.\n /// \n /// \n /// A value of 0 means cost is not important, while a value of 1 means cost is the most important factor.\n /// \n [JsonPropertyName(\"costPriority\")]\n public float? CostPriority { get; init; }\n\n /// \n /// Gets or sets optional hints to use for model selection.\n /// \n [JsonPropertyName(\"hints\")]\n public IReadOnlyList? Hints { get; init; }\n\n /// \n /// Gets or sets how much to prioritize sampling speed (latency) when selecting a model.\n /// \n /// \n /// A value of 0 means speed is not important, while a value of 1 means speed is the most important factor.\n /// \n [JsonPropertyName(\"speedPriority\")]\n public float? SpeedPriority { get; init; }\n\n /// \n /// Gets or sets how much to prioritize intelligence and capabilities when selecting a model.\n /// \n /// \n /// A value of 0 means intelligence is not important, while a value of 1 means intelligence is the most important factor.\n /// \n [JsonPropertyName(\"intelligencePriority\")]\n public float? IntelligencePriority { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ClientOAuthOptions.cs", "namespace ModelContextProtocol.Authentication;\n\n/// \n/// Provides configuration options for the .\n/// \npublic sealed class ClientOAuthOptions\n{\n /// \n /// Gets or sets the OAuth redirect URI.\n /// \n public required Uri RedirectUri { get; set; }\n\n /// \n /// Gets or sets the OAuth client ID. If not provided, the client will attempt to register dynamically.\n /// \n public string? ClientId { get; set; }\n\n /// \n /// Gets or sets the OAuth client secret.\n /// \n /// \n /// This is optional for public clients or when using PKCE without client authentication.\n /// \n public string? ClientSecret { get; set; }\n\n /// \n /// Gets or sets the OAuth scopes to request.\n /// \n /// \n /// \n /// When specified, these scopes will be used instead of the scopes advertised by the protected resource.\n /// If not specified, the provider will use the scopes from the protected resource metadata.\n /// \n /// \n /// Common OAuth scopes include \"openid\", \"profile\", \"email\", etc.\n /// \n /// \n public IEnumerable? Scopes { get; set; }\n\n /// \n /// Gets or sets the authorization redirect delegate for handling the OAuth authorization flow.\n /// \n /// \n /// \n /// This delegate is responsible for handling the OAuth authorization URL and obtaining the authorization code.\n /// If not specified, a default implementation will be used that prompts the user to enter the code manually.\n /// \n /// \n /// Custom implementations might open a browser, start an HTTP listener, or use other mechanisms to capture\n /// the authorization code from the OAuth redirect.\n /// \n /// \n public AuthorizationRedirectDelegate? AuthorizationRedirectDelegate { get; set; }\n\n /// \n /// Gets or sets the authorization server selector function.\n /// \n /// \n /// \n /// This function is used to select which authorization server to use when multiple servers are available.\n /// If not specified, the first available server will be selected.\n /// \n /// \n /// The function receives a list of available authorization server URIs and should return the selected server,\n /// or null if no suitable server is found.\n /// \n /// \n public Func, Uri?>? AuthServerSelector { get; set; }\n\n /// \n /// Gets or sets the client name to use during dynamic client registration.\n /// \n /// \n /// This is a human-readable name for the client that may be displayed to users during authorization.\n /// Only used when a is not specified.\n /// \n public string? ClientName { get; set; }\n\n /// \n /// Gets or sets the client URI to use during dynamic client registration.\n /// \n /// \n /// This should be a URL pointing to the client's home page or information page.\n /// Only used when a is not specified.\n /// \n public Uri? ClientUri { get; set; }\n\n /// \n /// Gets or sets additional parameters to include in the query string of the OAuth authorization request\n /// providing extra information or fulfilling specific requirements of the OAuth provider.\n /// \n /// \n /// \n /// Parameters specified cannot override or append to any automatically set parameters like the \"redirect_uri\"\n /// which should instead be configured via .\n /// \n /// \n public IDictionary AdditionalAuthorizationParameters { get; set; } = new Dictionary();\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace QuickstartWeatherServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public static async Task GetAlerts(\n HttpClient client,\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public static async Task GetForecast(\n HttpClient client,\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Implementation.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides the name and version of an MCP implementation.\n/// \n/// \n/// \n/// The class is used to identify MCP clients and servers during the initialization handshake.\n/// It provides version and name information that can be used for compatibility checks, logging, and debugging.\n/// \n/// \n/// Both clients and servers provide this information during connection establishment.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class Implementation : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the version of the implementation.\n /// \n /// \n /// The version is used during client-server handshake to identify implementation versions,\n /// which can be important for troubleshooting compatibility issues or when reporting bugs.\n /// \n [JsonPropertyName(\"version\")]\n public required string Version { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides configuration options for the MCP server.\n/// \npublic sealed class McpServerOptions\n{\n /// \n /// Gets or sets information about this server implementation, including its name and version.\n /// \n /// \n /// This information is sent to the client during initialization to identify the server.\n /// It's displayed in client logs and can be used for debugging and compatibility checks.\n /// \n public Implementation? ServerInfo { get; set; }\n\n /// \n /// Gets or sets server capabilities to advertise to the client.\n /// \n /// \n /// These determine which features will be available when a client connects.\n /// Capabilities can include \"tools\", \"prompts\", \"resources\", \"logging\", and other \n /// protocol-specific functionality.\n /// \n public ServerCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version supported by this server, using a date-based versioning scheme.\n /// \n /// \n /// The protocol version defines which features and message formats this server supports.\n /// This uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// If , the server will advertize to the client the version requested\n /// by the client if that version is known to be supported, and otherwise will advertize the latest\n /// version supported by the server.\n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout used for the client-server initialization handshake sequence.\n /// \n /// \n /// This timeout determines how long the server will wait for client responses during\n /// the initialization protocol handshake. If the client doesn't respond within this timeframe,\n /// the initialization process will be aborted.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n\n /// \n /// Gets or sets optional server instructions to send to clients.\n /// \n /// \n /// These instructions are sent to clients during the initialization handshake and provide\n /// guidance on how to effectively use the server's capabilities. They can include details\n /// about available tools, expected input formats, limitations, or other helpful information.\n /// Client applications typically use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n public string? ServerInstructions { get; set; }\n\n /// \n /// Gets or sets whether to create a new service provider scope for each handled request.\n /// \n /// \n /// The default is . When , each invocation of a request\n /// handler will be invoked within a new service scope.\n /// \n public bool ScopeRequests { get; set; } = true;\n\n /// \n /// Gets or sets preexisting knowledge about the client including its name and version to help support\n /// stateless Streamable HTTP servers that encode this knowledge in the mcp-session-id header.\n /// \n /// \n /// \n /// When not specified, this information is sourced from the client's initialize request.\n /// \n /// \n public Implementation? KnownClientInfo { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides configuration options for creating instances.\n/// \n/// \n/// These options are typically passed to when creating a client.\n/// They define client capabilities, protocol version, and other client-specific settings.\n/// \npublic sealed class McpClientOptions\n{\n /// \n /// Gets or sets information about this client implementation, including its name and version.\n /// \n /// \n /// \n /// This information is sent to the server during initialization to identify the client.\n /// It's often displayed in server logs and can be used for debugging and compatibility checks.\n /// \n /// \n /// When not specified, information sourced from the current process will be used.\n /// \n /// \n public Implementation? ClientInfo { get; set; }\n\n /// \n /// Gets or sets the client capabilities to advertise to the server.\n /// \n public ClientCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version to request from the server, using a date-based versioning scheme.\n /// \n /// \n /// \n /// The protocol version is a key part of the initialization handshake. The client and server must \n /// agree on a compatible protocol version to communicate successfully.\n /// \n /// \n /// If non-, this version will be sent to the server, and the handshake\n /// will fail if the version in the server's response does not match this version.\n /// If , the client will request the latest version supported by the server\n /// but will allow any supported version that the server advertizes in its response.\n /// \n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout for the client-server initialization handshake sequence.\n /// \n /// \n /// \n /// This timeout determines how long the client will wait for the server to respond during\n /// the initialization protocol handshake. If the server doesn't respond within this timeframe,\n /// an exception will be thrown.\n /// \n /// \n /// Setting an appropriate timeout prevents the client from hanging indefinitely when\n /// connecting to unresponsive servers.\n /// \n /// The default value is 60 seconds.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StdioServerTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implemented via \"stdio\" (standard input/output).\n/// \npublic sealed class StdioServerTransport : StreamServerTransport\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The server options.\n /// Optional logger factory used for logging employed by the transport.\n /// is or contains a null name.\n public StdioServerTransport(McpServerOptions serverOptions, ILoggerFactory? loggerFactory = null)\n : this(GetServerName(serverOptions), loggerFactory: loggerFactory)\n {\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the server.\n /// Optional logger factory used for logging employed by the transport.\n /// is .\n public StdioServerTransport(string serverName, ILoggerFactory? loggerFactory = null)\n : base(new CancellableStdinStream(Console.OpenStandardInput()),\n new BufferedStream(Console.OpenStandardOutput()),\n serverName ?? throw new ArgumentNullException(nameof(serverName)),\n loggerFactory)\n {\n }\n\n private static string GetServerName(McpServerOptions serverOptions)\n {\n Throw.IfNull(serverOptions);\n\n return serverOptions.ServerInfo?.Name ?? McpServer.DefaultImplementation.Name;\n }\n\n // Neither WindowsConsoleStream nor UnixConsoleStream respect CancellationTokens or cancel any I/O on Dispose.\n // WindowsConsoleStream will return an EOS on Ctrl-C, but that is not the only reason the shutdownToken may fire.\n private sealed class CancellableStdinStream(Stream stdinStream) : Stream\n {\n public override bool CanRead => true;\n public override bool CanSeek => false;\n public override bool CanWrite => false;\n\n public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n => stdinStream.ReadAsync(buffer, offset, count, cancellationToken).WaitAsync(cancellationToken);\n\n#if NET\n public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)\n {\n ValueTask vt = stdinStream.ReadAsync(buffer, cancellationToken);\n return vt.IsCompletedSuccessfully ? vt : new(vt.AsTask().WaitAsync(cancellationToken));\n }\n#endif\n\n // The McpServer shouldn't call flush on the stdin Stream, but it doesn't need to throw just in case.\n public override void Flush() { }\n\n public override long Length => throw new NotSupportedException();\n\n public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }\n\n public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();\n\n public override void SetLength(long value) => throw new NotSupportedException();\n public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n }\n}\n"], ["/csharp-sdk/src/Common/CancellableStreamReader/ValueStringBuilder.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.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n#nullable enable\n\nnamespace System.Text\n{\n internal ref partial struct ValueStringBuilder\n {\n private char[]? _arrayToReturnToPool;\n private Span _chars;\n private int _pos;\n\n public ValueStringBuilder(Span initialBuffer)\n {\n _arrayToReturnToPool = null;\n _chars = initialBuffer;\n _pos = 0;\n }\n\n public ValueStringBuilder(int initialCapacity)\n {\n _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity);\n _chars = _arrayToReturnToPool;\n _pos = 0;\n }\n\n public int Length\n {\n get => _pos;\n set\n {\n Debug.Assert(value >= 0);\n Debug.Assert(value <= _chars.Length);\n _pos = value;\n }\n }\n\n public int Capacity => _chars.Length;\n\n public void EnsureCapacity(int capacity)\n {\n // This is not expected to be called this with negative capacity\n Debug.Assert(capacity >= 0);\n\n // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.\n if ((uint)capacity > (uint)_chars.Length)\n Grow(capacity - _pos);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// Does not ensure there is a null char after \n /// This overload is pattern matched in the C# 7.3+ compiler so you can omit\n /// the explicit method call, and write eg \"fixed (char* c = builder)\"\n /// \n public ref char GetPinnableReference()\n {\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// \n /// Ensures that the builder has a null char after \n public ref char GetPinnableReference(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n public ref char this[int index]\n {\n get\n {\n Debug.Assert(index < _pos);\n return ref _chars[index];\n }\n }\n\n public override string ToString()\n {\n string s = _chars.Slice(0, _pos).ToString();\n Dispose();\n return s;\n }\n\n /// Returns the underlying storage of the builder.\n public Span RawChars => _chars;\n\n /// \n /// Returns a span around the contents of the builder.\n /// \n /// Ensures that the builder has a null char after \n public ReadOnlySpan AsSpan(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return _chars.Slice(0, _pos);\n }\n\n public ReadOnlySpan AsSpan() => _chars.Slice(0, _pos);\n public ReadOnlySpan AsSpan(int start) => _chars.Slice(start, _pos - start);\n public ReadOnlySpan AsSpan(int start, int length) => _chars.Slice(start, length);\n\n public bool TryCopyTo(Span destination, out int charsWritten)\n {\n if (_chars.Slice(0, _pos).TryCopyTo(destination))\n {\n charsWritten = _pos;\n Dispose();\n return true;\n }\n else\n {\n charsWritten = 0;\n Dispose();\n return false;\n }\n }\n\n public void Insert(int index, char value, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n _chars.Slice(index, count).Fill(value);\n _pos += count;\n }\n\n public void Insert(int index, string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int count = s.Length;\n\n if (_pos > (_chars.Length - count))\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(index));\n _pos += count;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(char c)\n {\n int pos = _pos;\n Span chars = _chars;\n if ((uint)pos < (uint)chars.Length)\n {\n chars[pos] = c;\n _pos = pos + 1;\n }\n else\n {\n GrowAndAppend(c);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int pos = _pos;\n if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.\n {\n _chars[pos] = s[0];\n _pos = pos + 1;\n }\n else\n {\n AppendSlow(s);\n }\n }\n\n private void AppendSlow(string s)\n {\n int pos = _pos;\n if (pos > _chars.Length - s.Length)\n {\n Grow(s.Length);\n }\n\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(pos));\n _pos += s.Length;\n }\n\n public void Append(char c, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n Span dst = _chars.Slice(_pos, count);\n for (int i = 0; i < dst.Length; i++)\n {\n dst[i] = c;\n }\n _pos += count;\n }\n\n public void Append(scoped ReadOnlySpan value)\n {\n int pos = _pos;\n if (pos > _chars.Length - value.Length)\n {\n Grow(value.Length);\n }\n\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public Span AppendSpan(int length)\n {\n int origPos = _pos;\n if (origPos > _chars.Length - length)\n {\n Grow(length);\n }\n\n _pos = origPos + length;\n return _chars.Slice(origPos, length);\n }\n\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowAndAppend(char c)\n {\n Grow(1);\n Append(c);\n }\n\n /// \n /// Resize the internal buffer either by doubling current buffer size or\n /// by adding to\n /// whichever is greater.\n /// \n /// \n /// Number of chars requested beyond current position.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void Grow(int additionalCapacityBeyondPos)\n {\n Debug.Assert(additionalCapacityBeyondPos > 0);\n Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, \"Grow called incorrectly, no resize is needed.\");\n\n const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength\n\n // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try\n // to double the size if possible, bounding the doubling to not go beyond the max array length.\n int newCapacity = (int)Math.Max(\n (uint)(_pos + additionalCapacityBeyondPos),\n Math.Min((uint)_chars.Length * 2, ArrayMaxLength));\n\n // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.\n // This could also go negative if the actual required length wraps around.\n char[] poolArray = ArrayPool.Shared.Rent(newCapacity);\n\n _chars.Slice(0, _pos).CopyTo(poolArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = poolArray;\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Dispose()\n {\n char[]? toReturn = _arrayToReturnToPool;\n this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IClientTransport.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a transport mechanism for Model Context Protocol (MCP) client-to-server communication.\n/// \n/// \n/// \n/// The interface abstracts the communication layer between MCP clients\n/// and servers, allowing different transport protocols to be used interchangeably.\n/// \n/// \n/// When creating an , is typically used, and is\n/// provided with the based on expected server configuration.\n/// \n/// \npublic interface IClientTransport\n{\n /// \n /// Gets a transport identifier, used for logging purposes.\n /// \n string Name { get; }\n\n /// \n /// Asynchronously establishes a transport session with an MCP server and returns a transport for the duplex message stream.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// Returns an interface for the duplex message stream.\n /// \n /// \n /// This method is responsible for initializing the connection to the server using the specific transport \n /// mechanism implemented by the derived class. The returned interface \n /// provides methods to send and receive messages over the established connection.\n /// \n /// \n /// The lifetime of the returned instance is typically managed by the \n /// that uses this transport. When the client is disposed, it will dispose\n /// the transport session as well.\n /// \n /// \n /// This method is used by to initialize the connection.\n /// \n /// \n /// The transport connection could not be established.\n Task ConnectAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace ProtectedMCPServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n private readonly IHttpClientFactory _httpClientFactory;\n\n public WeatherTools(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public async Task GetAlerts(\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public async Task GetForecast(\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingLevel.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Indicates the severity of a log message.\n/// \n/// \n/// These map to syslog message severities, as specified in RFC-5424.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum LoggingLevel\n{\n /// Detailed debug information, typically only valuable to developers.\n [JsonStringEnumMemberName(\"debug\")]\n Debug,\n\n /// Normal operational messages that require no action.\n [JsonStringEnumMemberName(\"info\")]\n Info,\n\n /// Normal but significant events that might deserve attention.\n [JsonStringEnumMemberName(\"notice\")]\n Notice,\n\n /// Warning conditions that don't represent an error but indicate potential issues.\n [JsonStringEnumMemberName(\"warning\")]\n Warning,\n\n /// Error conditions that should be addressed but don't require immediate action.\n [JsonStringEnumMemberName(\"error\")]\n Error,\n\n /// Critical conditions that require immediate attention.\n [JsonStringEnumMemberName(\"critical\")]\n Critical,\n\n /// Action must be taken immediately to address the condition.\n [JsonStringEnumMemberName(\"alert\")]\n Alert,\n\n /// System is unusable and requires immediate attention.\n [JsonStringEnumMemberName(\"emergency\")]\n Emergency\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationOptions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Options for the MCP authentication handler.\n/// \npublic class McpAuthenticationOptions : AuthenticationSchemeOptions\n{\n private static readonly Uri DefaultResourceMetadataUri = new(\"/.well-known/oauth-protected-resource\", UriKind.Relative);\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationOptions()\n {\n // \"Bearer\" is JwtBearerDefaults.AuthenticationScheme, but we don't have a reference to the JwtBearer package here.\n ForwardAuthenticate = \"Bearer\";\n ResourceMetadataUri = DefaultResourceMetadataUri;\n Events = new McpAuthenticationEvents();\n }\n\n /// \n /// Gets or sets the events used to handle authentication events.\n /// \n public new McpAuthenticationEvents Events\n {\n get { return (McpAuthenticationEvents)base.Events!; }\n set { base.Events = value; }\n }\n\n /// \n /// The URI to the resource metadata document.\n /// \n /// \n /// This URI will be included in the WWW-Authenticate header when a 401 response is returned.\n /// \n public Uri ResourceMetadataUri { get; set; }\n\n /// \n /// Gets or sets the protected resource metadata.\n /// \n /// \n /// This contains the OAuth metadata for the protected resource, including authorization servers,\n /// supported scopes, and other information needed for clients to authenticate.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common request methods used in the MCP protocol.\n/// \npublic static class RequestMethods\n{\n /// \n /// The name of the request method sent from the client to request a list of the server's tools.\n /// \n public const string ToolsList = \"tools/list\";\n\n /// \n /// The name of the request method sent from the client to request that the server invoke a specific tool.\n /// \n public const string ToolsCall = \"tools/call\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's prompts.\n /// \n public const string PromptsList = \"prompts/list\";\n\n /// \n /// The name of the request method sent by the client to get a prompt provided by the server.\n /// \n public const string PromptsGet = \"prompts/get\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resources.\n /// \n public const string ResourcesList = \"resources/list\";\n\n /// \n /// The name of the request method sent from the client to read a specific server resource.\n /// \n public const string ResourcesRead = \"resources/read\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resource templates.\n /// \n public const string ResourcesTemplatesList = \"resources/templates/list\";\n\n /// \n /// The name of the request method sent from the client to request \n /// notifications from the server whenever a particular resource changes.\n /// \n public const string ResourcesSubscribe = \"resources/subscribe\";\n\n /// \n /// The name of the request method sent from the client to request unsubscribing from \n /// notifications from the server.\n /// \n public const string ResourcesUnsubscribe = \"resources/unsubscribe\";\n\n /// \n /// The name of the request method sent from the server to request a list of the client's roots.\n /// \n public const string RootsList = \"roots/list\";\n\n /// \n /// The name of the request method sent by either endpoint to check that the connected endpoint is still alive.\n /// \n public const string Ping = \"ping\";\n\n /// \n /// The name of the request method sent from the client to the server to adjust the logging level.\n /// \n /// \n /// This request allows clients to control which log messages they receive from the server\n /// by setting a minimum severity threshold. After processing this request, the server will\n /// send log messages with severity at or above the specified level to the client as\n /// notifications.\n /// \n public const string LoggingSetLevel = \"logging/setLevel\";\n\n /// \n /// The name of the request method sent from the client to the server to ask for completion suggestions.\n /// \n /// \n /// This is used to provide autocompletion-like functionality for arguments in a resource reference or a prompt template.\n /// The client provides a reference (resource or prompt), argument name, and partial value, and the server \n /// responds with matching completion options.\n /// \n public const string CompletionComplete = \"completion/complete\";\n\n /// \n /// The name of the request method sent from the server to sample an large language model (LLM) via the client.\n /// \n /// \n /// This request allows servers to utilize an LLM available on the client side to generate text or image responses\n /// based on provided messages. It is part of the sampling capability in the Model Context Protocol and enables servers to access\n /// client-side AI models without needing direct API access to those models.\n /// \n public const string SamplingCreateMessage = \"sampling/createMessage\";\n\n /// \n /// The name of the request method sent from the client to the server to elicit additional information from the user via the client.\n /// \n /// \n /// This request is used when the server needs more information from the client to proceed with a task or interaction.\n /// Servers can request structured data from users, with optional JSON schemas to validate responses.\n /// \n public const string ElicitationCreate = \"elicitation/create\";\n\n /// \n /// The name of the request method sent from the client to the server when it first connects, asking it initialize.\n /// \n /// \n /// The initialize request is the first request sent by the client to the server. It provides client information\n /// and capabilities to the server during connection establishment. The server responds with its own capabilities\n /// and information, establishing the protocol version and available features for the session.\n /// \n public const string Initialize = \"initialize\";\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer server,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await server.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrimitiveCollection.cs", "using System.Collections;\nusing System.Collections.Concurrent;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their names.\n/// Specifies the type of primitive stored in the collection.\npublic class McpServerPrimitiveCollection : ICollection, IReadOnlyCollection\n where T : IMcpServerPrimitive\n{\n /// Concurrent dictionary of primitives, indexed by their names.\n private readonly ConcurrentDictionary _primitives;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPrimitiveCollection(IEqualityComparer? keyComparer = null)\n {\n _primitives = new(keyComparer ?? EqualityComparer.Default);\n }\n\n /// Occurs when the collection is changed.\n /// \n /// By default, this is raised when a primitive is added or removed. However, a derived implementation\n /// may raise this event for other reasons, such as when a primitive is modified.\n /// \n public event EventHandler? Changed;\n\n /// Gets the number of primitives in the collection.\n public int Count => _primitives.Count;\n\n /// Gets whether there are any primitives in the collection.\n public bool IsEmpty => _primitives.IsEmpty;\n\n /// Raises if there are registered handlers.\n protected void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);\n\n /// Gets the with the specified from the collection.\n /// The name of the primitive to retrieve.\n /// The with the specified name.\n /// is .\n /// An primitive with the specified name does not exist in the collection.\n public T this[string name]\n {\n get\n {\n Throw.IfNull(name);\n return _primitives[name];\n }\n }\n\n /// Clears all primitives from the collection.\n public virtual void Clear()\n {\n _primitives.Clear();\n RaiseChanged();\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// is .\n /// A primitive with the same name as already exists in the collection.\n public void Add(T primitive)\n {\n if (!TryAdd(primitive))\n {\n throw new ArgumentException($\"A primitive with the same name '{primitive.Id}' already exists in the collection.\", nameof(primitive));\n }\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// if the primitive was added; otherwise, .\n /// is .\n public virtual bool TryAdd(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool added = _primitives.TryAdd(primitive.Id, primitive);\n if (added)\n {\n RaiseChanged();\n }\n\n return added;\n }\n\n /// Removes the specified primitivefrom the collection.\n /// The primitive to be removed from the collection.\n /// \n /// if the primitive was found in the collection and removed; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool Remove(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool removed = ((ICollection>)_primitives).Remove(new(primitive.Id, primitive));\n if (removed)\n {\n RaiseChanged();\n }\n\n return removed;\n }\n\n /// Attempts to get the primitive with the specified name from the collection.\n /// The name of the primitive to retrieve.\n /// The primitive, if found; otherwise, .\n /// \n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool TryGetPrimitive(string name, [NotNullWhen(true)] out T? primitive)\n {\n Throw.IfNull(name);\n return _primitives.TryGetValue(name, out primitive);\n }\n\n /// Checks if a specific primitive is present in the collection of primitives.\n /// The primitive to search for in the collection.\n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// is .\n public virtual bool Contains(T primitive)\n {\n Throw.IfNull(primitive);\n return ((ICollection>)_primitives).Contains(new(primitive.Id, primitive));\n }\n\n /// Gets the names of all of the primitives in the collection.\n public virtual ICollection PrimitiveNames => _primitives.Keys;\n\n /// Creates an array containing all of the primitives in the collection.\n /// An array containing all of the primitives in the collection.\n public virtual T[] ToArray() => _primitives.Values.ToArray();\n\n /// \n public virtual void CopyTo(T[] array, int arrayIndex)\n {\n Throw.IfNull(array);\n\n _primitives.Values.CopyTo(array, arrayIndex);\n }\n\n /// \n public virtual IEnumerator GetEnumerator()\n {\n foreach (var entry in _primitives)\n {\n yield return entry.Value;\n }\n }\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n bool ICollection.IsReadOnly => false;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/ProgressNotificationValue.cs", "namespace ModelContextProtocol;\n\n/// Provides a progress value that can be sent using .\npublic sealed class ProgressNotificationValue\n{\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// \n /// This value typically represents either a percentage (0-100) or the number of items processed so far (when used with the property).\n /// \n /// \n /// When reporting progress, this value should increase monotonically as the operation proceeds.\n /// Values are typically between 0 and 100 when representing percentages, or can be any positive number\n /// when representing completed items in combination with the property.\n /// \n /// \n public required float Progress { get; init; }\n\n /// Gets or sets the total number of items to process (or total progress required), if known.\n public float? Total { get; init; }\n\n /// Gets or sets an optional message describing the current progress.\n public string? Message { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CompilerFeatureRequiredAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Indicates that compiler support for a particular feature is required for the location where this attribute is applied.\n /// \n [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]\n internal sealed class CompilerFeatureRequiredAttribute : Attribute\n {\n public CompilerFeatureRequiredAttribute(string featureName)\n {\n FeatureName = featureName;\n }\n\n /// \n /// The name of the compiler feature.\n /// \n public string FeatureName { get; }\n\n /// \n /// If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand .\n /// \n public bool IsOptional { get; init; }\n\n /// \n /// The used for the required members C# feature.\n /// \n public const string RequiredMembers = nameof(RequiredMembers);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpSession.cs", "using ModelContextProtocol.AspNetCore.Stateless;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Security.Claims;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed class HttpMcpSession(\n string sessionId,\n TTransport transport,\n UserIdClaim? userId,\n TimeProvider timeProvider) : IAsyncDisposable\n where TTransport : ITransport\n{\n private int _referenceCount;\n private int _getRequestStarted;\n private CancellationTokenSource _disposeCts = new();\n\n public string Id { get; } = sessionId;\n public TTransport Transport { get; } = transport;\n public UserIdClaim? UserIdClaim { get; } = userId;\n\n public CancellationToken SessionClosed => _disposeCts.Token;\n\n public bool IsActive => !SessionClosed.IsCancellationRequested && _referenceCount > 0;\n public long LastActivityTicks { get; private set; } = timeProvider.GetTimestamp();\n\n private TimeProvider TimeProvider => timeProvider;\n\n public IMcpServer? Server { get; set; }\n public Task? ServerRunTask { get; set; }\n\n public IDisposable AcquireReference()\n {\n Interlocked.Increment(ref _referenceCount);\n return new UnreferenceDisposable(this);\n }\n\n public bool TryStartGetRequest() => Interlocked.Exchange(ref _getRequestStarted, 1) == 0;\n\n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n\n if (ServerRunTask is not null)\n {\n await ServerRunTask;\n }\n }\n catch (OperationCanceledException)\n {\n }\n finally\n {\n try\n {\n if (Server is not null)\n {\n await Server.DisposeAsync();\n }\n }\n finally\n {\n await Transport.DisposeAsync();\n _disposeCts.Dispose();\n }\n }\n }\n\n public bool HasSameUserId(ClaimsPrincipal user)\n => UserIdClaim == StreamableHttpHandler.GetUserIdClaim(user);\n\n private sealed class UnreferenceDisposable(HttpMcpSession session) : IDisposable\n {\n public void Dispose()\n {\n if (Interlocked.Decrement(ref session._referenceCount) == 0)\n {\n session.LastActivityTicks = session.TimeProvider.GetTimestamp();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/TextResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents text-based contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when textual data needs to be exchanged through\n/// the Model Context Protocol. The text is stored directly in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for binary resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class TextResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the text of the item.\n /// \n [JsonPropertyName(\"text\")]\n public string Text { get; set; } = string.Empty;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerFactory.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a factory for creating instances.\n/// \n/// \n/// This is the recommended way to create instances.\n/// The factory handles proper initialization of server instances with the required dependencies.\n/// \npublic static class McpServerFactory\n{\n /// \n /// Creates a new instance of an .\n /// \n /// Transport to use for the server representing an already-established MCP session.\n /// Configuration options for this server, including capabilities. \n /// Logger factory to use for logging. If null, logging will be disabled.\n /// Optional service provider to create new instances of tools and other dependencies.\n /// An instance that should be disposed when no longer needed.\n /// is .\n /// is .\n public static IMcpServer Create(\n ITransport transport,\n McpServerOptions serverOptions,\n ILoggerFactory? loggerFactory = null,\n IServiceProvider? serviceProvider = null)\n {\n Throw.IfNull(transport);\n Throw.IfNull(serverOptions);\n\n return new McpServer(transport, serverOptions, loggerFactory, serviceProvider);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Argument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument used in completion requests to provide context for auto-completion functionality.\n/// \n/// \n/// This class is used when requesting completion suggestions for a particular field or parameter.\n/// See the schema for details.\n/// \npublic sealed class Argument\n{\n /// \n /// Gets or sets the name of the argument being completed.\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the current partial text value for which completion suggestions are requested.\n /// \n /// \n /// This represents the text that has been entered so far and for which completion\n /// options should be generated.\n /// \n [JsonPropertyName(\"value\")]\n public string Value { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PingResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request in the Model Context Protocol.\n/// \n/// \n/// \n/// The is returned in response to a request, \n/// which is used to verify that the connection between client and server is still alive and responsive. \n/// Since this is a simple connectivity check, the result is an empty object containing no data.\n/// \n/// \n/// Ping requests can be initiated by either the client or the server to check if the other party\n/// is still responsive.\n/// \n/// \npublic sealed class PingResult : Result;"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/TokenContainer.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a token response from the OAuth server.\n/// \ninternal sealed class TokenContainer\n{\n /// \n /// Gets or sets the access token.\n /// \n [JsonPropertyName(\"access_token\")]\n public string AccessToken { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the refresh token.\n /// \n [JsonPropertyName(\"refresh_token\")]\n public string? RefreshToken { get; set; }\n\n /// \n /// Gets or sets the number of seconds until the access token expires.\n /// \n [JsonPropertyName(\"expires_in\")]\n public int ExpiresIn { get; set; }\n\n /// \n /// Gets or sets the extended expiration time in seconds.\n /// \n [JsonPropertyName(\"ext_expires_in\")]\n public int ExtExpiresIn { get; set; }\n\n /// \n /// Gets or sets the token type (typically \"Bearer\").\n /// \n [JsonPropertyName(\"token_type\")]\n public string TokenType { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the scope of the access token.\n /// \n [JsonPropertyName(\"scope\")]\n public string Scope { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the timestamp when the token was obtained.\n /// \n [JsonIgnore]\n public DateTimeOffset ObtainedAt { get; set; }\n\n /// \n /// Gets the timestamp when the token expires, calculated from ObtainedAt and ExpiresIn.\n /// \n [JsonIgnore]\n public DateTimeOffset ExpiresAt => ObtainedAt.AddSeconds(ExpiresIn);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/BlobResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the binary contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when binary data needs to be exchanged through\n/// the Model Context Protocol. The binary data is represented as a base64-encoded string\n/// in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for text-based resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class BlobResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the base64-encoded string representing the binary data of the item.\n /// \n [JsonPropertyName(\"blob\")]\n public string Blob { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContextInclusion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Specifies the context inclusion options for a request in the Model Context Protocol (MCP).\n/// \n/// \n/// See the schema for details.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum ContextInclusion\n{\n /// \n /// Indicates that no context should be included.\n /// \n [JsonStringEnumMemberName(\"none\")]\n None,\n\n /// \n /// Indicates that context from the server that sent the request should be included.\n /// \n [JsonStringEnumMemberName(\"thisServer\")]\n ThisServer,\n\n /// \n /// Indicates that context from all servers that the client is connected to should be included.\n /// \n [JsonStringEnumMemberName(\"allServers\")]\n AllServers\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Program.cs", "using Microsoft.AspNetCore.Authentication.JwtBearer;\nusing Microsoft.IdentityModel.Tokens;\nusing ModelContextProtocol.AspNetCore.Authentication;\nusing ProtectedMCPServer.Tools;\nusing System.Net.Http.Headers;\nusing System.Security.Claims;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nvar serverUrl = \"http://localhost:7071/\";\nvar inMemoryOAuthServerUrl = \"https://localhost:7029\";\n\nbuilder.Services.AddAuthentication(options =>\n{\n options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;\n options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;\n})\n.AddJwtBearer(options =>\n{\n // Configure to validate tokens from our in-memory OAuth server\n options.Authority = inMemoryOAuthServerUrl;\n options.TokenValidationParameters = new TokenValidationParameters\n {\n ValidateIssuer = true,\n ValidateAudience = true,\n ValidateLifetime = true,\n ValidateIssuerSigningKey = true,\n ValidAudience = serverUrl, // Validate that the audience matches the resource metadata as suggested in RFC 8707\n ValidIssuer = inMemoryOAuthServerUrl,\n NameClaimType = \"name\",\n RoleClaimType = \"roles\"\n };\n\n options.Events = new JwtBearerEvents\n {\n OnTokenValidated = context =>\n {\n var name = context.Principal?.Identity?.Name ?? \"unknown\";\n var email = context.Principal?.FindFirstValue(\"preferred_username\") ?? \"unknown\";\n Console.WriteLine($\"Token validated for: {name} ({email})\");\n return Task.CompletedTask;\n },\n OnAuthenticationFailed = context =>\n {\n Console.WriteLine($\"Authentication failed: {context.Exception.Message}\");\n return Task.CompletedTask;\n },\n OnChallenge = context =>\n {\n Console.WriteLine($\"Challenging client to authenticate with Entra ID\");\n return Task.CompletedTask;\n }\n };\n})\n.AddMcp(options =>\n{\n options.ResourceMetadata = new()\n {\n Resource = new Uri(serverUrl),\n ResourceDocumentation = new Uri(\"https://docs.example.com/api/weather\"),\n AuthorizationServers = { new Uri(inMemoryOAuthServerUrl) },\n ScopesSupported = [\"mcp:tools\"],\n };\n});\n\nbuilder.Services.AddAuthorization();\n\nbuilder.Services.AddHttpContextAccessor();\nbuilder.Services.AddMcpServer()\n .WithTools()\n .WithHttpTransport();\n\n// Configure HttpClientFactory for weather.gov API\nbuilder.Services.AddHttpClient(\"WeatherApi\", client =>\n{\n client.BaseAddress = new Uri(\"https://api.weather.gov\");\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n});\n\nvar app = builder.Build();\n\napp.UseAuthentication();\napp.UseAuthorization();\n\n// Use the default MCP policy name that we've configured\napp.MapMcp().RequireAuthorization();\n\nConsole.WriteLine($\"Starting MCP server with authorization at {serverUrl}\");\nConsole.WriteLine($\"Using in-memory OAuth server at {inMemoryOAuthServerUrl}\");\nConsole.WriteLine($\"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource\");\nConsole.WriteLine(\"Press Ctrl+C to stop the server\");\n\napp.Run(serverUrl);\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerOptionsSetup.cs", "using Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Configures the McpServerOptions using addition services from DI.\n/// \n/// The server handlers configuration options.\n/// Tools individually registered.\n/// Prompts individually registered.\n/// Resources individually registered.\ninternal sealed class McpServerOptionsSetup(\n IOptions serverHandlers,\n IEnumerable serverTools,\n IEnumerable serverPrompts,\n IEnumerable serverResources) : IConfigureOptions\n{\n /// \n /// Configures the given McpServerOptions instance by setting server information\n /// and applying custom server handlers and tools.\n /// \n /// The options instance to be configured.\n public void Configure(McpServerOptions options)\n {\n Throw.IfNull(options);\n\n // Collect all of the provided tools into a tools collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection toolCollection = options.Capabilities?.Tools?.ToolCollection ?? [];\n foreach (var tool in serverTools)\n {\n toolCollection.TryAdd(tool);\n }\n\n if (!toolCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Tools ??= new();\n options.Capabilities.Tools.ToolCollection = toolCollection;\n }\n\n // Collect all of the provided prompts into a prompts collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection promptCollection = options.Capabilities?.Prompts?.PromptCollection ?? [];\n foreach (var prompt in serverPrompts)\n {\n promptCollection.TryAdd(prompt);\n }\n\n if (!promptCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Prompts ??= new();\n options.Capabilities.Prompts.PromptCollection = promptCollection;\n }\n\n // Collect all of the provided resources into a resources collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerResourceCollection resourceCollection = options.Capabilities?.Resources?.ResourceCollection ?? [];\n foreach (var resource in serverResources)\n {\n resourceCollection.TryAdd(resource);\n }\n\n if (!resourceCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Resources ??= new();\n options.Capabilities.Resources.ResourceCollection = resourceCollection;\n }\n\n // Apply custom server handlers.\n serverHandlers.Value.OverwriteWithSetHandlers(options);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads that support cursor-based pagination.\n/// \n/// \n/// \n/// Pagination allows API responses to be broken into smaller, manageable chunks when\n/// there are potentially many results to return or when dynamically-computed results\n/// may incur measurable latency.\n/// \n/// \n/// Classes that inherit from implement cursor-based pagination,\n/// where the property serves as an opaque token pointing to the next \n/// set of results.\n/// \n/// \npublic abstract class PaginatedResult : Result\n{\n private protected PaginatedResult()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the pagination position after the last returned result.\n /// \n /// \n /// When a paginated result has more data available, the \n /// property will contain a non- token that can be used in subsequent requests\n /// to fetch the next page. When there are no more results to return, the property\n /// will be .\n /// \n public string? NextCursor { get; set; }\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/AnnotatedMessageTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AnnotatedMessageTool\n{\n public enum MessageType\n {\n Error,\n Success,\n Debug,\n }\n\n [McpServerTool(Name = \"annotatedMessage\"), Description(\"Generates an annotated message\")]\n public static IEnumerable AnnotatedMessage(MessageType messageType, bool includeImage = true)\n {\n List contents = messageType switch\n {\n MessageType.Error => [new TextContentBlock\n {\n Text = \"Error: Operation failed\",\n Annotations = new() { Audience = [Role.User, Role.Assistant], Priority = 1.0f }\n }],\n MessageType.Success => [new TextContentBlock\n {\n Text = \"Operation completed successfully\",\n Annotations = new() { Audience = [Role.User], Priority = 0.7f }\n }],\n MessageType.Debug => [new TextContentBlock\n {\n Text = \"Debug: Cache hit ratio 0.95, latency 150ms\",\n Annotations = new() { Audience = [Role.Assistant], Priority = 0.3f }\n }],\n _ => throw new ArgumentOutOfRangeException(nameof(messageType), messageType, null)\n };\n\n if (includeImage)\n {\n contents.Add(new ImageContentBlock\n {\n Data = TinyImageTool.MCP_TINY_IMAGE.Split(\",\").Last(),\n MimeType = \"image/png\",\n Annotations = new() { Audience = [Role.User], Priority = 0.5f }\n });\n }\n\n return contents;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Result.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads.\n/// \npublic abstract class Result\n{\n /// Prevent external derivations.\n private protected Result()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional context information for completion requests.\n/// \n/// \n/// This context provides information that helps the server generate more relevant \n/// completion suggestions, such as previously resolved variables in a template.\n/// \npublic sealed class CompleteContext\n{\n /// \n /// Gets or sets previously-resolved variables in a URI template or prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompletionsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the completions capability for providing auto-completion suggestions\n/// for prompt arguments and resource references.\n/// \n/// \n/// \n/// When enabled, this capability allows a Model Context Protocol server to provide \n/// auto-completion suggestions. This capability is advertised to clients during the initialize handshake.\n/// \n/// \n/// The primary function of this capability is to improve the user experience by offering\n/// contextual suggestions for argument values or resource identifiers based on partial input.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompletionsCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for completion requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler receives a reference type (e.g., \"ref/prompt\" or \"ref/resource\") and the current argument value,\n /// and should return appropriate completion suggestions.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring HTTP MCP servers via dependency injection.\n/// \npublic static class HttpMcpServerBuilderExtensions\n{\n /// \n /// Adds the services necessary for \n /// to handle MCP requests and sessions using the MCP Streamable HTTP transport. For more information on configuring the underlying HTTP server\n /// to control things like port binding custom TLS certificates, see the Minimal APIs quick reference.\n /// \n /// The builder instance.\n /// Configures options for the Streamable HTTP transport. This allows configuring per-session\n /// and running logic before and after a session.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithHttpTransport(this IMcpServerBuilder builder, Action? configureOptions = null)\n {\n ArgumentNullException.ThrowIfNull(builder);\n\n builder.Services.TryAddSingleton();\n builder.Services.TryAddSingleton();\n builder.Services.AddHostedService();\n builder.Services.AddDataProtection();\n\n if (configureOptions is not null)\n {\n builder.Services.Configure(configureOptions);\n }\n\n return builder;\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/LongRunningTool.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class LongRunningTool\n{\n [McpServerTool(Name = \"longRunningOperation\"), Description(\"Demonstrates a long running operation with progress updates\")]\n public static async Task LongRunningOperation(\n IMcpServer server,\n RequestContext context,\n int duration = 10,\n int steps = 5)\n {\n var progressToken = context.Params?.ProgressToken;\n var stepDuration = duration / steps;\n\n for (int i = 1; i <= steps + 1; i++)\n {\n await Task.Delay(stepDuration * 1000);\n \n if (progressToken is not null)\n {\n await server.SendNotificationAsync(\"notifications/progress\", new\n {\n Progress = i,\n Total = steps,\n progressToken\n });\n }\n }\n\n return $\"Long running operation completed. Duration: {duration} seconds. Steps: {steps}.\";\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationServerMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the metadata about an OAuth authorization server.\n/// \ninternal sealed class AuthorizationServerMetadata\n{\n /// \n /// The authorization endpoint URI.\n /// \n [JsonPropertyName(\"authorization_endpoint\")]\n public Uri AuthorizationEndpoint { get; set; } = null!;\n\n /// \n /// The token endpoint URI.\n /// \n [JsonPropertyName(\"token_endpoint\")]\n public Uri TokenEndpoint { get; set; } = null!;\n\n /// \n /// The registration endpoint URI.\n /// \n [JsonPropertyName(\"registration_endpoint\")]\n public Uri? RegistrationEndpoint { get; set; }\n\n /// \n /// The revocation endpoint URI.\n /// \n [JsonPropertyName(\"revocation_endpoint\")]\n public Uri? RevocationEndpoint { get; set; }\n\n /// \n /// The response types supported by the authorization server.\n /// \n [JsonPropertyName(\"response_types_supported\")]\n public List? ResponseTypesSupported { get; set; }\n\n /// \n /// The grant types supported by the authorization server.\n /// \n [JsonPropertyName(\"grant_types_supported\")]\n public List? GrantTypesSupported { get; set; }\n\n /// \n /// The token endpoint authentication methods supported by the authorization server.\n /// \n [JsonPropertyName(\"token_endpoint_auth_methods_supported\")]\n public List? TokenEndpointAuthMethodsSupported { get; set; }\n\n /// \n /// The code challenge methods supported by the authorization server.\n /// \n [JsonPropertyName(\"code_challenge_methods_supported\")]\n public List? CodeChallengeMethodsSupported { get; set; }\n\n /// \n /// The issuer URI of the authorization server.\n /// \n [JsonPropertyName(\"issuer\")]\n public Uri? Issuer { get; set; }\n\n /// \n /// The scopes supported by the authorization server.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List? ScopesSupported { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AugmentedServiceProvider.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Augments a service provider with additional request-related services.\ninternal sealed class RequestServiceProvider(\n RequestContext request, IServiceProvider? innerServices) :\n IServiceProvider, IKeyedServiceProvider,\n IServiceProviderIsService, IServiceProviderIsKeyedService,\n IDisposable, IAsyncDisposable\n where TRequestParams : RequestParams\n{\n /// Gets the request associated with this instance.\n public RequestContext Request => request;\n\n /// Gets whether the specified type is in the list of additional types this service provider wraps around the one in a provided request's services.\n public static bool IsAugmentedWith(Type serviceType) =>\n serviceType == typeof(RequestContext) ||\n serviceType == typeof(IMcpServer) ||\n serviceType == typeof(IProgress);\n\n /// \n public object? GetService(Type serviceType) =>\n serviceType == typeof(RequestContext) ? request :\n serviceType == typeof(IMcpServer) ? request.Server :\n serviceType == typeof(IProgress) ?\n (request.Params?.ProgressToken is { } progressToken ? new TokenProgress(request.Server, progressToken) : NullProgress.Instance) :\n innerServices?.GetService(serviceType);\n\n /// \n public bool IsService(Type serviceType) =>\n IsAugmentedWith(serviceType) ||\n (innerServices as IServiceProviderIsService)?.IsService(serviceType) is true;\n\n /// \n public bool IsKeyedService(Type serviceType, object? serviceKey) =>\n (serviceKey is null && IsService(serviceType)) ||\n (innerServices as IServiceProviderIsKeyedService)?.IsKeyedService(serviceType, serviceKey) is true;\n\n /// \n public object? GetKeyedService(Type serviceType, object? serviceKey) =>\n serviceKey is null ? GetService(serviceType) :\n (innerServices as IKeyedServiceProvider)?.GetKeyedService(serviceType, serviceKey);\n\n /// \n public object GetRequiredKeyedService(Type serviceType, object? serviceKey) =>\n GetKeyedService(serviceType, serviceKey) ??\n throw new InvalidOperationException($\"No service of type '{serviceType}' with key '{serviceKey}' is registered.\");\n\n /// \n public void Dispose() =>\n (innerServices as IDisposable)?.Dispose();\n\n /// \n public ValueTask DisposeAsync() =>\n innerServices is IAsyncDisposable asyncDisposable ? asyncDisposable.DisposeAsync() : default;\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/ResourceMetadataRequestContext.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Context for resource metadata request events.\n/// \npublic class ResourceMetadataRequestContext : HandleRequestContext\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The HTTP context.\n /// The authentication scheme.\n /// The authentication options.\n public ResourceMetadataRequestContext(\n HttpContext context,\n AuthenticationScheme scheme,\n McpAuthenticationOptions options)\n : base(context, scheme, options)\n {\n }\n\n /// \n /// Gets or sets the protected resource metadata for the current request.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building resources that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner resource instance.\n/// \npublic abstract class DelegatingMcpServerResource : McpServerResource\n{\n private readonly McpServerResource _innerResource;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner resource wrapped by this delegating resource.\n protected DelegatingMcpServerResource(McpServerResource innerResource)\n {\n Throw.IfNull(innerResource);\n _innerResource = innerResource;\n }\n\n /// \n public override Resource? ProtocolResource => _innerResource.ProtocolResource;\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate => _innerResource.ProtocolResourceTemplate;\n\n /// \n public override ValueTask ReadAsync(RequestContext request, CancellationToken cancellationToken = default) => \n _innerResource.ReadAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerResource.ToString();\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/StringSyntaxAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// Specifies the syntax used in a string.\n[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\ninternal sealed class StringSyntaxAttribute : Attribute\n{\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n public StringSyntaxAttribute(string syntax)\n {\n Syntax = syntax;\n Arguments = Array.Empty();\n }\n\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n /// Optional arguments associated with the specific syntax employed.\n public StringSyntaxAttribute(string syntax, params object?[] arguments)\n {\n Syntax = syntax;\n Arguments = arguments;\n }\n\n /// Gets the identifier of the syntax used.\n public string Syntax { get; }\n\n /// Optional arguments associated with the specific syntax employed.\n public object?[] Arguments { get; }\n\n /// The syntax identifier for strings containing composite formats for string formatting.\n public const string CompositeFormat = nameof(CompositeFormat);\n\n /// The syntax identifier for strings containing date format specifiers.\n public const string DateOnlyFormat = nameof(DateOnlyFormat);\n\n /// The syntax identifier for strings containing date and time format specifiers.\n public const string DateTimeFormat = nameof(DateTimeFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string EnumFormat = nameof(EnumFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string GuidFormat = nameof(GuidFormat);\n\n /// The syntax identifier for strings containing JavaScript Object Notation (JSON).\n public const string Json = nameof(Json);\n\n /// The syntax identifier for strings containing numeric format specifiers.\n public const string NumericFormat = nameof(NumericFormat);\n\n /// The syntax identifier for strings containing regular expressions.\n public const string Regex = nameof(Regex);\n\n /// The syntax identifier for strings containing time format specifiers.\n public const string TimeOnlyFormat = nameof(TimeOnlyFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string TimeSpanFormat = nameof(TimeSpanFormat);\n\n /// The syntax identifier for strings containing URIs.\n public const string Uri = nameof(Uri);\n\n /// The syntax identifier for strings containing XML.\n public const string Xml = nameof(Xml);\n}\n#endif"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/PasteArguments.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/d2650b6ae7023a2d9d2c74c56116f1f18472ab04/src/libraries/System.Private.CoreLib/src/System/PasteArguments.cs\n// and changed from using ValueStringBuilder to StringBuilder.\n\n#if !NET\nusing System.Text;\n\nnamespace System;\n\ninternal static partial class PasteArguments\n{\n internal static void AppendArgument(StringBuilder stringBuilder, string argument)\n {\n if (stringBuilder.Length != 0)\n {\n stringBuilder.Append(' ');\n }\n\n // Parsing rules for non-argv[0] arguments:\n // - Backslash is a normal character except followed by a quote.\n // - 2N backslashes followed by a quote ==> N literal backslashes followed by unescaped quote\n // - 2N+1 backslashes followed by a quote ==> N literal backslashes followed by a literal quote\n // - Parsing stops at first whitespace outside of quoted region.\n // - (post 2008 rule): A closing quote followed by another quote ==> literal quote, and parsing remains in quoting mode.\n if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument))\n {\n // Simple case - no quoting or changes needed.\n stringBuilder.Append(argument);\n }\n else\n {\n stringBuilder.Append(Quote);\n int idx = 0;\n while (idx < argument.Length)\n {\n char c = argument[idx++];\n if (c == Backslash)\n {\n int numBackSlash = 1;\n while (idx < argument.Length && argument[idx] == Backslash)\n {\n idx++;\n numBackSlash++;\n }\n\n if (idx == argument.Length)\n {\n // We'll emit an end quote after this so must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2);\n }\n else if (argument[idx] == Quote)\n {\n // Backslashes will be followed by a quote. Must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2 + 1);\n stringBuilder.Append(Quote);\n idx++;\n }\n else\n {\n // Backslash will not be followed by a quote, so emit as normal characters.\n stringBuilder.Append(Backslash, numBackSlash);\n }\n\n continue;\n }\n\n if (c == Quote)\n {\n // Escape the quote so it appears as a literal. This also guarantees that we won't end up generating a closing quote followed\n // by another quote (which parses differently pre-2008 vs. post-2008.)\n stringBuilder.Append(Backslash);\n stringBuilder.Append(Quote);\n continue;\n }\n\n stringBuilder.Append(c);\n }\n\n stringBuilder.Append(Quote);\n }\n }\n\n private static bool ContainsNoWhitespaceOrQuotes(string s)\n {\n for (int i = 0; i < s.Length; i++)\n {\n char c = s[i];\n if (char.IsWhiteSpace(c) || c == Quote)\n {\n return false;\n }\n }\n\n return true;\n }\n\n private const char Quote = '\\\"';\n private const char Backslash = '\\\\';\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for notification parameters.\n/// \npublic abstract class NotificationParams\n{\n /// Prevent external derivations.\n private protected NotificationParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}"], ["/csharp-sdk/samples/EverythingServer/Prompts/ComplexPromptType.cs", "using EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class ComplexPromptType\n{\n [McpServerPrompt(Name = \"complex_prompt\"), Description(\"A prompt with arguments\")]\n public static IEnumerable ComplexPrompt(\n [Description(\"Temperature setting\")] int temperature,\n [Description(\"Output style\")] string? style = null)\n {\n return [\n new ChatMessage(ChatRole.User,$\"This is a complex prompt with arguments: temperature={temperature}, style={style}\"),\n new ChatMessage(ChatRole.Assistant, \"I understand. You've provided a complex prompt with temperature and style arguments. How would you like me to proceed?\"),\n new ChatMessage(ChatRole.User, [new DataContent(TinyImageTool.MCP_TINY_IMAGE)])\n ];\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServer.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) server that connects to and communicates with an MCP client.\n/// \npublic interface IMcpServer : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the client.\n /// \n /// \n /// \n /// These capabilities are established during the initialization handshake and indicate\n /// which features the client supports, such as sampling, roots, and other\n /// protocol-specific functionality.\n /// \n /// \n /// Server implementations can check these capabilities to determine which features\n /// are available when interacting with the client.\n /// \n /// \n ClientCapabilities? ClientCapabilities { get; }\n\n /// \n /// Gets the version and implementation information of the connected client.\n /// \n /// \n /// \n /// This property contains identification information about the client that has connected to this server,\n /// including its name and version. This information is provided by the client during initialization.\n /// \n /// \n /// Server implementations can use this information for logging, tracking client versions, \n /// or implementing client-specific behaviors.\n /// \n /// \n Implementation? ClientInfo { get; }\n\n /// \n /// Gets the options used to construct this server.\n /// \n /// \n /// These options define the server's capabilities, protocol version, and other configuration\n /// settings that were used to initialize the server.\n /// \n McpServerOptions ServerOptions { get; }\n\n /// \n /// Gets the service provider for the server.\n /// \n IServiceProvider? Services { get; }\n\n /// Gets the last logging level set by the client, or if it's never been set.\n LoggingLevel? LoggingLevel { get; }\n\n /// \n /// Runs the server, listening for and handling client requests.\n /// \n Task RunAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/SemaphoreSlimExtensions.cs", "namespace ModelContextProtocol;\n\ninternal static class SynchronizationExtensions\n{\n /// \n /// Asynchronously acquires a lock on the semaphore and returns a disposable object that releases the lock when disposed.\n /// \n /// The semaphore to acquire a lock on.\n /// A cancellation token to observe while waiting for the semaphore.\n /// A disposable that releases the semaphore when disposed.\n /// \n /// This extension method provides a convenient pattern for using a semaphore in asynchronous code,\n /// similar to how the `lock` statement is used in synchronous code.\n /// \n /// The was canceled.\n public static async ValueTask LockAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)\n {\n await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);\n return new(semaphore);\n }\n\n /// \n /// A disposable struct that releases a semaphore when disposed.\n /// \n /// \n /// This struct is used with the extension method to provide\n /// a using-pattern for semaphore locking, similar to lock statements.\n /// \n public readonly struct Releaser(SemaphoreSlim semaphore) : IDisposable\n {\n /// \n /// Releases the semaphore.\n /// \n /// \n /// This method is called automatically when the goes out of scope\n /// in a using statement or expression.\n /// \n public void Dispose() => semaphore.Release();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the logging capability configuration for a Model Context Protocol server.\n/// \n/// \n/// This capability allows clients to set the logging level and receive log messages from the server.\n/// See the schema for details.\n/// \npublic sealed class LoggingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for set logging level requests from clients.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerPrompt.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building prompts that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner prompt instance.\n/// \npublic abstract class DelegatingMcpServerPrompt : McpServerPrompt\n{\n private readonly McpServerPrompt _innerPrompt;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner prompt wrapped by this delegating prompt.\n protected DelegatingMcpServerPrompt(McpServerPrompt innerPrompt)\n {\n Throw.IfNull(innerPrompt);\n _innerPrompt = innerPrompt;\n }\n\n /// \n public override Prompt ProtocolPrompt => _innerPrompt.ProtocolPrompt;\n\n /// \n public override ValueTask GetAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerPrompt.GetAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerPrompt.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerTool.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building tools that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner tool instance.\n/// \npublic abstract class DelegatingMcpServerTool : McpServerTool\n{\n private readonly McpServerTool _innerTool;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner tool wrapped by this delegating tool.\n protected DelegatingMcpServerTool(McpServerTool innerTool)\n {\n Throw.IfNull(innerTool);\n _innerTool = innerTool;\n }\n\n /// \n public override Tool ProtocolTool => _innerTool.ProtocolTool;\n\n /// \n public override ValueTask InvokeAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerTool.InvokeAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerTool.ToString();\n}\n"], ["/csharp-sdk/src/Common/Throw.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace ModelContextProtocol;\n\n/// Provides helper methods for throwing exceptions.\ninternal static class Throw\n{\n // NOTE: Most of these should be replaced with extension statics for the relevant extension\n // type as downlevel polyfills once the C# 14 extension everything feature is available.\n\n public static void IfNull([NotNull] object? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n }\n\n public static void IfNullOrWhiteSpace([NotNull] string? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null || arg.AsSpan().IsWhiteSpace())\n {\n ThrowArgumentNullOrWhiteSpaceException(parameterName);\n }\n }\n\n public static void IfNegative(int arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg < 0)\n {\n Throw(parameterName);\n static void Throw(string? parameterName) => throw new ArgumentOutOfRangeException(parameterName, \"must not be negative.\");\n }\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullOrWhiteSpaceException(string? parameterName)\n {\n if (parameterName is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n\n throw new ArgumentException(\"Value cannot be empty or composed entirely of whitespace.\", parameterName);\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullException(string? parameterName) => throw new ArgumentNullException(parameterName);\n}"], ["/csharp-sdk/src/ModelContextProtocol/DefaultMcpServerBuilder.cs", "using ModelContextProtocol;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Default implementation of that enables fluent configuration\n/// of the Model Context Protocol (MCP) server. This builder is returned by the\n/// extension method and\n/// provides access to the service collection for registering additional MCP components.\n/// \ninternal sealed class DefaultMcpServerBuilder : IMcpServerBuilder\n{\n /// \n public IServiceCollection Services { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service collection to which MCP server services will be added. This collection\n /// is exposed through the property to allow additional configuration.\n /// Thrown when is null.\n public DefaultMcpServerBuilder(IServiceCollection services)\n {\n Throw.IfNull(services);\n\n Services = services;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationExtensions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.AspNetCore.Authentication;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Extension methods for adding MCP authorization support to ASP.NET Core applications.\n/// \npublic static class McpAuthenticationExtensions\n{\n /// \n /// Adds MCP authorization support to the application.\n /// \n /// The authentication builder.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n Action? configureOptions = null)\n {\n return AddMcp(\n builder,\n McpAuthenticationDefaults.AuthenticationScheme,\n McpAuthenticationDefaults.DisplayName,\n configureOptions);\n }\n\n /// \n /// Adds MCP authorization support to the application with a custom scheme name.\n /// \n /// The authentication builder.\n /// The authentication scheme name to use.\n /// The display name for the authentication scheme.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n string authenticationScheme,\n string displayName,\n Action? configureOptions = null)\n {\n return builder.AddScheme(\n authenticationScheme,\n displayName,\n configureOptions);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionId.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed class StatelessSessionId\n{\n [JsonPropertyName(\"clientInfo\")]\n public Implementation? ClientInfo { get; init; }\n\n [JsonPropertyName(\"userIdClaim\")]\n public UserIdClaim? UserIdClaim { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/IMcpServerBuilder.cs", "using ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides a builder for configuring instances.\n/// \n/// \n/// \n/// The interface provides a fluent API for configuring Model Context Protocol (MCP) servers\n/// when using dependency injection. It exposes methods for registering tools, prompts, custom request handlers,\n/// and server transports, allowing for comprehensive server configuration through a chain of method calls.\n/// \n/// \n/// The builder is obtained from the extension\n/// method and provides access to the underlying service collection via the property.\n/// \n/// \npublic interface IMcpServerBuilder\n{\n /// \n /// Gets the associated service collection.\n /// \n IServiceCollection Services { get; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerServiceCollectionExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides extension methods for configuring MCP servers with dependency injection.\n/// \npublic static class McpServerServiceCollectionExtensions\n{\n /// \n /// Adds the Model Context Protocol (MCP) server to the service collection with default options.\n /// \n /// The to add the server to.\n /// Optional callback to configure the .\n /// An that can be used to further configure the MCP server.\n\n public static IMcpServerBuilder AddMcpServer(this IServiceCollection services, Action? configureOptions = null)\n {\n services.AddOptions();\n services.TryAddEnumerable(ServiceDescriptor.Transient, McpServerOptionsSetup>());\n if (configureOptions is not null)\n {\n services.Configure(configureOptions);\n }\n\n return new DefaultMcpServerBuilder(services);\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/LoggingUpdateMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace EverythingServer;\n\npublic class LoggingUpdateMessageSender(IMcpServer server, Func getMinLevel) : BackgroundService\n{\n readonly Dictionary _loggingLevelMap = new()\n {\n { LoggingLevel.Debug, \"Debug-level message\" },\n { LoggingLevel.Info, \"Info-level message\" },\n { LoggingLevel.Notice, \"Notice-level message\" },\n { LoggingLevel.Warning, \"Warning-level message\" },\n { LoggingLevel.Error, \"Error-level message\" },\n { LoggingLevel.Critical, \"Critical-level message\" },\n { LoggingLevel.Alert, \"Alert-level message\" },\n { LoggingLevel.Emergency, \"Emergency-level message\" }\n };\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n var newLevel = (LoggingLevel)Random.Shared.Next(_loggingLevelMap.Count);\n\n var message = new\n {\n Level = newLevel.ToString().ToLower(),\n Data = _loggingLevelMap[newLevel],\n };\n\n if (newLevel > getMinLevel())\n {\n await server.SendNotificationAsync(\"notifications/message\", message, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(15000, stoppingToken);\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IMcpClient.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) client that connects to and communicates with an MCP server.\n/// \npublic interface IMcpClient : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the connected server.\n /// \n /// The client is not connected.\n ServerCapabilities ServerCapabilities { get; }\n\n /// \n /// Gets the implementation information of the connected server.\n /// \n /// \n /// \n /// This property provides identification details about the connected server, including its name and version.\n /// It is populated during the initialization handshake and is available after a successful connection.\n /// \n /// \n /// This information can be useful for logging, debugging, compatibility checks, and displaying server\n /// information to users.\n /// \n /// \n /// The client is not connected.\n Implementation ServerInfo { get; }\n\n /// \n /// Gets any instructions describing how to use the connected server and its features.\n /// \n /// \n /// \n /// This property contains instructions provided by the server during initialization that explain\n /// how to effectively use its capabilities. These instructions can include details about available\n /// tools, expected input formats, limitations, or any other helpful information.\n /// \n /// \n /// This can be used by clients to improve an LLM's understanding of available tools, prompts, and resources. \n /// It can be thought of like a \"hint\" to the model and may be added to a system prompt.\n /// \n /// \n string? ServerInstructions { get; }\n}"], ["/csharp-sdk/samples/EverythingServer/ResourceGenerator.cs", "using ModelContextProtocol.Protocol;\n\nnamespace EverythingServer;\n\nstatic class ResourceGenerator\n{\n private static readonly List _resources = Enumerable.Range(1, 100).Select(i =>\n {\n var uri = $\"test://template/resource/{i}\";\n if (i % 2 != 0)\n {\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"text/plain\",\n Description = $\"Resource {i}: This is a plaintext resource\"\n };\n }\n else\n {\n var buffer = System.Text.Encoding.UTF8.GetBytes($\"Resource {i}: This is a base64 blob\");\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"application/octet-stream\",\n Description = Convert.ToBase64String(buffer)\n };\n }\n }).ToList();\n\n public static IReadOnlyList Resources => _resources;\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationEvents.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Represents the authentication events for Model Context Protocol.\n/// \npublic class McpAuthenticationEvents\n{\n /// \n /// Gets or sets the function that is invoked when resource metadata is requested.\n /// \n /// \n /// This function is called when a resource metadata request is made to the protected resource metadata endpoint.\n /// The implementer should set the property\n /// to provide the appropriate metadata for the current request.\n /// \n public Func OnResourceMetadataRequest { get; set; } = context => Task.CompletedTask;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/EmptyResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an empty result object for operations that need to indicate successful completion \n/// but don't need to return any specific data.\n/// \npublic sealed class EmptyResult : Result\n{\n [JsonIgnore]\n internal static EmptyResult Instance { get; } = new();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resource templates available from the server.\n/// \n/// \n/// The server responds with a containing the available resource templates.\n/// See the schema for details.\n/// \npublic sealed class ListResourceTemplatesRequestParams : PaginatedRequestParams;"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithToolsFromAssembly, it enables automatic registration of tools without explicitly listing each tool\n/// class. The attribute is not necessary when a reference to the type is provided directly to a method like WithTools.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// tools must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerToolTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithPromptsFromAssembly, it enables automatic registration of prompts without explicitly listing each prompt class.\n/// The attribute is not necessary when a reference to the type is provided directly to a method like WithPrompts.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// prompts must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerPromptTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol/SingleSessionMcpServerHostedService.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Hosted service for a single-session (e.g. stdio) MCP server.\n/// \n/// The server representing the session being hosted.\n/// \n/// The host's application lifetime. If available, it will have termination requested when the session's run completes.\n/// \ninternal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime? lifetime = null) : BackgroundService\n{\n /// \n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n try\n {\n await session.RunAsync(stoppingToken).ConfigureAwait(false);\n }\n finally\n {\n lifetime?.StopApplication();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/NopProgress.cs", "namespace ModelContextProtocol;\n\n/// Provides an that's a nop.\ninternal sealed class NullProgress : IProgress\n{\n /// \n /// Gets the singleton instance of the class that performs no operations when progress is reported.\n /// \n /// \n /// Use this property when you need to provide an implementation \n /// but don't need to track or report actual progress.\n /// \n public static NullProgress Instance { get; } = new();\n\n /// \n public void Report(ProgressNotificationValue value)\n {\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing members that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing members that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithResourcesFromAssembly, it enables automatic registration of resources without explicitly listing each\n/// resource class. The attribute is not necessary when a reference to the type is provided directly to a method\n/// like McpServerBuilderExtensions.WithResources.\n/// \n/// \n/// Within a class marked with this attribute, individual members that should be exposed as\n/// resources must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerResourceTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resources available from the server.\n/// \n/// \n/// The server responds with a containing the available resources.\n/// See the schema for details.\n/// \npublic sealed class ListResourcesRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of tools available from the server.\n/// \n/// \n/// The server responds with a containing the available tools.\n/// See the schema for details.\n/// \npublic sealed class ListToolsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of prompts available from the server.\n/// \n/// \n/// The server responds with a containing the available prompts.\n/// See the schema for details.\n/// \npublic sealed class ListPromptsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Role.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the type of role in the Model Context Protocol conversation.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum Role\n{\n /// \n /// Corresponds to a human user in the conversation.\n /// \n [JsonStringEnumMemberName(\"user\")]\n User,\n\n /// \n /// Corresponds to the AI assistant in the conversation.\n /// \n [JsonStringEnumMemberName(\"assistant\")]\n Assistant\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a server to request\n/// a list of roots available from the client.\n/// \n/// \n/// The client responds with a containing the client's roots.\n/// See the schema for details.\n/// \npublic sealed class ListRootsRequestParams : RequestParams;\n"], ["/csharp-sdk/samples/ChatWithTools/Program.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing OpenAI;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\n\nusing var tracerProvider = Sdk.CreateTracerProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddSource(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var metricsProvider = Sdk.CreateMeterProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddMeter(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var loggerFactory = LoggerFactory.Create(builder => builder.AddOpenTelemetry(opt => opt.AddOtlpExporter()));\n\n// Connect to an MCP server\nConsole.WriteLine(\"Connecting client to MCP 'everything' server\");\n\n// Create OpenAI client (or any other compatible with IChatClient)\n// Provide your own OPENAI_API_KEY via an environment variable.\nvar openAIClient = new OpenAIClient(Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")).GetChatClient(\"gpt-4o-mini\");\n\n// Create a sampling client.\nusing IChatClient samplingClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\nvar mcpClient = await McpClientFactory.CreateAsync(\n new StdioClientTransport(new()\n {\n Command = \"npx\",\n Arguments = [\"-y\", \"--verbose\", \"@modelcontextprotocol/server-everything\"],\n Name = \"Everything\",\n }),\n clientOptions: new()\n {\n Capabilities = new() { Sampling = new() { SamplingHandler = samplingClient.CreateSamplingHandler() } },\n },\n loggerFactory: loggerFactory);\n\n// Get all available tools\nConsole.WriteLine(\"Tools available:\");\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\" {tool}\");\n}\n\nConsole.WriteLine();\n\n// Create an IChatClient that can use the tools.\nusing IChatClient chatClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseFunctionInvocation()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\n// Have a conversation, making all tools available to the LLM.\nList messages = [];\nwhile (true)\n{\n Console.Write(\"Q: \");\n messages.Add(new(ChatRole.User, Console.ReadLine()));\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, new() { Tools = [.. tools] }))\n {\n Console.Write(update);\n updates.Add(update);\n }\n Console.WriteLine();\n\n messages.AddMessages(updates);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationRedirectDelegate.cs", "\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a method that handles the OAuth authorization URL and returns the authorization code.\n/// \n/// The authorization URL that the user needs to visit.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// A task that represents the asynchronous operation. The task result contains the authorization code if successful, or null if the operation failed or was cancelled.\n/// \n/// \n/// This delegate provides SDK consumers with full control over how the OAuth authorization flow is handled.\n/// Implementers can choose to:\n/// \n/// \n/// Start a local HTTP server and open a browser (default behavior)\n/// Display the authorization URL to the user for manual handling\n/// Integrate with a custom UI or authentication flow\n/// Use a different redirect mechanism altogether\n/// \n/// \n/// The implementation should handle user interaction to visit the authorization URL and extract\n/// the authorization code from the callback. The authorization code is typically provided as\n/// a query parameter in the redirect URI callback.\n/// \n/// \npublic delegate Task AuthorizationRedirectDelegate(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken);"], ["/csharp-sdk/samples/EverythingServer/SubscriptionMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\ninternal class SubscriptionMessageSender(IMcpServer server, HashSet subscriptions) : BackgroundService\n{\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n foreach (var uri in subscriptions)\n {\n await server.SendNotificationAsync(\"notifications/resource/updated\",\n new\n {\n Uri = uri,\n }, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(5000, stoppingToken);\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/TokenProgress.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides an tied to a specific progress token and that will issue\n/// progress notifications on the supplied endpoint.\n/// \ninternal sealed class TokenProgress(IMcpEndpoint endpoint, ProgressToken progressToken) : IProgress\n{\n /// \n public void Report(ProgressNotificationValue value)\n {\n _ = endpoint.NotifyProgressAsync(progressToken, value, CancellationToken.None);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServerPrimitive.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Represents an MCP server primitive, like a tool or a prompt.\n/// \npublic interface IMcpServerPrimitive\n{\n /// Gets the unique identifier of the primitive.\n string Id { get; }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Serilog;\nusing TestServerWithHosting.Tools;\n\nLog.Logger = new LoggerConfiguration()\n .MinimumLevel.Verbose() // Capture all log levels\n .WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"logs\", \"TestServer_.log\"),\n rollingInterval: RollingInterval.Day,\n outputTemplate: \"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}\")\n .WriteTo.Debug()\n .WriteTo.Console(standardErrorFromLevel: Serilog.Events.LogEventLevel.Verbose)\n .CreateLogger();\n\ntry\n{\n Log.Information(\"Starting server...\");\n\n var builder = Host.CreateApplicationBuilder(args);\n builder.Services.AddSerilog();\n builder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools();\n\n var app = builder.Build();\n\n await app.RunAsync();\n return 0;\n}\ncatch (Exception ex)\n{\n Log.Fatal(ex, \"Host terminated unexpectedly\");\n return 1;\n}\nfinally\n{\n Log.CloseAndFlush();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of resources it can read from has changed. \n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/Common/Polyfills/System/IO/StreamExtensions.cs", "using ModelContextProtocol;\nusing System.Buffers;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n#if !NET\nnamespace System.IO;\n\ninternal static class StreamExtensions\n{\n public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return WriteAsyncCore(stream, buffer, cancellationToken);\n\n static async ValueTask WriteAsyncCore(Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n buffer.Span.CopyTo(array);\n await stream.WriteAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n\n public static ValueTask ReadAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.ReadAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return ReadAsyncCore(stream, buffer, cancellationToken);\n static async ValueTask ReadAsyncCore(Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n int bytesRead = await stream.ReadAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n array.AsSpan(0, bytesRead).CopyTo(buffer.Span);\n return bytesRead;\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Tasks/TaskExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class TaskExtensions\n{\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n await WaitAsync((Task)task, timeout, cancellationToken).ConfigureAwait(false);\n return task.Result;\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(task);\n\n if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan)\n {\n throw new ArgumentOutOfRangeException(nameof(timeout));\n }\n\n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n cts.CancelAfter(timeout);\n\n var cancellationTask = new TaskCompletionSource();\n using var _ = cts.Token.Register(tcs => ((TaskCompletionSource)tcs!).TrySetResult(true), cancellationTask);\n await Task.WhenAny(task, cancellationTask.Task).ConfigureAwait(false);\n \n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n throw new TimeoutException();\n }\n }\n\n await task.ConfigureAwait(false);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the client to the server, informing it that the list of roots has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of tools it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ToolListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptListChangedNotification .cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of prompts it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/samples/QuickstartWeatherServer/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing QuickstartWeatherServer.Tools;\nusing System.Net.Http.Headers;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools();\n\nbuilder.Logging.AddConsole(options =>\n{\n options.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nbuilder.Services.AddSingleton(_ =>\n{\n var client = new HttpClient { BaseAddress = new Uri(\"https://api.weather.gov\") };\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n return client;\n});\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMemberTypes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Specifies the types of members that are dynamically accessed.\n///\n/// This enumeration has a attribute that allows a\n/// bitwise combination of its member values.\n/// \n[Flags]\ninternal enum DynamicallyAccessedMemberTypes\n{\n /// \n /// Specifies no members.\n /// \n None = 0,\n\n /// \n /// Specifies the default, parameterless public constructor.\n /// \n PublicParameterlessConstructor = 0x0001,\n\n /// \n /// Specifies all public constructors.\n /// \n PublicConstructors = 0x0002 | PublicParameterlessConstructor,\n\n /// \n /// Specifies all non-public constructors.\n /// \n NonPublicConstructors = 0x0004,\n\n /// \n /// Specifies all public methods.\n /// \n PublicMethods = 0x0008,\n\n /// \n /// Specifies all non-public methods.\n /// \n NonPublicMethods = 0x0010,\n\n /// \n /// Specifies all public fields.\n /// \n PublicFields = 0x0020,\n\n /// \n /// Specifies all non-public fields.\n /// \n NonPublicFields = 0x0040,\n\n /// \n /// Specifies all public nested types.\n /// \n PublicNestedTypes = 0x0080,\n\n /// \n /// Specifies all non-public nested types.\n /// \n NonPublicNestedTypes = 0x0100,\n\n /// \n /// Specifies all public properties.\n /// \n PublicProperties = 0x0200,\n\n /// \n /// Specifies all non-public properties.\n /// \n NonPublicProperties = 0x0400,\n\n /// \n /// Specifies all public events.\n /// \n PublicEvents = 0x0800,\n\n /// \n /// Specifies all non-public events.\n /// \n NonPublicEvents = 0x1000,\n\n /// \n /// Specifies all interfaces implemented by the type.\n /// \n Interfaces = 0x2000,\n\n /// \n /// Specifies all non-public constructors, including those inherited from base classes.\n /// \n NonPublicConstructorsWithInherited = NonPublicConstructors | 0x4000,\n\n /// \n /// Specifies all non-public methods, including those inherited from base classes.\n /// \n NonPublicMethodsWithInherited = NonPublicMethods | 0x8000,\n\n /// \n /// Specifies all non-public fields, including those inherited from base classes.\n /// \n NonPublicFieldsWithInherited = NonPublicFields | 0x10000,\n\n /// \n /// Specifies all non-public nested types, including those inherited from base classes.\n /// \n NonPublicNestedTypesWithInherited = NonPublicNestedTypes | 0x20000,\n\n /// \n /// Specifies all non-public properties, including those inherited from base classes.\n /// \n NonPublicPropertiesWithInherited = NonPublicProperties | 0x40000,\n\n /// \n /// Specifies all non-public events, including those inherited from base classes.\n /// \n NonPublicEventsWithInherited = NonPublicEvents | 0x80000,\n\n /// \n /// Specifies all public constructors, including those inherited from base classes.\n /// \n PublicConstructorsWithInherited = PublicConstructors | 0x100000,\n\n /// \n /// Specifies all public nested types, including those inherited from base classes.\n /// \n PublicNestedTypesWithInherited = PublicNestedTypes | 0x200000,\n\n /// \n /// Specifies all constructors, including those inherited from base classes.\n /// \n AllConstructors = PublicConstructorsWithInherited | NonPublicConstructorsWithInherited,\n\n /// \n /// Specifies all methods, including those inherited from base classes.\n /// \n AllMethods = PublicMethods | NonPublicMethodsWithInherited,\n\n /// \n /// Specifies all fields, including those inherited from base classes.\n /// \n AllFields = PublicFields | NonPublicFieldsWithInherited,\n\n /// \n /// Specifies all nested types, including those inherited from base classes.\n /// \n AllNestedTypes = PublicNestedTypesWithInherited | NonPublicNestedTypesWithInherited,\n\n /// \n /// Specifies all properties, including those inherited from base classes.\n /// \n AllProperties = PublicProperties | NonPublicPropertiesWithInherited,\n\n /// \n /// Specifies all events, including those inherited from base classes.\n /// \n AllEvents = PublicEvents | NonPublicEventsWithInherited,\n\n /// \n /// Specifies all members.\n /// \n All = ~None\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// sent from the client to the server after initialization has finished.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class InitializedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices;\n\n[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]\ninternal sealed class CallerArgumentExpressionAttribute : Attribute\n{\n public CallerArgumentExpressionAttribute(string parameterName)\n {\n ParameterName = parameterName;\n }\n\n public string ParameterName { get; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/HttpTransportMode.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Specifies the transport mode for HTTP client connections.\n/// \npublic enum HttpTransportMode\n{\n /// \n /// Automatically detect the appropriate transport by trying Streamable HTTP first, then falling back to SSE if that fails.\n /// This is the recommended mode for maximum compatibility.\n /// \n AutoDetect,\n\n /// \n /// Use only the Streamable HTTP transport.\n /// \n StreamableHttp,\n\n /// \n /// Use only the HTTP with SSE transport.\n /// \n Sse\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/RequiredMemberAttribute.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Specifies that a type has required members or that a member is required.\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\n [EditorBrowsable(EditorBrowsableState.Never)]\n internal sealed class RequiredMemberAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/IsExternalInit.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Reserved to be used by the compiler for tracking metadata.\n /// This class should not be used by developers in source code.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n internal static class IsExternalInit;\n}\n#else\n// The compiler emits a reference to the internal copy of this type in the non-.NET builds,\n// so we must include a forward to be compatible.\n[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExternalInit))]\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Channels/ChannelExtensions.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading.Channels;\n\ninternal static class ChannelExtensions\n{\n public static async IAsyncEnumerable ReadAllAsync(this ChannelReader reader, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))\n {\n while (reader.TryRead(out var item))\n {\n yield return item;\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/samples/EverythingServer/Tools/PrintEnvTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class PrintEnvTool\n{\n private static readonly JsonSerializerOptions options = new()\n {\n WriteIndented = true\n };\n\n [McpServerTool(Name = \"printEnv\"), Description(\"Prints all environment variables, helpful for debugging MCP server configuration\")]\n public static string PrintEnv() =>\n JsonSerializer.Serialize(Environment.GetEnvironmentVariables(), options);\n}\n"], ["/csharp-sdk/src/Common/CancellableStreamReader/TextReaderExtensions.cs", "namespace System.IO;\n\ninternal static class TextReaderExtensions\n{\n public static ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n {\n if (reader is CancellableStreamReader cancellableReader)\n {\n return cancellableReader.ReadLineAsync(cancellationToken)!;\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n return new ValueTask(reader.ReadLineAsync());\n }\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class EchoTool\n{\n [McpServerTool(Name = \"echo\"), Description(\"Echoes the message back to the client.\")]\n public static string Echo(string message) => $\"Echo: {message}\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionIdJsonContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\n[JsonSerializable(typeof(StatelessSessionId))]\ninternal sealed partial class StatelessSessionIdJsonContext : JsonSerializerContext;\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/ForceYielding.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading;\n\n/// \n/// await default(ForceYielding) to provide the same behavior as\n/// await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding).\n/// \ninternal readonly struct ForceYielding : INotifyCompletion, ICriticalNotifyCompletion\n{\n public ForceYielding GetAwaiter() => this;\n\n public bool IsCompleted => false;\n public void OnCompleted(Action continuation) => ThreadPool.QueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void UnsafeOnCompleted(Action continuation) => ThreadPool.UnsafeQueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void GetResult() { }\n}\n#endif"], ["/csharp-sdk/samples/AspNetCoreSseServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource, Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationDefaults.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Default values used by MCP authentication.\n/// \npublic static class McpAuthenticationDefaults\n{\n /// \n /// The default value used for authentication scheme name.\n /// \n public const string AuthenticationScheme = \"McpAuth\";\n\n /// \n /// The default value used for authentication scheme display name.\n /// \n public const string DisplayName = \"MCP Authentication\";\n}"], ["/csharp-sdk/samples/EverythingServer/Prompts/SimplePromptType.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class SimplePromptType\n{\n [McpServerPrompt(Name = \"simple_prompt\"), Description(\"A prompt without arguments\")]\n public static string SimplePrompt() => \"This is a simple prompt without arguments\";\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/AddTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AddTool\n{\n [McpServerTool(Name = \"add\"), Description(\"Adds two numbers.\")]\n public static string Add(int a, int b) => $\"The sum of {a} and {b} is {a + b}\";\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Program.cs", "using OpenTelemetry;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\nusing TestServerWithHosting.Tools;\nusing TestServerWithHosting.Resources;\n\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Services.AddMcpServer()\n .WithHttpTransport()\n .WithTools()\n .WithTools()\n .WithResources();\n\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithMetrics(b => b.AddMeter(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithLogging()\n .UseOtlpExporter();\n\nvar app = builder.Build();\n\napp.MapMcp();\n\napp.Run();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCollection.cs", "namespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their URI templates.\npublic sealed class McpServerResourceCollection()\n : McpServerPrimitiveCollection(UriTemplate.UriTemplateComparer.Instance);"], ["/csharp-sdk/src/Common/Polyfills/System/Collections/Generic/CollectionExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Collections.Generic;\n\ninternal static class CollectionExtensions\n{\n public static TValue? GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key)\n {\n return dictionary.GetValueOrDefault(key, default!);\n }\n\n public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key, TValue defaultValue)\n {\n Throw.IfNull(dictionary);\n\n return dictionary.TryGetValue(key, out TValue? value) ? value : defaultValue;\n }\n\n public static Dictionary ToDictionary(this IEnumerable> source) =>\n source.ToDictionary(kv => kv.Key, kv => kv.Value);\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Net/Http/HttpClientExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Net.Http;\n\ninternal static class HttpClientExtensions\n{\n public static async Task ReadAsStreamAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStreamAsync();\n }\n\n public static async Task ReadAsStringAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStringAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/CancellationTokenSourceExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class CancellationTokenSourceExtensions\n{\n public static Task CancelAsync(this CancellationTokenSource cancellationTokenSource)\n {\n Throw.IfNull(cancellationTokenSource);\n\n cancellationTokenSource.Cancel();\n return Task.CompletedTask;\n }\n}\n#endif"], ["/csharp-sdk/samples/EverythingServer/Tools/TinyImageTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class TinyImageTool\n{\n [McpServerTool(Name = \"getTinyImage\"), Description(\"Get a tiny image from the server\")]\n public static IEnumerable GetTinyImage() => [\n new TextContent(\"This is a tiny image:\"),\n new DataContent(MCP_TINY_IMAGE),\n new TextContent(\"The image above is the MCP tiny image.\")\n ];\n\n internal const string MCP_TINY_IMAGE =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAKsGlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgOfe9JDQEiIgJfQmSCeAlBBaAAXpYCMkAUKJMRBU7MriClZURLCs6KqIgo0idizYFsWC3QVZBNR1sWDDlXeBQ9jdd9575805c+a7c+efmf+e/z9nLgCdKZDJMlF1gCxpjjwyyI8dn5DIJvUABRiY0kBdIMyWcSMiwgCTUft3+dgGyJC9YzuU69/f/1fREImzhQBIBMbJomxhFsbHMe0TyuQ5ALg9mN9kbo5siK9gzJRjDWL8ZIhTR7hviJOHGY8fjomO5GGsDUCmCQTyVACaKeZn5wpTsTw0f4ztpSKJFGPsGbyzsmaLMMbqgiUWI8N4KD8n+S95Uv+WM1mZUyBIVfLIXoaF7C/JlmUK5v+fn+N/S1amYrSGOaa0NHlwJGaxvpAHGbNDlSxNnhI+yhLRcPwwpymCY0ZZmM1LHGWRwD9UuTZzStgop0gC+co8OfzoURZnB0SNsnx2pLJWipzHHWWBfKyuIiNG6U8T85X589Ki40Y5VxI7ZZSzM6JCx2J4Sr9cEansXywN8hurG6jce1b2X/Yr4SvX5qRFByv3LhjrXyzljuXMjlf2JhL7B4zFxCjjZTl+ylqyzAhlvDgzSOnPzo1Srs3BDuTY2gjlN0wXhESMMoRBELAhBjIhB+QggECQgBTEOeJ5Q2cUeLNl8+WS1LQcNhe7ZWI2Xyq0m8B2tHd0Bhi6syNH4j1r+C4irGtjvhWVAF4nBgcHT475Qm4BHEkCoNaO+SxnAKh3A1w5JVTIc0d8Q9cJCEAFNWCCDhiACViCLTiCK3iCLwRACIRDNCTATBBCGmRhnc+FhbAMCqAI1sNmKIOdsBv2wyE4CvVwCs7DZbgOt+AePIZ26IJX0AcfYQBBEBJCRxiIDmKImCE2iCPCQbyRACQMiUQSkCQkFZEiCmQhsgIpQoqRMmQXUokcQU4g55GrSCvyEOlAepF3yFcUh9JQJqqPmqMTUQ7KRUPRaHQGmorOQfPQfHQtWopWoAfROvQ8eh29h7ajr9B+HOBUcCycEc4Wx8HxcOG4RFwKTo5bjCvEleAqcNW4Rlwz7g6uHfca9wVPxDPwbLwt3hMfjI/BC/Fz8Ivxq/Fl+P34OvxF/B18B74P/51AJ+gRbAgeBD4hnpBKmEsoIJQQ9hJqCZcI9whdhI9EIpFFtCC6EYOJCcR04gLiauJ2Yg3xHLGV2EnsJ5FIOiQbkhcpnCQg5ZAKSFtJB0lnSbdJXaTPZBWyIdmRHEhOJEvJy8kl5APkM+Tb5G7yAEWdYkbxoIRTRJT5lHWUPZRGyk1KF2WAqkG1oHpRo6np1GXUUmo19RL1CfW9ioqKsYq7ylQVicpSlVKVwypXVDpUvtA0adY0Hm06TUFbS9tHO0d7SHtPp9PN6b70RHoOfS29kn6B/oz+WZWhaqfKVxWpLlEtV61Tva36Ro2iZqbGVZuplqdWonZM7abaa3WKurk6T12gvli9XP2E+n31fg2GhoNGuEaWxmqNAxpXNXo0SZrmmgGaIs18zd2aFzQ7GTiGCYPHEDJWMPYwLjG6mESmBZPPTGcWMQ8xW5h9WppazlqxWvO0yrVOa7WzcCxzFp+VyVrHOspqY30dpz+OO048btW46nG3x33SHq/tqy3WLtSu0b6n/VWHrROgk6GzQade56kuXtdad6ruXN0dupd0X49njvccLxxfOP7o+Ed6qJ61XqTeAr3dejf0+vUN9IP0Zfpb9S/ovzZgGfgapBtsMjhj0GvIMPQ2lBhuMjxr+JKtxeayM9ml7IvsPiM9o2AjhdEuoxajAWML4xjj5cY1xk9NqCYckxSTTSZNJn2mhqaTTReaVpk+MqOYcczSzLaYNZt9MrcwjzNfaV5v3mOhbcG3yLOosnhiSbf0sZxjWWF514poxbHKsNpudcsatXaxTrMut75pg9q42khsttu0TiBMcJ8gnVAx4b4tzZZrm2tbZdthx7ILs1tuV2/3ZqLpxMSJGyY2T/xu72Kfab/H/rGDpkOIw3KHRod3jtaOQsdyx7tOdKdApyVODU5vnW2cxc47nB+4MFwmu6x0aXL509XNVe5a7drrZuqW5LbN7T6HyYngrOZccSe4+7kvcT/l/sXD1SPH46jHH562nhmeBzx7JllMEk/aM6nTy9hL4LXLq92b7Z3k/ZN3u4+Rj8Cnwue5r4mvyHevbzfXipvOPch942fvJ/er9fvE8+At4p3zx/kH+Rf6twRoBsQElAU8CzQOTA2sCuwLcglaEHQumBAcGrwh+D5fny/kV/L7QtxCFoVcDKWFRoWWhT4Psw6ThzVORieHTN44+ckUsynSKfXhEM4P3xj+NMIiYk7EyanEqRFTy6e+iHSIXBjZHMWImhV1IOpjtF/0uujHMZYxipimWLXY6bGVsZ/i/OOK49rjJ8Yvir+eoJsgSWhIJCXGJu5N7J8WMG3ztK7pLtMLprfNsJgxb8bVmbozM2eenqU2SzDrWBIhKS7pQNI3QbigQtCfzE/eltwn5Am3CF+JfEWbRL1iL3GxuDvFK6U4pSfVK3Vjam+aT1pJ2msJT1ImeZsenL4z/VNGeMa+jMHMuMyaLHJWUtYJqaY0Q3pxtsHsebNbZTayAln7HI85m+f0yUPle7OR7BnZDTlMbDi6obBU/KDoyPXOLc/9PDd27rF5GvOk827Mt56/an53XmDezwvwC4QLmhYaLVy2sGMRd9Guxcji5MVNS0yW5C/pWhq0dP8y6rKMZb8st19evPzDirgVjfn6+UvzO38I+qGqQLVAXnB/pefKnT/if5T82LLKadXWVd8LRYXXiuyLSoq+rRauvrbGYU3pmsG1KWtb1rmu27GeuF66vm2Dz4b9xRrFecWdGydvrNvE3lS46cPmWZuvljiX7NxC3aLY0l4aVtqw1XTr+q3fytLK7pX7ldds09u2atun7aLtt3f47qjeqb+zaOfXnyQ/PdgVtKuuwryiZDdxd+7uF3ti9zT/zPm5cq/u3qK9f+6T7mvfH7n/YqVbZeUBvQPrqtAqRVXvwekHbx3yP9RQbVu9q4ZVU3QYDisOvzySdKTtaOjRpmOcY9XHzY5vq2XUFtYhdfPr+urT6tsbEhpaT4ScaGr0bKw9aXdy3ymjU+WntU6vO0M9k39m8Gze2f5zsnOvz6ee72ya1fT4QvyFuxenXmy5FHrpyuXAyxeauc1nr3hdOXXV4+qJa5xr9dddr9fdcLlR+4vLL7Utri11N91uNtzyv9XYOqn1zG2f2+fv+N+5fJd/9/q9Kfda22LaHtyffr/9gehBz8PMh28f5T4aeLz0CeFJ4VP1pyXP9J5V/Gr1a027a/vpDv+OG8+jnj/uFHa++i37t29d+S/oL0q6Dbsrexx7TvUG9t56Oe1l1yvZq4HXBb9r/L7tjeWb43/4/nGjL76v66387eC71e913u/74PyhqT+i/9nHrI8Dnwo/63ze/4Xzpflr3NfugbnfSN9K/7T6s/F76Pcng1mDgzKBXDA8CuAwRVNSAN7tA6AnADCwGYI6bWSmHhZk5D9gmOA/8cjcPSyuANWYGRqNeOcADmNqvhRAzRdgaCyK9gXUyUmpo/Pv8Kw+JAbYv8K0HECi2x6tebQU/iEjc/xf+v6nBWXWv9l/AV0EC6JTIblRAAAAeGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAJAAAAABAAAAkAAAAAEAAqACAAQAAAABAAAAFKADAAQAAAABAAAAFAAAAAAXNii1AAAACXBIWXMAABYlAAAWJQFJUiTwAAAB82lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOllSZXNvbHV0aW9uPjE0NDwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+MTQ0PC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KReh49gAAAjRJREFUOBGFlD2vMUEUx2clvoNCcW8hCqFAo1dKhEQpvsF9KrWEBh/ALbQ0KkInBI3SWyGPCCJEQliXgsTLefaca/bBWjvJzs6cOf/fnDkzOQJIjWm06/XKBEGgD8c6nU5VIWgBtQDPZPWtJE8O63a7LBgMMo/Hw0ql0jPjcY4RvmqXy4XMjUYDUwLtdhtmsxnYbDbI5/O0djqdFFKmsEiGZ9jP9gem0yn0ej2Yz+fg9XpfycimAD7DttstQTDKfr8Po9GIIg6Hw1Cr1RTgB+A72GAwgMPhQLBMJgNSXsFqtUI2myUo18pA6QJogefsPrLBX4QdCVatViklw+EQRFGEj88P2O12pEUGATmsXq+TaLPZ0AXgMRF2vMEqlQoJTSYTpNNpApvNZliv1/+BHDaZTAi2Wq1A3Ig0xmMej7+RcZjdbodUKkWAaDQK+GHjHPnImB88JrZIJAKFQgH2+z2BOczhcMiwRCIBgUAA+NN5BP6mj2DYff35gk6nA61WCzBn2JxO5wPM7/fLz4vD0E+OECfn8xl/0Gw2KbLxeAyLxQIsFgt8p75pDSO7h/HbpUWpewCike9WLpfB7XaDy+WCYrFI/slk8i0MnRRAUt46hPMI4vE4+Hw+ec7t9/44VgWigEeby+UgFArJWjUYOqhWG6x50rpcSfR6PVUfNOgEVRlTX0HhrZBKz4MZjUYWi8VoA+lc9H/VaRZYjBKrtXR8tlwumcFgeMWRbZpA9ORQWfVm8A/FsrLaxebd5wAAAABJRU5ErkJggg==\";\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/SetsRequiredMembersAttribute.cs", "#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]\n internal sealed class SetsRequiredMembersAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/IO/TextWriterExtensions.cs", "#if !NET\nnamespace System.IO;\n\ninternal static class TextWriterExtensions\n{\n public static async Task FlushAsync(this TextWriter writer, CancellationToken cancellationToken)\n {\n cancellationToken.ThrowIfCancellationRequested();\n await writer.FlushAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/UserIdClaim.cs", "namespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed record UserIdClaim(string Type, string Value, string Issuer);\n"]], "task_instance_info": {"created_time": "2025-08-20 18:38:49", "created_task_model": "DeepSeek-R1", "class_skeleton": "public\nsealed\nclass\nJsonRpcRequest\n: JsonRpcMessageWithId\n{\n[JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n[JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\ninternal JsonRpcRequest WithId (RequestId id) {}\n}", "code_description": "This code segment functions to: Define the structure for a remote procedure call request by specifying the operation to be executed and its associated parameters, while providing mechanisms to associate unique identifiers for request tracking and response correlation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\ninternal JsonRpcRequest WithId(RequestId id)\n{\n return new JsonRpcRequest\n {\n Id = id,\n Method = this.Method,\n Params = this.Params\n };\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-39-16"}, "editdistance_info": {"edit_distance": 24.2991, "calculate_time": "2025-08-20 18:39:16", "true_code_clean": "public sealed class JsonRpcRequest : JsonRpcMessageWithId\n{\n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n internal JsonRpcRequest WithId(RequestId id)\n {\n return new JsonRpcRequest\n {\n JsonRpc = JsonRpc,\n Id = id,\n Method = Method,\n Params = Params,\n RelatedTransport = RelatedTransport,\n };\n }\n}", "predict_code_clean": "internal JsonRpcRequest WithId(RequestId id)\n{\n return new JsonRpcRequest\n {\n Id = id,\n Method = this.Method,\n Params = this.Params\n };\n}"}} {"repo_name": "csharp-sdk", "file_name": "/csharp-sdk/samples/EverythingServer/Resources/SimpleResourceType.cs", "inference_info": {"prefix_code": "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Resources;\n\n", "suffix_code": "\n", "middle_code": "[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test:\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n [McpServerResource(UriTemplate = \"test:\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id)\n {\n int index = id - 1;\n if ((uint)index >= ResourceGenerator.Resources.Count)\n {\n throw new NotSupportedException($\"Unknown resource: {requestContext.Params?.Uri}\");\n }\n var resource = ResourceGenerator.Resources[index];\n return resource.MimeType == \"text/plain\" ?\n new TextResourceContents\n {\n Text = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n } :\n new BlobResourceContents\n {\n Blob = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n };\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerResource : McpServerResource\n{\n private readonly Regex? _uriParser;\n private readonly string[] _templateVariableNames = [];\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n object? target,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerResourceCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n // These parameters are the ones and only ones to include in the schema. The schema\n // won't be consumed by anyone other than this instance, which will use it to determine\n // which properties should show up in the URI template.\n if (pi.Name is not null && GetConverter(pi.ParameterType) is { } converter)\n {\n return new()\n {\n ExcludeFromSchema = false,\n BindParameter = (pi, args) =>\n {\n if (args.TryGetValue(pi.Name!, out var value))\n {\n return\n value is null || pi.ParameterType.IsInstanceOfType(value) ? value :\n value is string stringValue ? converter(stringValue) :\n throw new ArgumentException($\"Parameter '{pi.Name}' is of type '{pi.ParameterType}', but value '{value}' is of type '{value.GetType()}'.\");\n }\n\n return\n pi.HasDefaultValue ? pi.DefaultValue :\n throw new ArgumentException($\"Missing a value for the required parameter '{pi.Name}'.\");\n },\n };\n }\n\n return default;\n },\n };\n\n private static readonly ConcurrentDictionary> s_convertersCache = [];\n\n private static Func? GetConverter(Type type)\n {\n Type key = type;\n\n if (s_convertersCache.TryGetValue(key, out var converter))\n {\n return converter;\n }\n\n if (Nullable.GetUnderlyingType(type) is { } underlyingType)\n {\n // We will have already screened out null values by the time the converter is used,\n // so we can parse just the underlying type.\n type = underlyingType;\n }\n\n if (type == typeof(string) || type == typeof(object)) converter = static s => s;\n if (type == typeof(bool)) converter = static s => bool.Parse(s);\n if (type == typeof(char)) converter = static s => char.Parse(s);\n if (type == typeof(byte)) converter = static s => byte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(sbyte)) converter = static s => sbyte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ushort)) converter = static s => ushort.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(short)) converter = static s => short.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(uint)) converter = static s => uint.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(int)) converter = static s => int.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ulong)) converter = static s => ulong.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(long)) converter = static s => long.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(float)) converter = static s => float.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(double)) converter = static s => double.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(decimal)) converter = static s => decimal.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeSpan)) converter = static s => TimeSpan.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTime)) converter = static s => DateTime.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTimeOffset)) converter = static s => DateTimeOffset.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Uri)) converter = static s => new Uri(s, UriKind.RelativeOrAbsolute);\n if (type == typeof(Guid)) converter = static s => Guid.Parse(s);\n if (type == typeof(Version)) converter = static s => Version.Parse(s);\n#if NET\n if (type == typeof(Half)) converter = static s => Half.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Int128)) converter = static s => Int128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UInt128)) converter = static s => UInt128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(IntPtr)) converter = static s => IntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UIntPtr)) converter = static s => UIntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateOnly)) converter = static s => DateOnly.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeOnly)) converter = static s => TimeOnly.Parse(s, CultureInfo.InvariantCulture);\n#endif\n if (type.IsEnum) converter = s => Enum.Parse(type, s);\n\n if (type.GetCustomAttribute() is TypeConverterAttribute tca &&\n Type.GetType(tca.ConverterTypeName, throwOnError: false) is { } converterType &&\n Activator.CreateInstance(converterType) is TypeConverter typeConverter &&\n typeConverter.CanConvertFrom(typeof(string)))\n {\n converter = s => typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, s);\n }\n\n if (converter is not null)\n {\n s_convertersCache.TryAdd(key, converter);\n }\n\n return converter;\n }\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerResource Create(AIFunction function, McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(function);\n\n string name = options?.Name ?? function.Name;\n\n ResourceTemplate resource = new()\n {\n UriTemplate = options?.UriTemplate ?? DeriveUriTemplate(name, function),\n Name = name,\n Title = options?.Title,\n Description = options?.Description,\n MimeType = options?.MimeType ?? \"application/octet-stream\",\n };\n\n return new AIFunctionMcpServerResource(function, resource);\n }\n\n private static McpServerResourceCreateOptions DeriveOptions(MemberInfo member, McpServerResourceCreateOptions? options)\n {\n McpServerResourceCreateOptions newOptions = options?.Clone() ?? new();\n\n if (member.GetCustomAttribute() is { } resourceAttr)\n {\n newOptions.UriTemplate ??= resourceAttr.UriTemplate;\n newOptions.Name ??= resourceAttr.Name;\n newOptions.Title ??= resourceAttr.Title;\n newOptions.MimeType ??= resourceAttr.MimeType;\n }\n\n if (member.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Derives a name to be used as a resource name.\n private static string DeriveUriTemplate(string name, AIFunction function)\n {\n StringBuilder template = new();\n\n template.Append(\"resource://mcp/\").Append(Uri.EscapeDataString(name));\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n string separator = \"{?\";\n foreach (var prop in properties.EnumerateObject())\n {\n template.Append(separator).Append(prop.Name);\n separator = \",\";\n }\n\n if (separator == \",\")\n {\n template.Append('}');\n }\n }\n\n return template.ToString();\n }\n\n /// Gets the wrapped by this resource.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerResource(AIFunction function, ResourceTemplate resourceTemplate)\n {\n AIFunction = function;\n ProtocolResourceTemplate = resourceTemplate;\n ProtocolResource = resourceTemplate.AsResource();\n\n if (ProtocolResource is null)\n {\n _uriParser = UriTemplate.CreateParser(resourceTemplate.UriTemplate);\n _templateVariableNames = _uriParser.GetGroupNames().Where(n => n != \"0\").ToArray();\n }\n }\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// \n public override Resource? ProtocolResource { get; }\n\n /// \n public override async ValueTask ReadAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n Throw.IfNull(request.Params);\n Throw.IfNull(request.Params.Uri);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check to see if this URI template matches the request URI. If it doesn't, return null.\n // For templates, use the Regex to parse. For static resources, we can just compare the URIs.\n Match? match = null;\n if (_uriParser is not null)\n {\n match = _uriParser.Match(request.Params.Uri);\n if (!match.Success)\n {\n return null;\n }\n }\n else if (!UriTemplate.UriTemplateComparer.Instance.Equals(request.Params.Uri, ProtocolResource!.Uri))\n {\n return null;\n }\n\n // Build up the arguments for the AIFunction call, including all of the name/value pairs from the URI.\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n // For templates, populate the arguments from the URI template.\n if (match is not null)\n {\n foreach (string varName in _templateVariableNames)\n {\n if (match.Groups[varName] is { Success: true } value)\n {\n arguments[varName] = Uri.UnescapeDataString(value.Value);\n }\n }\n }\n\n // Invoke the function.\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n // And process the result.\n return result switch\n {\n ReadResourceResult readResourceResult => readResourceResult,\n\n ResourceContents content => new()\n {\n Contents = [content],\n },\n\n TextContent tc => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = tc.Text }],\n },\n\n DataContent dc => new()\n {\n Contents = [new BlobResourceContents { Uri = request.Params!.Uri, MimeType = dc.MediaType, Blob = dc.Base64Data.ToString() }],\n },\n\n string text => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = text }],\n },\n\n IEnumerable contents => new()\n {\n Contents = contents.ToList(),\n },\n\n IEnumerable aiContents => new()\n {\n Contents = aiContents.Select(\n ac => ac switch\n {\n TextContent tc => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = tc.Text\n },\n\n DataContent dc => new BlobResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = dc.MediaType,\n Blob = dc.Base64Data.ToString()\n },\n\n _ => throw new InvalidOperationException($\"Unsupported AIContent type '{ac.GetType()}' returned from resource function.\"),\n }).ToList(),\n },\n\n IEnumerable strings => new()\n {\n Contents = strings.Select(text => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = text\n }).ToList(),\n },\n\n null => throw new InvalidOperationException(\"Null result returned from resource function.\"),\n\n _ => throw new InvalidOperationException($\"Unsupported result type '{result.GetType()}' returned from resource function.\"),\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceContents.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class representing contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// serves as the base class for different types of resources that can be \n/// exchanged through the Model Context Protocol. Resources are identified by URIs and can contain\n/// different types of data.\n/// \n/// \n/// This class is abstract and has two concrete implementations:\n/// \n/// - For text-based resources\n/// - For binary data resources\n/// \n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class ResourceContents\n{\n /// Prevent external derivations.\n private protected ResourceContents()\n {\n }\n\n /// \n /// Gets or sets the URI of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n public string Uri { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the MIME type of the resource content.\n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ResourceContents? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? uri = null;\n string? mimeType = null;\n string? blob = null;\n string? text = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"blob\":\n blob = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n if (blob is not null)\n {\n return new BlobResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Blob = blob,\n Meta = meta,\n };\n }\n\n if (text is not null)\n {\n return new TextResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Text = text,\n Meta = meta,\n };\n }\n\n return null;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ResourceContents value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n writer.WriteString(\"uri\", value.Uri);\n writer.WriteString(\"mimeType\", value.MimeType);\n \n Debug.Assert(value is BlobResourceContents or TextResourceContents);\n if (value is BlobResourceContents blobResource)\n {\n writer.WriteString(\"blob\", blobResource.Blob);\n }\n else if (value is TextResourceContents textResource)\n {\n writer.WriteString(\"text\", textResource.Text);\n }\n\n if (value.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, value.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContentBlock.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents content within the Model Context Protocol (MCP).\n/// \n/// \n/// \n/// The class is a fundamental type in the MCP that can represent different forms of content\n/// based on the property. Derived types like , ,\n/// and provide the type-specific content.\n/// \n/// \n/// This class is used throughout the MCP for representing content in messages, tool responses,\n/// and other communication between clients and servers.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\npublic abstract class ContentBlock\n{\n /// Prevent external derivations.\n private protected ContentBlock()\n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This determines the structure of the content object. Valid values include \"image\", \"audio\", \"text\", \"resource\", and \"resource_link\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Gets or sets optional annotations for the content.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the content. Clients can use this information to filter or prioritize content for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ContentBlock? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? text = null;\n string? name = null;\n string? data = null;\n string? mimeType = null;\n string? uri = null;\n string? description = null;\n long? size = null;\n ResourceContents? resource = null;\n Annotations? annotations = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"data\":\n data = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"size\":\n size = reader.GetInt64();\n break;\n\n case \"resource\":\n resource = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.ResourceContents);\n break;\n\n case \"annotations\":\n annotations = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.Annotations);\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n return type switch\n {\n \"text\" => new TextContentBlock\n {\n Text = text ?? throw new JsonException(\"Text contents must be provided for 'text' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"image\" => new ImageContentBlock\n {\n Data = data ?? throw new JsonException(\"Image data must be provided for 'image' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'image' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"audio\" => new AudioContentBlock\n {\n Data = data ?? throw new JsonException(\"Audio data must be provided for 'audio' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'audio' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource\" => new EmbeddedResourceBlock\n {\n Resource = resource ?? throw new JsonException(\"Resource contents must be provided for 'resource' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource_link\" => new ResourceLinkBlock\n {\n Uri = uri ?? throw new JsonException(\"URI must be provided for 'resource_link' type.\"),\n Name = name ?? throw new JsonException(\"Name must be provided for 'resource_link' type.\"),\n Description = description,\n MimeType = mimeType,\n Size = size,\n Annotations = annotations,\n },\n\n _ => throw new JsonException($\"Unknown content type: '{type}'\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case TextContentBlock textContent:\n writer.WriteString(\"text\", textContent.Text);\n if (textContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, textContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ImageContentBlock imageContent:\n writer.WriteString(\"data\", imageContent.Data);\n writer.WriteString(\"mimeType\", imageContent.MimeType);\n if (imageContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, imageContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case AudioContentBlock audioContent:\n writer.WriteString(\"data\", audioContent.Data);\n writer.WriteString(\"mimeType\", audioContent.MimeType);\n if (audioContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, audioContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case EmbeddedResourceBlock embeddedResource:\n writer.WritePropertyName(\"resource\");\n JsonSerializer.Serialize(writer, embeddedResource.Resource, McpJsonUtilities.JsonContext.Default.ResourceContents);\n if (embeddedResource.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, embeddedResource.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ResourceLinkBlock resourceLink:\n writer.WriteString(\"uri\", resourceLink.Uri);\n writer.WriteString(\"name\", resourceLink.Name);\n if (resourceLink.Description is not null)\n {\n writer.WriteString(\"description\", resourceLink.Description);\n }\n if (resourceLink.MimeType is not null)\n {\n writer.WriteString(\"mimeType\", resourceLink.MimeType);\n }\n if (resourceLink.Size.HasValue)\n {\n writer.WriteNumber(\"size\", resourceLink.Size.Value);\n }\n break;\n }\n\n if (value.Annotations is { } annotations)\n {\n writer.WritePropertyName(\"annotations\");\n JsonSerializer.Serialize(writer, annotations, McpJsonUtilities.JsonContext.Default.Annotations);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// Represents text provided to or from an LLM.\npublic sealed class TextContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public TextContentBlock() => Type = \"text\";\n\n /// \n /// Gets or sets the text content of the message.\n /// \n [JsonPropertyName(\"text\")]\n public required string Text { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents an image provided to or from an LLM.\npublic sealed class ImageContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ImageContentBlock() => Type = \"image\";\n\n /// \n /// Gets or sets the base64-encoded image data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"image/png\" and \"image/jpeg\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents audio provided to or from an LLM.\npublic sealed class AudioContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public AudioContentBlock() => Type = \"audio\";\n\n /// \n /// Gets or sets the base64-encoded audio data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"audio/wav\" and \"audio/mp3\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents the contents of a resource, embedded into a prompt or tool call result.\n/// \n/// It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user.\n/// \npublic sealed class EmbeddedResourceBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public EmbeddedResourceBlock() => Type = \"resource\";\n\n /// \n /// Gets or sets the resource content of the message when is \"resource\".\n /// \n /// \n /// \n /// Resources can be either text-based () or \n /// binary (), allowing for flexible data representation.\n /// Each resource has a URI that can be used for identification and retrieval.\n /// \n /// \n [JsonPropertyName(\"resource\")]\n public required ResourceContents Resource { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents a resource that the server is capable of reading, included in a prompt or tool call result.\n/// \n/// Resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n/// \npublic sealed class ResourceLinkBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ResourceLinkBlock() => Type = \"resource_link\";\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for this resource.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n}"], ["/csharp-sdk/samples/EverythingServer/ResourceGenerator.cs", "using ModelContextProtocol.Protocol;\n\nnamespace EverythingServer;\n\nstatic class ResourceGenerator\n{\n private static readonly List _resources = Enumerable.Range(1, 100).Select(i =>\n {\n var uri = $\"test://template/resource/{i}\";\n if (i % 2 != 0)\n {\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"text/plain\",\n Description = $\"Resource {i}: This is a plaintext resource\"\n };\n }\n else\n {\n var buffer = System.Text.Encoding.UTF8.GetBytes($\"Resource {i}: This is a base64 blob\");\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"application/octet-stream\",\n Description = Convert.ToBase64String(buffer)\n };\n }\n }).ToList();\n\n public static IReadOnlyList Resources => _resources;\n}"], ["/csharp-sdk/samples/EverythingServer/Program.cs", "using EverythingServer;\nusing EverythingServer.Prompts;\nusing EverythingServer.Resources;\nusing EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Resources;\nusing OpenTelemetry.Trace;\n\nvar builder = Host.CreateApplicationBuilder(args);\nbuilder.Logging.AddConsole(consoleLogOptions =>\n{\n // Configure all logs to go to stderr\n consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nHashSet subscriptions = [];\nvar _minimumLoggingLevel = LoggingLevel.Debug;\n\nbuilder.Services\n .AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithPrompts()\n .WithPrompts()\n .WithResources()\n .WithSubscribeToResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n\n if (uri is not null)\n {\n subscriptions.Add(uri);\n\n await ctx.Server.SampleAsync([\n new ChatMessage(ChatRole.System, \"You are a helpful test server\"),\n new ChatMessage(ChatRole.User, $\"Resource {uri}, context: A new subscription was started\"),\n ],\n options: new ChatOptions\n {\n MaxOutputTokens = 100,\n Temperature = 0.7f,\n },\n cancellationToken: ct);\n }\n\n return new EmptyResult();\n })\n .WithUnsubscribeFromResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n if (uri is not null)\n {\n subscriptions.Remove(uri);\n }\n return new EmptyResult();\n })\n .WithCompleteHandler(async (ctx, ct) =>\n {\n var exampleCompletions = new Dictionary>\n {\n { \"style\", [\"casual\", \"formal\", \"technical\", \"friendly\"] },\n { \"temperature\", [\"0\", \"0.5\", \"0.7\", \"1.0\"] },\n { \"resourceId\", [\"1\", \"2\", \"3\", \"4\", \"5\"] }\n };\n\n if (ctx.Params is not { } @params)\n {\n throw new NotSupportedException($\"Params are required.\");\n }\n\n var @ref = @params.Ref;\n var argument = @params.Argument;\n\n if (@ref is ResourceTemplateReference rtr)\n {\n var resourceId = rtr.Uri?.Split(\"/\").Last();\n\n if (resourceId is null)\n {\n return new CompleteResult();\n }\n\n var values = exampleCompletions[\"resourceId\"].Where(id => id.StartsWith(argument.Value));\n\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n if (@ref is PromptReference pr)\n {\n if (!exampleCompletions.TryGetValue(argument.Name, out IEnumerable? value))\n {\n throw new NotSupportedException($\"Unknown argument name: {argument.Name}\");\n }\n\n var values = value.Where(value => value.StartsWith(argument.Value));\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n throw new NotSupportedException($\"Unknown reference type: {@ref.Type}\");\n })\n .WithSetLoggingLevelHandler(async (ctx, ct) =>\n {\n if (ctx.Params?.Level is null)\n {\n throw new McpException(\"Missing required argument 'level'\", McpErrorCode.InvalidParams);\n }\n\n _minimumLoggingLevel = ctx.Params.Level;\n\n await ctx.Server.SendNotificationAsync(\"notifications/message\", new\n {\n Level = \"debug\",\n Logger = \"test-server\",\n Data = $\"Logging level set to {_minimumLoggingLevel}\",\n }, cancellationToken: ct);\n\n return new EmptyResult();\n });\n\nResourceBuilder resource = ResourceBuilder.CreateDefault().AddService(\"everything-server\");\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithMetrics(b => b.AddMeter(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithLogging(b => b.SetResourceBuilder(resource))\n .UseOtlpExporter();\n\nbuilder.Services.AddSingleton(subscriptions);\nbuilder.Services.AddHostedService();\nbuilder.Services.AddHostedService();\n\nbuilder.Services.AddSingleton>(_ => () => _minimumLoggingLevel);\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/AIContentExtensions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\n#if !NET\nusing System.Runtime.InteropServices;\n#endif\nusing System.Text.Json;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for converting between Model Context Protocol (MCP) types and Microsoft.Extensions.AI types.\n/// \n/// \n/// This class serves as an adapter layer between Model Context Protocol (MCP) types and the model types\n/// from the Microsoft.Extensions.AI namespace.\n/// \npublic static class AIContentExtensions\n{\n /// \n /// Converts a to a object.\n /// \n /// The prompt message to convert.\n /// A object created from the prompt message.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries.\n /// \n public static ChatMessage ToChatMessage(this PromptMessage promptMessage)\n {\n Throw.IfNull(promptMessage);\n\n AIContent? content = ToAIContent(promptMessage.Content);\n\n return new()\n {\n RawRepresentation = promptMessage,\n Role = promptMessage.Role == Role.User ? ChatRole.User : ChatRole.Assistant,\n Contents = content is not null ? [content] : [],\n };\n }\n\n /// \n /// Converts a to a object.\n /// \n /// The tool result to convert.\n /// The identifier for the function call request that triggered the tool invocation.\n /// A object created from the tool result.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries. It produces a\n /// message containing a with result as a\n /// serialized .\n /// \n public static ChatMessage ToChatMessage(this CallToolResult result, string callId)\n {\n Throw.IfNull(result);\n Throw.IfNull(callId);\n\n return new(ChatRole.Tool, [new FunctionResultContent(callId, JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult))\n {\n RawRepresentation = result,\n }]);\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The prompt result containing messages to convert.\n /// A list of objects created from the prompt messages.\n /// \n /// This method transforms protocol-specific objects from a Model Context Protocol\n /// prompt result into standard objects that can be used with AI client libraries.\n /// \n public static IList ToChatMessages(this GetPromptResult promptResult)\n {\n Throw.IfNull(promptResult);\n\n return promptResult.Messages.Select(m => m.ToChatMessage()).ToList();\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The chat message to convert.\n /// A list of objects created from the chat message's contents.\n /// \n /// This method transforms standard objects used with AI client libraries into\n /// protocol-specific objects for the Model Context Protocol system.\n /// Only representable content items are processed.\n /// \n public static IList ToPromptMessages(this ChatMessage chatMessage)\n {\n Throw.IfNull(chatMessage);\n\n Role r = chatMessage.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n List messages = [];\n foreach (var content in chatMessage.Contents)\n {\n if (content is TextContent or DataContent)\n {\n messages.Add(new PromptMessage { Role = r, Content = content.ToContent() });\n }\n }\n\n return messages;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// \n /// The created . If the content can't be converted (such as when it's a resource link), is returned.\n /// \n /// \n /// This method converts Model Context Protocol content types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent? ToAIContent(this ContentBlock content)\n {\n Throw.IfNull(content);\n\n AIContent? ac = content switch\n {\n TextContentBlock textContent => new TextContent(textContent.Text),\n ImageContentBlock imageContent => new DataContent(Convert.FromBase64String(imageContent.Data), imageContent.MimeType),\n AudioContentBlock audioContent => new DataContent(Convert.FromBase64String(audioContent.Data), audioContent.MimeType),\n EmbeddedResourceBlock resourceContent => resourceContent.Resource.ToAIContent(),\n _ => null,\n };\n\n if (ac is not null)\n {\n ac.RawRepresentation = content;\n }\n\n return ac;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// The created .\n /// \n /// This method converts Model Context Protocol resource types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent ToAIContent(this ResourceContents content)\n {\n Throw.IfNull(content);\n\n AIContent ac = content switch\n {\n BlobResourceContents blobResource => new DataContent(Convert.FromBase64String(blobResource.Blob), blobResource.MimeType ?? \"application/octet-stream\"),\n TextResourceContents textResource => new TextContent(textResource.Text),\n _ => throw new NotSupportedException($\"Resource type '{content.GetType().Name}' is not supported.\")\n };\n\n (ac.AdditionalProperties ??= [])[\"uri\"] = content.Uri;\n ac.RawRepresentation = content;\n\n return ac;\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// The created instances.\n /// \n /// \n /// This method converts a collection of Model Context Protocol content objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple content items, such as\n /// when processing the contents of a message or response.\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic for text, images, audio, and resources.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent).OfType()];\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// A list of objects created from the resource contents.\n /// \n /// \n /// This method converts a collection of Model Context Protocol resource objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple resources, such as\n /// when processing the contents of a .\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic: text resources become objects and\n /// binary resources become objects.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent)];\n }\n\n internal static ContentBlock ToContent(this AIContent content) =>\n content switch\n {\n TextContent textContent => new TextContentBlock\n {\n Text = textContent.Text,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") => new ImageContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"audio\") => new AudioContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent => new EmbeddedResourceBlock\n {\n Resource = new BlobResourceContents\n {\n Blob = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n }\n },\n\n _ => new TextContentBlock\n {\n Text = JsonSerializer.Serialize(content, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))),\n }\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/Client/McpClientResourceTemplate.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource template that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource template defined on an MCP server. It allows\n/// retrieving the resource template's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResourceTemplate\n{\n private readonly IMcpClient _client;\n\n internal McpClientResourceTemplate(IMcpClient client, ResourceTemplate resourceTemplate)\n {\n _client = client;\n ProtocolResourceTemplate = resourceTemplate;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource template,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the URI template of the resource template.\n public string UriTemplate => ProtocolResourceTemplate.UriTemplate;\n\n /// Gets the name of the resource template.\n public string Name => ProtocolResourceTemplate.Name;\n\n /// Gets the title of the resource template.\n public string? Title => ProtocolResourceTemplate.Title;\n\n /// Gets a description of the resource template.\n public string? Description => ProtocolResourceTemplate.Description;\n\n /// Gets a media (MIME) type of the resource template.\n public string? MimeType => ProtocolResourceTemplate.MimeType;\n\n /// \n /// Gets this resource template's content by formatting a URI from the template and supplied arguments\n /// and sending a request to the server.\n /// \n /// A dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource template's result with content and messages.\n public ValueTask ReadAsync(\n IReadOnlyDictionary arguments,\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(UriTemplate, arguments, cancellationToken);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceTemplate.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource template that the server is capable of reading.\n/// \n/// \n/// Resource templates provide metadata about resources available on the server,\n/// including how to construct URIs for those resources.\n/// \npublic sealed class ResourceTemplate : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI template (according to RFC 6570) that can be used to construct resource URIs.\n /// \n [JsonPropertyName(\"uriTemplate\")]\n public required string UriTemplate { get; init; }\n\n /// \n /// Gets or sets a description of what this resource template represents.\n /// \n /// \n /// \n /// This description helps clients understand the purpose and content of resources\n /// that can be generated from this template. It can be used by client applications\n /// to provide context about available resource types or to display in user interfaces.\n /// \n /// \n /// For AI models, this description can serve as a hint about when and how to use\n /// the resource template, enhancing the model's ability to generate appropriate URIs.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource template, if known.\n /// \n /// \n /// \n /// Specifies the expected format of resources that can be generated from this template.\n /// This helps clients understand what type of content to expect when accessing resources\n /// created using this template.\n /// \n /// \n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, or \"application/json\" for JSON data.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource template.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource template. Clients can use this information to filter\n /// or prioritize resource templates for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n\n /// Gets whether contains any template expressions.\n [JsonIgnore]\n public bool IsTemplated => UriTemplate.Contains('{');\n\n /// Converts the into a .\n /// A if is ; otherwise, .\n public Resource? AsResource()\n {\n if (IsTemplated)\n {\n return null;\n }\n\n return new()\n {\n Uri = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n Annotations = Annotations,\n Meta = Meta,\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Reference.cs", "using ModelContextProtocol.Client;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a reference to a resource or prompt in the Model Context Protocol.\n/// \n/// \n/// \n/// References are commonly used with to request completion suggestions for arguments,\n/// and with other methods that need to reference resources or prompts.\n/// \n/// \n/// See the schema for details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class Reference\n{\n /// Prevent external derivations.\n private protected Reference() \n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This can be \"ref/resource\" or \"ref/prompt\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override Reference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? name = null;\n string? title = null;\n string? uri = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n default:\n break;\n }\n }\n\n // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n\n switch (type)\n {\n case \"ref/prompt\":\n if (name is null)\n {\n throw new JsonException(\"Prompt references must have a 'name' property.\");\n }\n\n return new PromptReference { Name = name, Title = title };\n\n case \"ref/resource\":\n if (uri is null)\n {\n throw new JsonException(\"Resource references must have a 'uri' property.\");\n }\n\n return new ResourceTemplateReference { Uri = uri };\n\n default:\n throw new JsonException($\"Unknown content type: '{type}'\");\n }\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, Reference value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case PromptReference pr:\n writer.WriteString(\"name\", pr.Name);\n if (pr.Title is not null)\n {\n writer.WriteString(\"title\", pr.Title);\n }\n break;\n\n case ResourceTemplateReference rtr:\n writer.WriteString(\"uri\", rtr.Uri);\n break;\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// \n/// Represents a reference to a prompt, identified by its name.\n/// \npublic sealed class PromptReference : Reference, IBaseMetadata\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public PromptReference() => Type = \"ref/prompt\";\n\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Name}\\\"\";\n}\n\n/// \n/// Represents a reference to a resource or resource template definition.\n/// \npublic sealed class ResourceTemplateReference : Reference\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public ResourceTemplateReference() => Type = \"ref/resource\";\n\n /// \n /// Gets or sets the URI or URI template of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public required string? Uri { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Uri}\\\"\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationHandler.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Authentication;\nusing System.Text.Encodings.Web;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Authentication handler for MCP protocol that adds resource metadata to challenge responses\n/// and handles resource metadata endpoint requests.\n/// \npublic class McpAuthenticationHandler : AuthenticationHandler, IAuthenticationRequestHandler\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationHandler(\n IOptionsMonitor options,\n ILoggerFactory logger,\n UrlEncoder encoder)\n : base(options, logger, encoder)\n {\n }\n\n /// \n public async Task HandleRequestAsync()\n {\n // Check if the request is for the resource metadata endpoint\n string requestPath = Request.Path.Value ?? string.Empty;\n\n string expectedMetadataPath = Options.ResourceMetadataUri?.ToString() ?? string.Empty;\n if (Options.ResourceMetadataUri != null && !Options.ResourceMetadataUri.IsAbsoluteUri)\n {\n // For relative URIs, it's just the path component.\n expectedMetadataPath = Options.ResourceMetadataUri.OriginalString;\n }\n\n // If the path doesn't match, let the request continue through the pipeline\n if (!string.Equals(requestPath, expectedMetadataPath, StringComparison.OrdinalIgnoreCase))\n {\n return false;\n }\n\n return await HandleResourceMetadataRequestAsync();\n }\n\n /// \n /// Gets the base URL from the current request, including scheme, host, and path base.\n /// \n private string GetBaseUrl() => $\"{Request.Scheme}://{Request.Host}{Request.PathBase}\";\n\n /// \n /// Gets the absolute URI for the resource metadata endpoint.\n /// \n private string GetAbsoluteResourceMetadataUri()\n {\n var resourceMetadataUri = Options.ResourceMetadataUri;\n\n string currentPath = resourceMetadataUri?.ToString() ?? string.Empty;\n\n if (resourceMetadataUri != null && resourceMetadataUri.IsAbsoluteUri)\n {\n return currentPath;\n }\n\n // For relative URIs, combine with the base URL\n string baseUrl = GetBaseUrl();\n string relativePath = resourceMetadataUri?.OriginalString.TrimStart('/') ?? string.Empty;\n\n if (!Uri.TryCreate($\"{baseUrl.TrimEnd('/')}/{relativePath}\", UriKind.Absolute, out var absoluteUri))\n {\n throw new InvalidOperationException($\"Could not create absolute URI for resource metadata. Base URL: {baseUrl}, Relative Path: {relativePath}\");\n }\n\n return absoluteUri.ToString();\n }\n\n private async Task HandleResourceMetadataRequestAsync()\n {\n var resourceMetadata = Options.ResourceMetadata;\n\n if (Options.Events.OnResourceMetadataRequest is not null)\n {\n var context = new ResourceMetadataRequestContext(Request.HttpContext, Scheme, Options)\n {\n ResourceMetadata = CloneResourceMetadata(resourceMetadata),\n };\n\n await Options.Events.OnResourceMetadataRequest(context);\n\n if (context.Result is not null)\n {\n if (context.Result.Handled)\n {\n return true;\n }\n else if (context.Result.Skipped)\n {\n return false;\n }\n else if (context.Result.Failure is not null)\n {\n throw new AuthenticationFailureException(\"An error occurred from the OnResourceMetadataRequest event.\", context.Result.Failure);\n }\n }\n\n resourceMetadata = context.ResourceMetadata;\n }\n\n if (resourceMetadata == null)\n {\n throw new InvalidOperationException(\n \"ResourceMetadata has not been configured. Please set McpAuthenticationOptions.ResourceMetadata or ensure context.ResourceMetadata is set inside McpAuthenticationOptions.Events.OnResourceMetadataRequest.\"\n );\n }\n\n await Results.Json(resourceMetadata, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ProtectedResourceMetadata))).ExecuteAsync(Context);\n return true;\n }\n\n /// \n // If no forwarding is configured, this handler doesn't perform authentication\n protected override async Task HandleAuthenticateAsync() => AuthenticateResult.NoResult();\n\n /// \n protected override Task HandleChallengeAsync(AuthenticationProperties properties)\n {\n // Get the absolute URI for the resource metadata\n string rawPrmDocumentUri = GetAbsoluteResourceMetadataUri();\n\n properties ??= new AuthenticationProperties();\n\n // Store the resource_metadata in properties in case other handlers need it\n properties.Items[\"resource_metadata\"] = rawPrmDocumentUri;\n\n // Add the WWW-Authenticate header with Bearer scheme and resource metadata\n string headerValue = $\"Bearer realm=\\\"{Scheme.Name}\\\", resource_metadata=\\\"{rawPrmDocumentUri}\\\"\";\n Response.Headers.Append(\"WWW-Authenticate\", headerValue);\n\n return base.HandleChallengeAsync(properties);\n }\n\n internal static ProtectedResourceMetadata? CloneResourceMetadata(ProtectedResourceMetadata? resourceMetadata)\n {\n if (resourceMetadata is null)\n {\n return null;\n }\n\n return new ProtectedResourceMetadata\n {\n Resource = resourceMetadata.Resource,\n AuthorizationServers = [.. resourceMetadata.AuthorizationServers],\n BearerMethodsSupported = [.. resourceMetadata.BearerMethodsSupported],\n ScopesSupported = [.. resourceMetadata.ScopesSupported],\n JwksUri = resourceMetadata.JwksUri,\n ResourceSigningAlgValuesSupported = resourceMetadata.ResourceSigningAlgValuesSupported is not null ? [.. resourceMetadata.ResourceSigningAlgValuesSupported] : null,\n ResourceName = resourceMetadata.ResourceName,\n ResourceDocumentation = resourceMetadata.ResourceDocumentation,\n ResourcePolicyUri = resourceMetadata.ResourcePolicyUri,\n ResourceTosUri = resourceMetadata.ResourceTosUri,\n TlsClientCertificateBoundAccessTokens = resourceMetadata.TlsClientCertificateBoundAccessTokens,\n AuthorizationDetailsTypesSupported = resourceMetadata.AuthorizationDetailsTypesSupported is not null ? [.. resourceMetadata.AuthorizationDetailsTypesSupported] : null,\n DpopSigningAlgValuesSupported = resourceMetadata.DpopSigningAlgValuesSupported is not null ? [.. resourceMetadata.DpopSigningAlgValuesSupported] : null,\n DpopBoundAccessTokensRequired = resourceMetadata.DpopBoundAccessTokensRequired\n };\n }\n\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class contains extension methods that simplify common operations with an MCP client,\n/// such as pinging a server, listing and working with tools, prompts, and resources, and\n/// managing subscriptions to resources.\n/// \n/// \npublic static class McpClientExtensions\n{\n /// \n /// Sends a ping request to verify server connectivity.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A task that completes when the ping is successful.\n /// \n /// \n /// This method is used to check if the MCP server is online and responding to requests.\n /// It can be useful for health checking, ensuring the connection is established, or verifying \n /// that the client has proper authorization to communicate with the server.\n /// \n /// \n /// The ping operation is lightweight and does not require any parameters. A successful completion\n /// of the task indicates that the server is operational and accessible.\n /// \n /// \n /// is .\n /// Thrown when the server cannot be reached or returns an error response.\n public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.Ping,\n parameters: null,\n McpJsonUtilities.JsonContext.Default.Object!,\n McpJsonUtilities.JsonContext.Default.Object,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Retrieves a list of available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available tools as instances.\n /// \n /// \n /// This method fetches all available tools from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of tools and that responds with paginated responses, consider using \n /// instead, as it streams tools as they arrive rather than loading them all at once.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// \n /// \n /// // Get all tools available on the server\n /// var tools = await mcpClient.ListToolsAsync();\n /// \n /// // Use tools with an AI client\n /// ChatOptions chatOptions = new()\n /// {\n /// Tools = [.. tools]\n /// };\n /// \n /// await foreach (var update in chatClient.GetStreamingResponseAsync(userMessage, chatOptions))\n /// {\n /// Console.Write(update);\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n List? tools = null;\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n tools ??= new List(toolResults.Tools.Count);\n foreach (var tool in toolResults.Tools)\n {\n tools.Add(new McpClientTool(client, tool, serializerOptions));\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n\n return tools;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available tools as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve tools from the server, which allows processing tools\n /// as they arrive rather than waiting for all tools to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with tools split across multiple responses.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available tools.\n /// \n /// \n /// \n /// \n /// // Enumerate all tools available on the server\n /// await foreach (var tool in client.EnumerateToolsAsync())\n /// {\n /// Console.WriteLine($\"Tool: {tool.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var tool in toolResults.Tools)\n {\n yield return new McpClientTool(client, tool, serializerOptions);\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available prompts as instances.\n /// \n /// \n /// This method fetches all available prompts from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of prompts and that responds with paginated responses, consider using \n /// instead, as it streams prompts as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListPromptsAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? prompts = null;\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n prompts ??= new List(promptResults.Prompts.Count);\n foreach (var prompt in promptResults.Prompts)\n {\n prompts.Add(new McpClientPrompt(client, prompt));\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n\n return prompts;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available prompts as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve prompts from the server, which allows processing prompts\n /// as they arrive rather than waiting for all prompts to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with prompts split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available prompts.\n /// \n /// \n /// \n /// \n /// // Enumerate all prompts available on the server\n /// await foreach (var prompt in client.EnumeratePromptsAsync())\n /// {\n /// Console.WriteLine($\"Prompt: {prompt.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumeratePromptsAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var prompt in promptResults.Prompts)\n {\n yield return new(client, prompt);\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a specific prompt from the MCP server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the prompt to retrieve.\n /// Optional arguments for the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to create the specified prompt with the provided arguments.\n /// The server will process the arguments and return a prompt containing messages or other content.\n /// \n /// \n /// Arguments are serialized into JSON and passed to the server, where they may be used to customize the \n /// prompt's behavior or content. Each prompt may have different argument requirements.\n /// \n /// \n /// The returned contains a collection of objects,\n /// which can be converted to objects using the method.\n /// \n /// \n /// Thrown when the prompt does not exist, when required arguments are missing, or when the server encounters an error processing the prompt.\n /// is .\n public static ValueTask GetPromptAsync(\n this IMcpClient client,\n string name,\n IReadOnlyDictionary? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(name);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n return client.SendRequestAsync(\n RequestMethods.PromptsGet,\n new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },\n McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,\n McpJsonUtilities.JsonContext.Default.GetPromptResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Retrieves a list of available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resource templates as instances.\n /// \n /// \n /// This method fetches all available resource templates from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resource templates and that responds with paginated responses, consider using \n /// instead, as it streams templates as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListResourceTemplatesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resourceTemplates = null;\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resourceTemplates ??= new List(templateResults.ResourceTemplates.Count);\n foreach (var template in templateResults.ResourceTemplates)\n {\n resourceTemplates.Add(new McpClientResourceTemplate(client, template));\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n\n return resourceTemplates;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resource templates as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resource templates from the server, which allows processing templates\n /// as they arrive rather than waiting for all templates to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with templates split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resource templates.\n /// \n /// \n /// \n /// \n /// // Enumerate all resource templates available on the server\n /// await foreach (var template in client.EnumerateResourceTemplatesAsync())\n /// {\n /// Console.WriteLine($\"Template: {template.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourceTemplatesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var templateResult in templateResults.ResourceTemplates)\n {\n yield return new McpClientResourceTemplate(client, templateResult);\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resources as instances.\n /// \n /// \n /// This method fetches all available resources from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resources and that responds with paginated responses, consider using \n /// instead, as it streams resources as they arrive rather than loading them all at once.\n /// \n /// \n /// \n /// \n /// // Get all resources available on the server\n /// var resources = await client.ListResourcesAsync();\n /// \n /// // Display information about each resource\n /// foreach (var resource in resources)\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListResourcesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resources = null;\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resources ??= new List(resourceResults.Resources.Count);\n foreach (var resource in resourceResults.Resources)\n {\n resources.Add(new McpClientResource(client, resource));\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n\n return resources;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resources as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resources from the server, which allows processing resources\n /// as they arrive rather than waiting for all resources to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with resources split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resources.\n /// \n /// \n /// \n /// \n /// // Enumerate all resources available on the server\n /// await foreach (var resource in client.EnumerateResourcesAsync())\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourcesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var resource in resourceResults.Resources)\n {\n yield return new McpClientResource(client, resource);\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return ReadResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri template of the resource.\n /// Arguments to use to format .\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uriTemplate, IReadOnlyDictionary arguments, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uriTemplate);\n Throw.IfNull(arguments);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = UriTemplate.FormatUri(uriTemplate, arguments) },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests completion suggestions for a prompt argument or resource reference.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The reference object specifying the type and optional URI or name.\n /// The name of the argument for which completions are requested.\n /// The current value of the argument, used to filter relevant completions.\n /// The to monitor for cancellation requests. The default is .\n /// A containing completion suggestions.\n /// \n /// \n /// This method allows clients to request auto-completion suggestions for arguments in a prompt template\n /// or for resource references.\n /// \n /// \n /// When working with prompt references, the server will return suggestions for the specified argument\n /// that match or begin with the current argument value. This is useful for implementing intelligent\n /// auto-completion in user interfaces.\n /// \n /// \n /// When working with resource references, the server will return suggestions relevant to the specified \n /// resource URI.\n /// \n /// \n /// is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n /// The server returned an error response.\n public static ValueTask CompleteAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(reference);\n Throw.IfNullOrWhiteSpace(argumentName);\n\n return client.SendRequestAsync(\n RequestMethods.CompletionComplete,\n new()\n {\n Ref = reference,\n Argument = new Argument { Name = argumentName, Value = argumentValue }\n },\n McpJsonUtilities.JsonContext.Default.CompleteRequestParams,\n McpJsonUtilities.JsonContext.Default.CompleteResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesSubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n public static Task SubscribeToResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return SubscribeToResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesUnsubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return UnsubscribeFromResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Invokes a tool on the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the tool to call on the server..\n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// is .\n /// is .\n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// // Call a simple echo tool with a string argument\n /// var result = await client.CallToolAsync(\n /// \"echo\",\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public static ValueTask CallToolAsync(\n this IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(toolName);\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n if (progress is not null)\n {\n return SendRequestWithProgressAsync(client, toolName, arguments, progress, serializerOptions, cancellationToken);\n }\n\n return client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken);\n\n static async ValueTask SendRequestWithProgressAsync(\n IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments,\n IProgress progress,\n JsonSerializerOptions serializerOptions,\n CancellationToken cancellationToken)\n {\n ProgressToken progressToken = new(Guid.NewGuid().ToString(\"N\"));\n\n await using var _ = client.RegisterNotificationHandler(NotificationMethods.ProgressNotification,\n (notification, cancellationToken) =>\n {\n if (JsonSerializer.Deserialize(notification.Params, McpJsonUtilities.JsonContext.Default.ProgressNotificationParams) is { } pn &&\n pn.ProgressToken == progressToken)\n {\n progress.Report(pn.Progress);\n }\n\n return default;\n }).ConfigureAwait(false);\n\n return await client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n ProgressToken = progressToken,\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n }\n\n /// \n /// Converts the contents of a into a pair of\n /// and instances to use\n /// as inputs into a operation.\n /// \n /// \n /// The created pair of messages and options.\n /// is .\n internal static (IList Messages, ChatOptions? Options) ToChatClientArguments(\n this CreateMessageRequestParams requestParams)\n {\n Throw.IfNull(requestParams);\n\n ChatOptions? options = null;\n\n if (requestParams.MaxTokens is int maxTokens)\n {\n (options ??= new()).MaxOutputTokens = maxTokens;\n }\n\n if (requestParams.Temperature is float temperature)\n {\n (options ??= new()).Temperature = temperature;\n }\n\n if (requestParams.StopSequences is { } stopSequences)\n {\n (options ??= new()).StopSequences = stopSequences.ToArray();\n }\n\n List messages =\n (from sm in requestParams.Messages\n let aiContent = sm.Content.ToAIContent()\n where aiContent is not null\n select new ChatMessage(sm.Role == Role.Assistant ? ChatRole.Assistant : ChatRole.User, [aiContent]))\n .ToList();\n\n return (messages, options);\n }\n\n /// Converts the contents of a into a .\n /// The whose contents should be extracted.\n /// The created .\n /// is .\n internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chatResponse)\n {\n Throw.IfNull(chatResponse);\n\n // The ChatResponse can include multiple messages, of varying modalities, but CreateMessageResult supports\n // only either a single blob of text or a single image. Heuristically, we'll use an image if there is one\n // in any of the response messages, or we'll use all the text from them concatenated, otherwise.\n\n ChatMessage? lastMessage = chatResponse.Messages.LastOrDefault();\n\n ContentBlock? content = null;\n if (lastMessage is not null)\n {\n foreach (var lmc in lastMessage.Contents)\n {\n if (lmc is DataContent dc && (dc.HasTopLevelMediaType(\"image\") || dc.HasTopLevelMediaType(\"audio\")))\n {\n content = dc.ToContent();\n }\n }\n }\n\n return new()\n {\n Content = content ?? new TextContentBlock { Text = lastMessage?.Text ?? string.Empty },\n Model = chatResponse.ModelId ?? \"unknown\",\n Role = lastMessage?.Role == ChatRole.User ? Role.User : Role.Assistant,\n StopReason = chatResponse.FinishReason == ChatFinishReason.Length ? \"maxTokens\" : \"endTurn\",\n };\n }\n\n /// \n /// Creates a sampling handler for use with that will\n /// satisfy sampling requests using the specified .\n /// \n /// The with which to satisfy sampling requests.\n /// The created handler delegate that can be assigned to .\n /// \n /// \n /// This method creates a function that converts MCP message requests into chat client calls, enabling\n /// an MCP client to generate text or other content using an actual AI model via the provided chat client.\n /// \n /// \n /// The handler can process text messages, image messages, and resource messages as defined in the\n /// Model Context Protocol.\n /// \n /// \n /// is .\n public static Func, CancellationToken, ValueTask> CreateSamplingHandler(\n this IChatClient chatClient)\n {\n Throw.IfNull(chatClient);\n\n return async (requestParams, progress, cancellationToken) =>\n {\n Throw.IfNull(requestParams);\n\n var (messages, options) = requestParams.ToChatClientArguments();\n var progressToken = requestParams.ProgressToken;\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false))\n {\n updates.Add(update);\n\n if (progressToken is not null)\n {\n progress.Report(new()\n {\n Progress = updates.Count,\n });\n }\n }\n\n return updates.ToChatResponse().ToCreateMessageResult();\n };\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// , , and \n /// level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LoggingLevel level, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.LoggingSetLevel,\n new() { Level = level },\n McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// and level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LogLevel level, CancellationToken cancellationToken = default) =>\n SetLoggingLevel(client, McpServer.ToLoggingLevel(level), cancellationToken);\n\n /// Convers a dictionary with values to a dictionary with values.\n private static Dictionary? ToArgumentsDictionary(\n IReadOnlyDictionary? arguments, JsonSerializerOptions options)\n {\n var typeInfo = options.GetTypeInfo();\n\n Dictionary? result = null;\n if (arguments is not null)\n {\n result = new(arguments.Count);\n foreach (var kvp in arguments)\n {\n result.Add(kvp.Key, kvp.Value is JsonElement je ? je : JsonSerializer.SerializeToElement(kvp.Value, typeInfo));\n }\n }\n\n return result;\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource defined on an MCP server. It allows\n/// retrieving the resource's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResource\n{\n private readonly IMcpClient _client;\n\n internal McpClientResource(IMcpClient client, Resource resource)\n {\n _client = client;\n ProtocolResource = resource;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Resource ProtocolResource { get; }\n\n /// Gets the URI of the resource.\n public string Uri => ProtocolResource.Uri;\n\n /// Gets the name of the resource.\n public string Name => ProtocolResource.Name;\n\n /// Gets the title of the resource.\n public string? Title => ProtocolResource.Title;\n\n /// Gets a description of the resource.\n public string? Description => ProtocolResource.Description;\n\n /// Gets a media (MIME) type of the resource.\n public string? MimeType => ProtocolResource.MimeType;\n\n /// \n /// Gets this resource's content by sending a request to the server.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource's result with content and messages.\n /// \n /// \n /// This is a convenience method that internally calls .\n /// \n /// \n public ValueTask ReadAsync(\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(Uri, cancellationToken);\n}"], ["/csharp-sdk/samples/AspNetCoreSseServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource, Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer server,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await server.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/AnnotatedMessageTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AnnotatedMessageTool\n{\n public enum MessageType\n {\n Error,\n Success,\n Debug,\n }\n\n [McpServerTool(Name = \"annotatedMessage\"), Description(\"Generates an annotated message\")]\n public static IEnumerable AnnotatedMessage(MessageType messageType, bool includeImage = true)\n {\n List contents = messageType switch\n {\n MessageType.Error => [new TextContentBlock\n {\n Text = \"Error: Operation failed\",\n Annotations = new() { Audience = [Role.User, Role.Assistant], Priority = 1.0f }\n }],\n MessageType.Success => [new TextContentBlock\n {\n Text = \"Operation completed successfully\",\n Annotations = new() { Audience = [Role.User], Priority = 0.7f }\n }],\n MessageType.Debug => [new TextContentBlock\n {\n Text = \"Debug: Cache hit ratio 0.95, latency 150ms\",\n Annotations = new() { Audience = [Role.Assistant], Priority = 0.3f }\n }],\n _ => throw new ArgumentOutOfRangeException(nameof(messageType), messageType, null)\n };\n\n if (includeImage)\n {\n contents.Add(new ImageContentBlock\n {\n Data = TinyImageTool.MCP_TINY_IMAGE.Split(\",\").Last(),\n MimeType = \"image/png\",\n Annotations = new() { Audience = [Role.User], Priority = 0.5f }\n });\n }\n\n return contents;\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses depenency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await thisServer.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable resource used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP resource for use in the server (as opposed\n/// to or , which provide the protocol representations of a resource). Instances of \n/// can be added into a to be picked up automatically when\n/// is used to create an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithResourcesFromAssembly and\n/// . The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the URI received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// is used to represent both direct resources (e.g. \"resource://example\") and templated\n/// resources (e.g. \"resource://example/{id}\").\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerResource : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerResource()\n {\n }\n\n /// Gets whether this resource is a URI template with parameters as opposed to a direct resource.\n public bool IsTemplated => ProtocolResourceTemplate.UriTemplate.Contains('{');\n\n /// Gets the protocol type for this instance.\n /// \n /// \n /// The property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n /// \n /// Every valid resource URI is a valid resource URI template, and thus this property always returns an instance.\n /// In contrast, the property may return if the resource template\n /// contains a parameter, in which case the resource template URI is not a valid resource URI.\n /// \n /// \n public abstract ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolResourceTemplate property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n public virtual Resource? ProtocolResource => ProtocolResourceTemplate.AsResource();\n\n /// \n /// Gets the resource, rendering it with the provided request parameters and returning the resource result.\n /// \n /// \n /// The request context containing information about the resource invocation, including any arguments\n /// passed to the resource. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the resource content and messages. If and only if this doesn't match the ,\n /// the method returns .\n /// \n /// is .\n /// The resource implementation returned or an unsupported result type.\n public abstract ValueTask ReadAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerResource Create(\n MethodInfo method, \n object? target = null,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerResource Create(\n AIFunction function,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(function, options);\n\n /// \n public override string ToString() => ProtocolResourceTemplate.UriTemplate;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolResourceTemplate.UriTemplate;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed partial class AIFunctionMcpServerTool : McpServerTool\n{\n private readonly ILogger _logger;\n private readonly bool _structuredOutputRequiresWrapping;\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n \n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n object? target,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerToolCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options)\n {\n Throw.IfNull(function);\n\n Tool tool = new()\n {\n Name = options?.Name ?? function.Name,\n Description = options?.Description ?? function.Description,\n InputSchema = function.JsonSchema,\n OutputSchema = CreateOutputSchema(function, options, out bool structuredOutputRequiresWrapping),\n };\n\n if (options is not null)\n {\n if (options.Title is not null ||\n options.Idempotent is not null ||\n options.Destructive is not null ||\n options.OpenWorld is not null ||\n options.ReadOnly is not null)\n {\n tool.Title = options.Title;\n\n tool.Annotations = new()\n {\n Title = options.Title,\n IdempotentHint = options.Idempotent,\n DestructiveHint = options.Destructive,\n OpenWorldHint = options.OpenWorld,\n ReadOnlyHint = options.ReadOnly,\n };\n }\n }\n\n return new AIFunctionMcpServerTool(function, tool, options?.Services, structuredOutputRequiresWrapping);\n }\n\n private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpServerToolCreateOptions? options)\n {\n McpServerToolCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } toolAttr)\n {\n newOptions.Name ??= toolAttr.Name;\n newOptions.Title ??= toolAttr.Title;\n\n if (toolAttr._destructive is bool destructive)\n {\n newOptions.Destructive ??= destructive;\n }\n\n if (toolAttr._idempotent is bool idempotent)\n {\n newOptions.Idempotent ??= idempotent;\n }\n\n if (toolAttr._openWorld is bool openWorld)\n {\n newOptions.OpenWorld ??= openWorld;\n }\n\n if (toolAttr._readOnly is bool readOnly)\n {\n newOptions.ReadOnly ??= readOnly;\n }\n\n newOptions.UseStructuredContent = toolAttr.UseStructuredContent;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this tool.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerTool(AIFunction function, Tool tool, IServiceProvider? serviceProvider, bool structuredOutputRequiresWrapping)\n {\n AIFunction = function;\n ProtocolTool = tool;\n _logger = serviceProvider?.GetService()?.CreateLogger() ?? (ILogger)NullLogger.Instance;\n _structuredOutputRequiresWrapping = structuredOutputRequiresWrapping;\n }\n\n /// \n public override Tool ProtocolTool { get; }\n\n /// \n public override async ValueTask InvokeAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result;\n try\n {\n result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e) when (e is not OperationCanceledException)\n {\n ToolCallError(request.Params?.Name ?? string.Empty, e);\n\n string errorMessage = e is McpException ?\n $\"An error occurred invoking '{request.Params?.Name}': {e.Message}\" :\n $\"An error occurred invoking '{request.Params?.Name}'.\";\n\n return new()\n {\n IsError = true,\n Content = [new TextContentBlock { Text = errorMessage }],\n };\n }\n\n JsonNode? structuredContent = CreateStructuredResponse(result);\n return result switch\n {\n AIContent aiContent => new()\n {\n Content = [aiContent.ToContent()],\n StructuredContent = structuredContent,\n IsError = aiContent is ErrorContent\n },\n\n null => new()\n {\n Content = [],\n StructuredContent = structuredContent,\n },\n \n string text => new()\n {\n Content = [new TextContentBlock { Text = text }],\n StructuredContent = structuredContent,\n },\n \n ContentBlock content => new()\n {\n Content = [content],\n StructuredContent = structuredContent,\n },\n \n IEnumerable texts => new()\n {\n Content = [.. texts.Select(x => new TextContentBlock { Text = x ?? string.Empty })],\n StructuredContent = structuredContent,\n },\n \n IEnumerable contentItems => ConvertAIContentEnumerableToCallToolResult(contentItems, structuredContent),\n \n IEnumerable contents => new()\n {\n Content = [.. contents],\n StructuredContent = structuredContent,\n },\n \n CallToolResult callToolResponse => callToolResponse,\n\n _ => new()\n {\n Content = [new TextContentBlock { Text = JsonSerializer.Serialize(result, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))) }],\n StructuredContent = structuredContent,\n },\n };\n }\n\n /// Creates a name to use based on the supplied method and naming policy.\n internal static string DeriveName(MethodInfo method, JsonNamingPolicy? policy = null)\n {\n string name = method.Name;\n\n // Remove any \"Async\" suffix if the method is an async method and if the method name isn't just \"Async\".\n const string AsyncSuffix = \"Async\";\n if (IsAsyncMethod(method) &&\n name.EndsWith(AsyncSuffix, StringComparison.Ordinal) &&\n name.Length > AsyncSuffix.Length)\n {\n name = name.Substring(0, name.Length - AsyncSuffix.Length);\n }\n\n // Replace anything other than ASCII letters or digits with underscores, trim off any leading or trailing underscores.\n name = NonAsciiLetterDigitsRegex().Replace(name, \"_\").Trim('_');\n\n // If after all our transformations the name is empty, just use the original method name.\n if (name.Length == 0)\n {\n name = method.Name;\n }\n\n // Case the name based on the provided naming policy.\n return (policy ?? JsonNamingPolicy.SnakeCaseLower).ConvertName(name) ?? name;\n\n static bool IsAsyncMethod(MethodInfo method)\n {\n Type t = method.ReturnType;\n\n if (t == typeof(Task) || t == typeof(ValueTask))\n {\n return true;\n }\n\n if (t.IsGenericType)\n {\n t = t.GetGenericTypeDefinition();\n if (t == typeof(Task<>) || t == typeof(ValueTask<>) || t == typeof(IAsyncEnumerable<>))\n {\n return true;\n }\n }\n\n return false;\n }\n }\n\n /// Regex that flags runs of characters other than ASCII digits or letters.\n#if NET\n [GeneratedRegex(\"[^0-9A-Za-z]+\")]\n private static partial Regex NonAsciiLetterDigitsRegex();\n#else\n private static Regex NonAsciiLetterDigitsRegex() => _nonAsciiLetterDigits;\n private static readonly Regex _nonAsciiLetterDigits = new(\"[^0-9A-Za-z]+\", RegexOptions.Compiled);\n#endif\n\n private static JsonElement? CreateOutputSchema(AIFunction function, McpServerToolCreateOptions? toolCreateOptions, out bool structuredOutputRequiresWrapping)\n {\n structuredOutputRequiresWrapping = false;\n\n if (toolCreateOptions?.UseStructuredContent is not true)\n {\n return null;\n }\n\n if (function.ReturnJsonSchema is not JsonElement outputSchema)\n {\n return null;\n }\n\n if (outputSchema.ValueKind is not JsonValueKind.Object ||\n !outputSchema.TryGetProperty(\"type\", out JsonElement typeProperty) ||\n typeProperty.ValueKind is not JsonValueKind.String ||\n typeProperty.GetString() is not \"object\")\n {\n // If the output schema is not an object, need to modify to be a valid MCP output schema.\n JsonNode? schemaNode = JsonSerializer.SerializeToNode(outputSchema, McpJsonUtilities.JsonContext.Default.JsonElement);\n\n if (schemaNode is JsonObject objSchema &&\n objSchema.TryGetPropertyValue(\"type\", out JsonNode? typeNode) &&\n typeNode is JsonArray { Count: 2 } typeArray && typeArray.Any(type => (string?)type is \"object\") && typeArray.Any(type => (string?)type is \"null\"))\n {\n // For schemas that are of type [\"object\", \"null\"], replace with just \"object\" to be conformant.\n objSchema[\"type\"] = \"object\";\n }\n else\n {\n // For anything else, wrap the schema in an envelope with a \"result\" property.\n schemaNode = new JsonObject\n {\n [\"type\"] = \"object\",\n [\"properties\"] = new JsonObject\n {\n [\"result\"] = schemaNode\n },\n [\"required\"] = new JsonArray { (JsonNode)\"result\" }\n };\n\n structuredOutputRequiresWrapping = true;\n }\n\n outputSchema = JsonSerializer.Deserialize(schemaNode, McpJsonUtilities.JsonContext.Default.JsonElement);\n }\n\n return outputSchema;\n }\n\n private JsonNode? CreateStructuredResponse(object? aiFunctionResult)\n {\n if (ProtocolTool.OutputSchema is null)\n {\n // Only provide structured responses if the tool has an output schema defined.\n return null;\n }\n\n JsonNode? nodeResult = aiFunctionResult switch\n {\n JsonNode node => node,\n JsonElement jsonElement => JsonSerializer.SerializeToNode(jsonElement, McpJsonUtilities.JsonContext.Default.JsonElement),\n _ => JsonSerializer.SerializeToNode(aiFunctionResult, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))),\n };\n\n if (_structuredOutputRequiresWrapping)\n {\n return new JsonObject\n {\n [\"result\"] = nodeResult\n };\n }\n\n return nodeResult;\n }\n\n private static CallToolResult ConvertAIContentEnumerableToCallToolResult(IEnumerable contentItems, JsonNode? structuredContent)\n {\n List contentList = [];\n bool allErrorContent = true;\n bool hasAny = false;\n\n foreach (var item in contentItems)\n {\n contentList.Add(item.ToContent());\n hasAny = true;\n\n if (allErrorContent && item is not ErrorContent)\n {\n allErrorContent = false;\n }\n }\n\n return new()\n {\n Content = contentList,\n StructuredContent = structuredContent,\n IsError = allErrorContent && hasAny\n };\n }\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"\\\"{ToolName}\\\" threw an unhandled exception.\")]\n private partial void ToolCallError(string toolName, Exception exception);\n}"], ["/csharp-sdk/src/ModelContextProtocol/McpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring MCP servers via dependency injection.\n/// \npublic static partial class McpServerBuilderExtensions\n{\n #region WithTools\n private const string WithToolsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithTools)} and {nameof(WithToolsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithTools)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The tool type.\n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n public static IMcpServerBuilder WithTools<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TToolType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var toolMethod in typeof(TToolType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, static r => CreateTarget(r.Services, typeof(TToolType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable tools)\n {\n Throw.IfNull(builder);\n Throw.IfNull(tools);\n\n foreach (var tool in tools)\n {\n if (tool is not null)\n {\n builder.Services.AddSingleton(tool);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with -attributed methods to add as tools to the server.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable toolTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(toolTypes);\n\n foreach (var toolType in toolTypes)\n {\n if (toolType is not null)\n {\n foreach (var toolMethod in toolType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services , SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, r => CreateTarget(r.Services, toolType), new() { Services = services , SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as tools to the server.\n /// \n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the tool.\n /// \n /// \n /// Tools registered through this method can be discovered by clients using the list_tools request\n /// and invoked using the call_tool request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithToolsFromAssembly(this IMcpServerBuilder builder, Assembly? toolAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n toolAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithTools(\n from t in toolAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithPrompts\n private const string WithPromptsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithPrompts)} and {nameof(WithPromptsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithPrompts)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The prompt type.\n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n public static IMcpServerBuilder WithPrompts<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TPromptType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var promptMethod in typeof(TPromptType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, static r => CreateTarget(r.Services, typeof(TPromptType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable prompts)\n {\n Throw.IfNull(builder);\n Throw.IfNull(prompts);\n\n foreach (var prompt in prompts)\n {\n if (prompt is not null)\n {\n builder.Services.AddSingleton(prompt);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as prompts to the server.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable promptTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(promptTypes);\n\n foreach (var promptType in promptTypes)\n {\n if (promptType is not null)\n {\n foreach (var promptMethod in promptType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, r => CreateTarget(r.Services, promptType), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as prompts to the server.\n /// \n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the prompt.\n /// \n /// \n /// Prompts registered through this method can be discovered by clients using the list_prompts request\n /// and invoked using the call_prompt request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPromptsFromAssembly(this IMcpServerBuilder builder, Assembly? promptAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n promptAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithPrompts(\n from t in promptAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithResources\n private const string WithResourcesRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithResources)} and {nameof(WithResourcesFromAssembly)} methods require dynamic lookup of member metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithResources)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The resource type.\n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the members are attributed as , and adds an \n /// instance for each. For instance members, an instance will be constructed for each invocation of the resource.\n /// \n public static IMcpServerBuilder WithResources<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TResourceType>(\n this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n foreach (var resourceTemplateMethod in typeof(TResourceType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, static r => CreateTarget(r.Services, typeof(TResourceType)), new() { Services = services })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplates)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplates);\n\n foreach (var resourceTemplate in resourceTemplates)\n {\n if (resourceTemplate is not null)\n {\n builder.Services.AddSingleton(resourceTemplate);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as resources to the server.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the resource.\n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplateTypes)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplateTypes);\n\n foreach (var resourceTemplateType in resourceTemplateTypes)\n {\n if (resourceTemplateType is not null)\n {\n foreach (var resourceTemplateMethod in resourceTemplateType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, r => CreateTarget(r.Services, resourceTemplateType), new() { Services = services })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as resources to the server.\n /// \n /// The builder instance.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all members within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance members. For instance members, a new instance\n /// of the containing class will be constructed for each invocation of the resource.\n /// \n /// \n /// Resource templates registered through this method can be discovered by clients using the list_resourceTemplates request\n /// and invoked using the read_resource request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResourcesFromAssembly(this IMcpServerBuilder builder, Assembly? resourceAssembly = null)\n {\n Throw.IfNull(builder);\n\n resourceAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithResources(\n from t in resourceAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t);\n }\n #endregion\n\n #region Handlers\n /// \n /// Configures a handler for listing resource templates available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource template list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is responsible for providing clients with information about available resource templates\n /// that can be used to construct resource URIs.\n /// \n /// \n /// Resource templates describe the structure of resource URIs that the server can handle. They include\n /// URI templates (according to RFC 6570) that clients can use to construct valid resource URIs.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// resource system where templates define the URI patterns and the read handler provides the actual content.\n /// \n /// \n public static IMcpServerBuilder WithListResourceTemplatesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourceTemplatesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list tools requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available tools. It should return all tools\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// tool collections.\n /// \n /// \n /// When tools are also defined using collection, both sets of tools\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// tools and dynamically generated tools.\n /// \n /// \n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and \n /// executes them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListToolsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListToolsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for calling tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes tool calls.\n /// The builder provided in .\n /// is .\n /// \n /// The call tool handler is responsible for executing custom tools and returning their results to clients.\n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and this handler executes them.\n /// \n public static IMcpServerBuilder WithCallToolHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CallToolHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing prompts available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list prompts requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available prompts. It should return all prompts\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// prompt collections.\n /// \n /// \n /// When prompts are also defined using collection, both sets of prompts\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// prompts and dynamically generated prompts.\n /// \n /// \n /// This method is typically paired with to provide a complete prompts implementation,\n /// where advertises available prompts and \n /// produces them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListPromptsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListPromptsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for getting a prompt available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes prompt requests.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithGetPromptHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.GetPromptHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing resources available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where this handler advertises available resources and the read handler provides their content when requested.\n /// \n /// \n public static IMcpServerBuilder WithListResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for reading a resource available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource read requests.\n /// The builder provided in .\n /// is .\n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where the list handler advertises available resources and the read handler provides their content when requested.\n /// \n public static IMcpServerBuilder WithReadResourceHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ReadResourceHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for auto-completion suggestions for prompt arguments or resource references available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes completion requests.\n /// The builder provided in .\n /// is .\n /// \n /// The completion handler is invoked when clients request suggestions for argument values.\n /// This enables auto-complete functionality for both prompt arguments and resource references.\n /// \n public static IMcpServerBuilder WithCompleteHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CompleteHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource subscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource subscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The subscribe handler is responsible for registering client interest in specific resources. When a resource\n /// changes, the server can notify all subscribed clients about the change.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. Resource subscriptions allow clients to maintain up-to-date information without\n /// needing to poll resources constantly.\n /// \n /// \n /// After registering a subscription, it's the server's responsibility to track which client is subscribed to which\n /// resources and to send appropriate notifications through the connection when resources change.\n /// \n /// \n public static IMcpServerBuilder WithSubscribeToResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SubscribeToResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource unsubscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource unsubscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The unsubscribe handler is responsible for removing client interest in specific resources. When a client\n /// no longer needs to receive notifications about resource changes, it can send an unsubscribe request.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. The unsubscribe operation is idempotent, meaning it can be called multiple\n /// times for the same resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// After removing a subscription, the server should stop sending notifications to the client about changes\n /// to the specified resource.\n /// \n /// \n public static IMcpServerBuilder WithUnsubscribeFromResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.UnsubscribeFromResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for processing logging level change requests from clients.\n /// \n /// The server builder instance.\n /// The handler that processes requests to change the logging level.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// When a client sends a logging/setLevel request, this handler will be invoked to process\n /// the requested level change. The server typically adjusts its internal logging level threshold\n /// and may begin sending log messages at or above the specified level to the client.\n /// \n /// \n /// Regardless of whether a handler is provided, an should itself handle\n /// such notifications by updating its property to return the\n /// most recently set level.\n /// \n /// \n public static IMcpServerBuilder WithSetLoggingLevelHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SetLoggingLevelHandler = handler);\n return builder;\n }\n #endregion\n\n #region Transports\n /// \n /// Adds a server transport that uses standard input (stdin) and standard output (stdout) for communication.\n /// \n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method configures the server to communicate using the standard input and output streams,\n /// which is commonly used when the Model Context Protocol server is launched locally by a client process.\n /// \n /// \n /// When using this transport, the server runs as a single-session service that exits when the\n /// stdin stream is closed. This makes it suitable for scenarios where the server should terminate\n /// when the parent process disconnects.\n /// \n /// \n /// is .\n public static IMcpServerBuilder WithStdioServerTransport(this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(sp =>\n {\n var serverOptions = sp.GetRequiredService>();\n var loggerFactory = sp.GetService();\n return new StdioServerTransport(serverOptions.Value, loggerFactory);\n });\n\n return builder;\n }\n\n /// \n /// Adds a server transport that uses the specified input and output streams for communication.\n /// \n /// The builder instance.\n /// The input to use as standard input.\n /// The output to use as standard output.\n /// The builder provided in .\n /// is .\n /// is .\n /// is .\n public static IMcpServerBuilder WithStreamServerTransport(\n this IMcpServerBuilder builder,\n Stream inputStream,\n Stream outputStream)\n {\n Throw.IfNull(builder);\n Throw.IfNull(inputStream);\n Throw.IfNull(outputStream);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(new StreamServerTransport(inputStream, outputStream));\n\n return builder;\n }\n\n private static void AddSingleSessionServerDependencies(IServiceCollection services)\n {\n services.AddHostedService();\n services.TryAddSingleton(services =>\n {\n ITransport serverTransport = services.GetRequiredService();\n IOptions options = services.GetRequiredService>();\n ILoggerFactory? loggerFactory = services.GetService();\n return McpServerFactory.Create(serverTransport, options.Value, loggerFactory, services);\n });\n }\n #endregion\n\n #region Helpers\n /// Creates an instance of the target object.\n private static object CreateTarget(\n IServiceProvider? services,\n [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) =>\n services is not null ? ActivatorUtilities.CreateInstance(services, type) :\n Activator.CreateInstance(type)!;\n #endregion\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerPrompt : McpServerPrompt\n{\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n object? target,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerPromptCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(function);\n\n List args = [];\n HashSet? requiredProps = function.JsonSchema.TryGetProperty(\"required\", out JsonElement required)\n ? new(required.EnumerateArray().Select(p => p.GetString()!), StringComparer.Ordinal)\n : null;\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n foreach (var param in properties.EnumerateObject())\n {\n args.Add(new()\n {\n Name = param.Name,\n Description = param.Value.TryGetProperty(\"description\", out JsonElement description) ? description.GetString() : null,\n Required = requiredProps?.Contains(param.Name) ?? false,\n });\n }\n }\n\n Prompt prompt = new()\n {\n Name = options?.Name ?? function.Name,\n Title = options?.Title,\n Description = options?.Description ?? function.Description,\n Arguments = args,\n };\n\n return new AIFunctionMcpServerPrompt(function, prompt);\n }\n\n private static McpServerPromptCreateOptions DeriveOptions(MethodInfo method, McpServerPromptCreateOptions? options)\n {\n McpServerPromptCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } promptAttr)\n {\n newOptions.Name ??= promptAttr.Name;\n newOptions.Title ??= promptAttr.Title;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this prompt.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerPrompt(AIFunction function, Prompt prompt)\n {\n AIFunction = function;\n ProtocolPrompt = prompt;\n }\n\n /// \n public override Prompt ProtocolPrompt { get; }\n\n /// \n public override async ValueTask GetAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n return result switch\n {\n GetPromptResult getPromptResult => getPromptResult,\n\n string text => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [new() { Role = Role.User, Content = new TextContentBlock { Text = text } }],\n },\n\n PromptMessage promptMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [promptMessage],\n },\n\n IEnumerable promptMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. promptMessages],\n },\n\n ChatMessage chatMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessage.ToPromptMessages()],\n },\n\n IEnumerable chatMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessages.SelectMany(chatMessage => chatMessage.ToPromptMessages())],\n },\n\n null => throw new InvalidOperationException(\"Null result returned from prompt function.\"),\n\n _ => throw new InvalidOperationException($\"Unknown result type '{result.GetType()}' returned from prompt function.\"),\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/UriTemplate.cs", "#if NET\nusing System.Buffers;\n#endif\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol;\n\n/// Provides basic support for parsing and formatting URI templates.\n/// \n/// This implementation should correctly handle valid URI templates, but it has undefined output for invalid templates,\n/// e.g. it may treat portions of invalid templates as literals rather than throwing.\n/// \ninternal static partial class UriTemplate\n{\n /// Regex pattern for finding URI template expressions and parsing out the operator and varname.\n private const string UriTemplateExpressionPattern = \"\"\"\n { # opening brace\n (?[+#./;?&]?) # optional operator\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}) # varchar: letter, digit, underscore, or pct-encoded\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))* # optionally dot-separated subsequent varchars\n )\n (?: :[1-9][0-9]{0,3} )? # optional prefix modifier (1–4 digits)\n \\*? # optional explode\n (?:, # comma separator, followed by the same as above\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*\n )\n (?: :[1-9][0-9]{0,3} )?\n \\*?\n )* # zero or more additional vars\n } # closing brace\n \"\"\";\n\n /// Gets a regex for finding URI template expressions and parsing out the operator and varname.\n /// \n /// This regex is for parsing a static URI template.\n /// It is not for parsing a URI according to a template.\n /// \n#if NET\n [GeneratedRegex(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace)]\n private static partial Regex UriTemplateExpression();\n#else\n private static Regex UriTemplateExpression() => s_uriTemplateExpression;\n private static readonly Regex s_uriTemplateExpression = new(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n#endif\n\n#if NET\n /// SearchValues for characters that needn't be escaped when allowing reserved characters.\n private static readonly SearchValues s_appendWhenAllowReserved = SearchValues.Create(\n \"abcdefghijklmnopqrstuvwxyz\" + // ASCII lowercase letters\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" + // ASCII uppercase letters\n \"0123456789\" + // ASCII digits\n \"-._~\" + // unreserved characters\n \":/?#[]@!$&'()*+,;=\"); // reserved characters\n#endif\n\n /// Create a for matching a URI against a URI template.\n /// The template against which to match.\n /// A regex pattern that can be used to match the specified URI template.\n public static Regex CreateParser(string uriTemplate)\n {\n DefaultInterpolatedStringHandler pattern = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n pattern.AppendFormatted('^');\n\n int lastIndex = 0;\n for (Match m = UriTemplateExpression().Match(uriTemplate); m.Success; m = m.NextMatch())\n {\n pattern.AppendFormatted(Regex.Escape(uriTemplate[lastIndex..m.Index]));\n lastIndex = m.Index + m.Length;\n\n var captures = m.Groups[\"varname\"].Captures;\n List paramNames = new(captures.Count);\n foreach (Capture c in captures)\n {\n paramNames.Add(c.Value);\n }\n\n switch (m.Groups[\"operator\"].Value)\n {\n case \"#\": AppendExpression(ref pattern, paramNames, '#', \"[^,]+\"); break;\n case \"/\": AppendExpression(ref pattern, paramNames, '/', \"[^/?]+\"); break;\n default: AppendExpression(ref pattern, paramNames, null, \"[^/?&]+\"); break;\n \n case \"?\": AppendQueryExpression(ref pattern, paramNames, '?'); break;\n case \"&\": AppendQueryExpression(ref pattern, paramNames, '&'); break;\n }\n }\n\n pattern.AppendFormatted(Regex.Escape(uriTemplate.Substring(lastIndex)));\n pattern.AppendFormatted('$');\n\n return new Regex(\n pattern.ToStringAndClear(),\n RegexOptions.IgnoreCase | RegexOptions.CultureInvariant |\n#if NET\n RegexOptions.NonBacktracking);\n#else\n RegexOptions.Compiled, TimeSpan.FromSeconds(10));\n#endif\n\n // Appends a regex fragment to `pattern` that matches an optional query string starting\n // with the given `prefix` (? or &), and up to one occurrence of each name in\n // `paramNames`. Each parameter is made optional and captured by a named group\n // of the form “paramName=value”.\n static void AppendQueryExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char prefix)\n {\n Debug.Assert(prefix is '?' or '&');\n\n pattern.AppendFormatted(\"(?:\\\\\");\n pattern.AppendFormatted(prefix);\n\n if (paramNames.Count > 0)\n {\n AppendParameter(ref pattern, paramNames[0]);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\&?\");\n AppendParameter(ref pattern, paramNames[i]);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName)\n {\n paramName = Regex.Escape(paramName);\n pattern.AppendFormatted(\"(?:\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\"=(?<\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\">[^/?&]+))?\");\n }\n }\n\n pattern.AppendFormatted(\")?\");\n }\n\n // Chooses a regex character‐class (`valueChars`) based on the initial `prefix` to define which\n // characters make up a parameter value. Then, for each name in `paramNames`, it optionally\n // appends the escaped `prefix` (only on the first parameter, then switches to ','), and\n // adds an optional named capture group `(?valueChars)` to match and capture that value.\n static void AppendExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char? prefix, string valueChars)\n {\n Debug.Assert(prefix is '#' or '/' or null);\n\n if (paramNames.Count > 0)\n {\n if (prefix is not null)\n {\n pattern.AppendFormatted('\\\\');\n pattern.AppendFormatted(prefix);\n pattern.AppendFormatted('?');\n }\n\n AppendParameter(ref pattern, paramNames[0], valueChars);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\,?\");\n AppendParameter(ref pattern, paramNames[i], valueChars);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName, string valueChars)\n {\n pattern.AppendFormatted(\"(?<\");\n pattern.AppendFormatted(Regex.Escape(paramName));\n pattern.AppendFormatted('>');\n pattern.AppendFormatted(valueChars);\n pattern.AppendFormatted(\")?\");\n }\n }\n }\n }\n\n /// \n /// Expand a URI template using the given variable values.\n /// \n public static string FormatUri(string uriTemplate, IReadOnlyDictionary arguments)\n {\n Throw.IfNull(uriTemplate);\n\n ReadOnlySpan uriTemplateSpan = uriTemplate.AsSpan();\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n while (!uriTemplateSpan.IsEmpty)\n {\n // Find the next expression.\n int openBracePos = uriTemplateSpan.IndexOf('{');\n if (openBracePos < 0)\n {\n if (uriTemplate.Length == uriTemplateSpan.Length)\n {\n return uriTemplate;\n }\n\n builder.AppendFormatted(uriTemplateSpan);\n break;\n }\n\n // Append as a literal everything before the next expression.\n builder.AppendFormatted(uriTemplateSpan.Slice(0, openBracePos));\n uriTemplateSpan = uriTemplateSpan.Slice(openBracePos + 1);\n\n int closeBracePos = uriTemplateSpan.IndexOf('}');\n if (closeBracePos < 0)\n {\n throw new FormatException($\"Unmatched '{{' in URI template '{uriTemplate}'\");\n }\n\n ReadOnlySpan expression = uriTemplateSpan.Slice(0, closeBracePos);\n uriTemplateSpan = uriTemplateSpan.Slice(closeBracePos + 1);\n if (expression.IsEmpty)\n {\n continue;\n }\n\n // The start of the expression may be a modifier; if it is, slice it off the expression.\n char modifier = expression[0];\n (string Prefix, string Separator, bool Named, bool IncludeNameIfEmpty, bool IncludeSeparatorIfEmpty, bool AllowReserved, bool PrefixEmptyExpansions, int ExpressionSlice) modifierBehavior = modifier switch\n {\n '+' => (string.Empty, \",\", false, false, true, true, false, 1),\n '#' => (\"#\", \",\", false, false, true, true, true, 1),\n '.' => (\".\", \".\", false, false, true, false, true, 1),\n '/' => (\"/\", \"/\", false, false, true, false, false, 1),\n ';' => (\";\", \";\", true, true, false, false, false, 1),\n '?' => (\"?\", \"&\", true, true, true, false, false, 1),\n '&' => (\"&\", \"&\", true, true, true, false, false, 1),\n _ => (string.Empty, \",\", false, false, true, false, false, 0),\n };\n expression = expression.Slice(modifierBehavior.ExpressionSlice);\n\n List expansions = [];\n\n // Process each varspec in the comma-delimited list in the expression (if it doesn't have any\n // commas, it will be the whole expression).\n while (!expression.IsEmpty)\n {\n // Find the next name.\n int commaPos = expression.IndexOf(',');\n ReadOnlySpan name;\n if (commaPos < 0)\n {\n name = expression;\n expression = ReadOnlySpan.Empty;\n }\n else\n {\n name = expression.Slice(0, commaPos);\n expression = expression.Slice(commaPos + 1);\n }\n\n bool explode = false;\n int prefixLength = -1;\n\n // If the name ends with a *, it means we should explode the value into separate\n // name=value pairs. If it has a colon, it means we should only take the first N characters\n // of the value. If it has both, the * takes precedence and we ignore the colon.\n if (!name.IsEmpty && name[name.Length - 1] == '*')\n {\n explode = true;\n name = name.Slice(0, name.Length - 1);\n }\n else if (name.IndexOf(':') >= 0)\n {\n int colonPos = name.IndexOf(':');\n if (colonPos < 0)\n {\n throw new FormatException($\"Invalid varspec '{name.ToString()}'\");\n }\n\n if (!int.TryParse(name.Slice(colonPos + 1)\n#if !NET\n .ToString()\n#endif\n , out prefixLength))\n {\n throw new FormatException($\"Invalid prefix length in varspec '{name.ToString()}'\");\n }\n\n name = name.Slice(0, colonPos);\n }\n\n // Look up the value for this name. If it doesn't exist, skip it.\n string nameString = name.ToString();\n if (!arguments.TryGetValue(nameString, out var value) || value is null)\n {\n continue;\n }\n\n if (value is IEnumerable list)\n {\n var items = list.Select(i => Encode(i, modifierBehavior.AllowReserved));\n if (explode)\n {\n if (modifierBehavior.Named)\n {\n foreach (var item in items)\n {\n expansions.Add($\"{nameString}={item}\");\n }\n }\n else\n {\n foreach (var item in items)\n {\n expansions.Add(item);\n }\n }\n }\n else\n {\n var joined = string.Join(\",\", items);\n expansions.Add(joined.Length > 0 && modifierBehavior.Named ?\n $\"{nameString}={joined}\" :\n joined);\n }\n }\n else if (value is IReadOnlyDictionary assoc)\n {\n var pairs = assoc.Select(kvp => (\n Encode(kvp.Key, modifierBehavior.AllowReserved),\n Encode(kvp.Value, modifierBehavior.AllowReserved)\n ));\n\n if (explode)\n {\n foreach (var (k, v) in pairs)\n {\n expansions.Add($\"{k}={v}\");\n }\n }\n else\n {\n var joined = string.Join(\",\", pairs.Select(p => $\"{p.Item1},{p.Item2}\"));\n if (joined.Length > 0)\n {\n expansions.Add(modifierBehavior.Named ? $\"{nameString}={joined}\" : joined);\n }\n }\n }\n else\n {\n string s =\n value as string ??\n (value is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) : value.ToString()) ??\n string.Empty;\n\n s = Encode((uint)prefixLength < s.Length ? s.Substring(0, prefixLength) : s, modifierBehavior.AllowReserved);\n if (!modifierBehavior.Named)\n {\n expansions.Add(s);\n }\n else if (s.Length != 0 || modifierBehavior.IncludeNameIfEmpty)\n {\n expansions.Add(\n s.Length != 0 ? $\"{nameString}={s}\" :\n modifierBehavior.IncludeSeparatorIfEmpty ? $\"{nameString}=\" :\n nameString);\n }\n }\n }\n\n if (expansions.Count > 0 && \n (modifierBehavior.PrefixEmptyExpansions || !expansions.All(string.IsNullOrEmpty)))\n {\n builder.AppendLiteral(modifierBehavior.Prefix);\n AppendJoin(ref builder, modifierBehavior.Separator, expansions);\n }\n }\n\n return builder.ToStringAndClear();\n }\n\n private static void AppendJoin(ref DefaultInterpolatedStringHandler builder, string separator, IList values)\n {\n int count = values.Count;\n if (count > 0)\n {\n builder.AppendLiteral(values[0]);\n for (int i = 1; i < count; i++)\n {\n builder.AppendLiteral(separator);\n builder.AppendLiteral(values[i]);\n }\n }\n }\n\n private static string Encode(string value, bool allowReserved)\n {\n if (!allowReserved)\n {\n return Uri.EscapeDataString(value);\n }\n\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n int i = 0;\n#if NET\n i = value.AsSpan().IndexOfAnyExcept(s_appendWhenAllowReserved);\n if (i < 0)\n {\n return value;\n }\n\n builder.AppendFormatted(value.AsSpan(0, i));\n#endif\n\n for (; i < value.Length; ++i)\n {\n char c = value[i];\n if (((uint)((c | 0x20) - 'a') <= 'z' - 'a') ||\n ((uint)(c - '0') <= '9' - '0') ||\n \"-._~:/?#[]@!$&'()*+,;=\".Contains(c))\n {\n builder.AppendFormatted(c);\n }\n else if (c == '%' && i < value.Length - 2 && Uri.IsHexDigit(value[i + 1]) && Uri.IsHexDigit(value[i + 2]))\n {\n builder.AppendFormatted(value.AsSpan(i, 3));\n i += 2;\n }\n else\n {\n AppendHex(ref builder, c);\n }\n }\n\n return builder.ToStringAndClear();\n\n static void AppendHex(ref DefaultInterpolatedStringHandler builder, char c)\n {\n ReadOnlySpan hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];\n\n if (c <= 0x7F)\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[c >> 4]);\n builder.AppendFormatted(hexDigits[c & 0xF]);\n }\n else\n {\n#if NET\n Span utf8 = stackalloc byte[Encoding.UTF8.GetMaxByteCount(1)];\n foreach (byte b in utf8.Slice(0, new Rune(c).EncodeToUtf8(utf8)))\n#else\n foreach (byte b in Encoding.UTF8.GetBytes([c]))\n#endif\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[b >> 4]);\n builder.AppendFormatted(hexDigits[b & 0xF]);\n }\n }\n }\n }\n\n /// \n /// Defines an equality comparer for Uri templates as follows:\n /// 1. Non-templated Uris use regular System.Uri equality comparison (host name is case insensitive).\n /// 2. Templated Uris use regular string equality.\n /// \n /// We do this because non-templated resources are looked up directly from the resource dictionary\n /// and we need to make sure equality is implemented correctly. Templated Uris are resolved in a\n /// fallback step using linear traversal of the resource dictionary, so their equality is only\n /// there to distinguish between different templates.\n /// \n public sealed class UriTemplateComparer : IEqualityComparer\n {\n public static IEqualityComparer Instance { get; } = new UriTemplateComparer();\n\n public bool Equals(string? uriTemplate1, string? uriTemplate2)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate1, out Uri? uri1) &&\n TryParseAsNonTemplatedUri(uriTemplate2, out Uri? uri2))\n {\n return uri1 == uri2;\n }\n\n return string.Equals(uriTemplate1, uriTemplate2, StringComparison.Ordinal);\n }\n\n public int GetHashCode([DisallowNull] string uriTemplate)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate, out Uri? uri))\n {\n return uri.GetHashCode();\n }\n else\n {\n return StringComparer.Ordinal.GetHashCode(uriTemplate);\n }\n }\n\n private static bool TryParseAsNonTemplatedUri(string? uriTemplate, [NotNullWhen(true)] out Uri? uri)\n {\n if (uriTemplate is null || uriTemplate.Contains('{'))\n {\n uri = null;\n return false;\n }\n\n return Uri.TryCreate(uriTemplate, UriKind.Absolute, out uri);\n }\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 posts.\n internal static UserIdClaim? GetUserIdClaim(ClaimsPrincipal user)\n {\n if (user?.Identity?.IsAuthenticated != true)\n {\n return null;\n }\n\n var claim = user.FindFirst(ClaimTypes.NameIdentifier) ?? user.FindFirst(\"sub\") ?? user.FindFirst(ClaimTypes.Upn);\n\n if (claim is { } idClaim)\n {\n return new(idClaim.Type, idClaim.Value, idClaim.Issuer);\n }\n\n return null;\n }\n\n private static JsonTypeInfo GetRequiredJsonTypeInfo() => (JsonTypeInfo)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));\n\n private static bool MatchesApplicationJsonMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"application/json\");\n\n private static bool MatchesTextEventStreamMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"text/event-stream\");\n\n private sealed class HttpDuplexPipe(HttpContext context) : IDuplexPipe\n {\n public PipeReader Input => context.Request.BodyReader;\n public PipeWriter Output => context.Response.BodyWriter;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of resources created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating resources programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerResourceCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the URI template of the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the from the attribute will be used. If that's not present,\n /// a URI template will be inferred from the member's signature.\n /// \n public string? UriTemplate { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the name from the attribute will be used. If that's not present, a name based on the members's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the member,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the MIME (media) type of the .\n /// \n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerResourceCreateOptions Clone() =>\n new McpServerResourceCreateOptions\n {\n Services = Services,\n UriTemplate = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\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/Server/McpServerResourceAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method or property should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods or properties that should be exposed as resources in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods or properties become available as resources that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerResourceAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerResourceAttribute()\n {\n }\n\n /// Gets or sets the URI template of the resource.\n /// \n /// If , a URI will be derived from and the method's parameter names.\n /// This template may, but doesn't have to, include parameters; if it does, this \n /// will be considered a \"resource template\", and if it doesn't, it will be considered a \"direct resource\".\n /// The former will be listed with requests and the latter\n /// with requests.\n /// \n public string? UriTemplate { get; set; }\n\n /// Gets or sets the name of the resource.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the resource.\n public string? Title { get; set; }\n\n /// Gets or sets the MIME (media) type of the resource.\n public string? MimeType { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides extension methods for interacting with an instance.\n/// \npublic static class McpServerExtensions\n{\n /// \n /// Requests to sample an LLM via the client using the specified request parameters.\n /// \n /// The server instance initiating the request.\n /// The parameters for the sampling request.\n /// The to monitor for cancellation requests.\n /// A task containing the sampling result from the client.\n /// is .\n /// The client does not support sampling.\n /// \n /// This method requires the client to support sampling capabilities.\n /// It allows detailed control over sampling parameters including messages, system prompt, temperature, \n /// and token limits.\n /// \n public static ValueTask SampleAsync(\n this IMcpServer server, CreateMessageRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.SamplingCreateMessage,\n request,\n McpJsonUtilities.JsonContext.Default.CreateMessageRequestParams,\n McpJsonUtilities.JsonContext.Default.CreateMessageResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests to sample an LLM via the client using the provided chat messages and options.\n /// \n /// The server initiating the request.\n /// The messages to send as part of the request.\n /// The options to use for the request, including model parameters and constraints.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the chat response from the model.\n /// is .\n /// is .\n /// The client does not support sampling.\n /// \n /// This method converts the provided chat messages into a format suitable for the sampling API,\n /// handling different content types such as text, images, and audio.\n /// \n public static async Task SampleAsync(\n this IMcpServer server,\n IEnumerable messages, ChatOptions? options = default, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n Throw.IfNull(messages);\n\n StringBuilder? systemPrompt = null;\n\n if (options?.Instructions is { } instructions)\n {\n (systemPrompt ??= new()).Append(instructions);\n }\n\n List samplingMessages = [];\n foreach (var message in messages)\n {\n if (message.Role == ChatRole.System)\n {\n if (systemPrompt is null)\n {\n systemPrompt = new();\n }\n else\n {\n systemPrompt.AppendLine();\n }\n\n systemPrompt.Append(message.Text);\n continue;\n }\n\n if (message.Role == ChatRole.User || message.Role == ChatRole.Assistant)\n {\n Role role = message.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n foreach (var content in message.Contents)\n {\n switch (content)\n {\n case TextContent textContent:\n samplingMessages.Add(new()\n {\n Role = role,\n Content = new TextContentBlock { Text = textContent.Text },\n });\n break;\n\n case DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") || dataContent.HasTopLevelMediaType(\"audio\"):\n samplingMessages.Add(new()\n {\n Role = role,\n Content = dataContent.HasTopLevelMediaType(\"image\") ?\n new ImageContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n } :\n new AudioContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n },\n });\n break;\n }\n }\n }\n }\n\n ModelPreferences? modelPreferences = null;\n if (options?.ModelId is { } modelId)\n {\n modelPreferences = new() { Hints = [new() { Name = modelId }] };\n }\n\n var result = await server.SampleAsync(new()\n {\n Messages = samplingMessages,\n MaxTokens = options?.MaxOutputTokens,\n StopSequences = options?.StopSequences?.ToArray(),\n SystemPrompt = systemPrompt?.ToString(),\n Temperature = options?.Temperature,\n ModelPreferences = modelPreferences,\n }, cancellationToken).ConfigureAwait(false);\n\n AIContent? responseContent = result.Content.ToAIContent();\n\n return new(new ChatMessage(result.Role is Role.User ? ChatRole.User : ChatRole.Assistant, responseContent is not null ? [responseContent] : []))\n {\n ModelId = result.Model,\n FinishReason = result.StopReason switch\n {\n \"maxTokens\" => ChatFinishReason.Length,\n \"endTurn\" or \"stopSequence\" or _ => ChatFinishReason.Stop,\n }\n };\n }\n\n /// \n /// Creates an wrapper that can be used to send sampling requests to the client.\n /// \n /// The server to be wrapped as an .\n /// The that can be used to issue sampling requests to the client.\n /// is .\n /// The client does not support sampling.\n public static IChatClient AsSamplingChatClient(this IMcpServer server)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return new SamplingChatClient(server);\n }\n\n /// Gets an on which logged messages will be sent as notifications to the client.\n /// The server to wrap as an .\n /// An that can be used to log to the client..\n public static ILoggerProvider AsClientLoggerProvider(this IMcpServer server)\n {\n Throw.IfNull(server);\n\n return new ClientLoggerProvider(server);\n }\n\n /// \n /// Requests the client to list the roots it exposes.\n /// \n /// The server initiating the request.\n /// The parameters for the list roots request.\n /// The to monitor for cancellation requests.\n /// A task containing the list of roots exposed by the client.\n /// is .\n /// The client does not support roots.\n /// \n /// This method requires the client to support the roots capability.\n /// Root resources allow clients to expose a hierarchical structure of resources that can be\n /// navigated and accessed by the server. These resources might include file systems, databases,\n /// or other structured data sources that the client makes available through the protocol.\n /// \n public static ValueTask RequestRootsAsync(\n this IMcpServer server, ListRootsRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfRootsUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.RootsList,\n request,\n McpJsonUtilities.JsonContext.Default.ListRootsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListRootsResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests additional information from the user via the client, allowing the server to elicit structured data.\n /// \n /// The server initiating the request.\n /// The parameters for the elicitation request.\n /// The to monitor for cancellation requests.\n /// A task containing the elicitation result.\n /// is .\n /// The client does not support elicitation.\n /// \n /// This method requires the client to support the elicitation capability.\n /// \n public static ValueTask ElicitAsync(\n this IMcpServer server, ElicitRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfElicitationUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.ElicitationCreate,\n request,\n McpJsonUtilities.JsonContext.Default.ElicitRequestParams,\n McpJsonUtilities.JsonContext.Default.ElicitResult,\n cancellationToken: cancellationToken);\n }\n\n private static void ThrowIfSamplingUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Sampling is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Sampling is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support sampling.\");\n }\n }\n\n private static void ThrowIfRootsUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Roots is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Roots are not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support roots.\");\n }\n }\n\n private static void ThrowIfElicitationUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Elicitation is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Elicitation is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support elicitation requests.\");\n }\n }\n\n /// Provides an implementation that's implemented via client sampling.\n private sealed class SamplingChatClient(IMcpServer server) : IChatClient\n {\n /// \n public Task GetResponseAsync(IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) =>\n server.SampleAsync(messages, options, cancellationToken);\n\n /// \n async IAsyncEnumerable IChatClient.GetStreamingResponseAsync(\n IEnumerable messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n var response = await GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);\n foreach (var update in response.ToChatResponseUpdates())\n {\n yield return update;\n }\n }\n\n /// \n object? IChatClient.GetService(Type serviceType, object? serviceKey)\n {\n Throw.IfNull(serviceType);\n\n return\n serviceKey is not null ? null :\n serviceType.IsInstanceOfType(this) ? this :\n serviceType.IsInstanceOfType(server) ? server :\n null;\n }\n\n /// \n void IDisposable.Dispose() { } // nop\n }\n\n /// \n /// Provides an implementation for creating loggers\n /// that send logging message notifications to the client for logged messages.\n /// \n private sealed class ClientLoggerProvider(IMcpServer server) : ILoggerProvider\n {\n /// \n public ILogger CreateLogger(string categoryName)\n {\n Throw.IfNull(categoryName);\n\n return new ClientLogger(server, categoryName);\n }\n\n /// \n void IDisposable.Dispose() { }\n\n private sealed class ClientLogger(IMcpServer server, string categoryName) : ILogger\n {\n /// \n public IDisposable? BeginScope(TState state) where TState : notnull =>\n null;\n\n /// \n public bool IsEnabled(LogLevel logLevel) =>\n server?.LoggingLevel is { } loggingLevel &&\n McpServer.ToLoggingLevel(logLevel) >= loggingLevel;\n\n /// \n public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)\n {\n if (!IsEnabled(logLevel))\n {\n return;\n }\n\n Throw.IfNull(formatter);\n\n Log(logLevel, formatter(state, exception));\n\n void Log(LogLevel logLevel, string message)\n {\n _ = server.SendNotificationAsync(NotificationMethods.LoggingMessageNotification, new LoggingMessageNotificationParams\n {\n Level = McpServer.ToLoggingLevel(logLevel),\n Data = JsonSerializer.SerializeToElement(message, McpJsonUtilities.JsonContext.Default.String),\n Logger = categoryName,\n });\n }\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building resources that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner resource instance.\n/// \npublic abstract class DelegatingMcpServerResource : McpServerResource\n{\n private readonly McpServerResource _innerResource;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner resource wrapped by this delegating resource.\n protected DelegatingMcpServerResource(McpServerResource innerResource)\n {\n Throw.IfNull(innerResource);\n _innerResource = innerResource;\n }\n\n /// \n public override Resource? ProtocolResource => _innerResource.ProtocolResource;\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate => _innerResource.ProtocolResourceTemplate;\n\n /// \n public override ValueTask ReadAsync(RequestContext request, CancellationToken cancellationToken = default) => \n _innerResource.ReadAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerResource.ToString();\n}\n"], ["/csharp-sdk/samples/EverythingServer/Prompts/ComplexPromptType.cs", "using EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class ComplexPromptType\n{\n [McpServerPrompt(Name = \"complex_prompt\"), Description(\"A prompt with arguments\")]\n public static IEnumerable ComplexPrompt(\n [Description(\"Temperature setting\")] int temperature,\n [Description(\"Output style\")] string? style = null)\n {\n return [\n new ChatMessage(ChatRole.User,$\"This is a complex prompt with arguments: temperature={temperature}, style={style}\"),\n new ChatMessage(ChatRole.Assistant, \"I understand. You've provided a complex prompt with temperature and style arguments. How would you like me to proceed?\"),\n new ChatMessage(ChatRole.User, [new DataContent(TinyImageTool.MCP_TINY_IMAGE)])\n ];\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitRequestParams.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued from the server to elicit additional information from the user via the client.\n/// \npublic sealed class ElicitRequestParams\n{\n /// \n /// Gets or sets the message to present to the user.\n /// \n [JsonPropertyName(\"message\")]\n public string Message { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the requested schema.\n /// \n /// \n /// May be one of , , , or .\n /// \n [JsonPropertyName(\"requestedSchema\")]\n [field: MaybeNull]\n public RequestSchema RequestedSchema\n {\n get => field ??= new RequestSchema();\n set => field = value;\n }\n\n /// Represents a request schema used in an elicitation request.\n public class RequestSchema\n {\n /// Gets the type of the schema.\n /// This is always \"object\".\n [JsonPropertyName(\"type\")]\n public string Type => \"object\";\n\n /// Gets or sets the properties of the schema.\n [JsonPropertyName(\"properties\")]\n [field: MaybeNull]\n public IDictionary Properties\n {\n get => field ??= new Dictionary();\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets the required properties of the schema.\n [JsonPropertyName(\"required\")]\n public IList? Required { get; set; }\n }\n\n /// \n /// Represents restricted subset of JSON Schema: \n /// , , , or .\n /// \n [JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n public abstract class PrimitiveSchemaDefinition\n {\n /// Prevent external derivations.\n protected private PrimitiveSchemaDefinition()\n {\n }\n\n /// Gets the type of the schema.\n [JsonPropertyName(\"type\")]\n public abstract string Type { get; set; }\n\n /// Gets or sets a title for the schema.\n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// Gets or sets a description for the schema.\n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override PrimitiveSchemaDefinition? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? title = null;\n string? description = null;\n int? minLength = null;\n int? maxLength = null;\n string? format = null;\n double? minimum = null;\n double? maximum = null;\n bool? defaultBool = null;\n IList? enumValues = null;\n IList? enumNames = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"title\":\n title = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"minLength\":\n minLength = reader.GetInt32();\n break;\n\n case \"maxLength\":\n maxLength = reader.GetInt32();\n break;\n\n case \"format\":\n format = reader.GetString();\n break;\n\n case \"minimum\":\n minimum = reader.GetDouble();\n break;\n\n case \"maximum\":\n maximum = reader.GetDouble();\n break;\n\n case \"default\":\n defaultBool = reader.GetBoolean();\n break;\n\n case \"enum\":\n enumValues = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n case \"enumNames\":\n enumNames = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n default:\n break;\n }\n }\n\n if (type is null)\n {\n throw new JsonException(\"The 'type' property is required.\");\n }\n\n PrimitiveSchemaDefinition? psd = null;\n switch (type)\n {\n case \"string\":\n if (enumValues is not null)\n {\n psd = new EnumSchema\n {\n Enum = enumValues,\n EnumNames = enumNames\n };\n }\n else\n {\n psd = new StringSchema\n {\n MinLength = minLength,\n MaxLength = maxLength,\n Format = format,\n };\n }\n break;\n\n case \"integer\":\n case \"number\":\n psd = new NumberSchema\n {\n Minimum = minimum,\n Maximum = maximum,\n };\n break;\n\n case \"boolean\":\n psd = new BooleanSchema\n {\n Default = defaultBool,\n };\n break;\n }\n\n if (psd is not null)\n {\n psd.Type = type;\n psd.Title = title;\n psd.Description = description;\n }\n\n return psd;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, PrimitiveSchemaDefinition value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n if (value.Title is not null)\n {\n writer.WriteString(\"title\", value.Title);\n }\n if (value.Description is not null)\n {\n writer.WriteString(\"description\", value.Description);\n }\n\n switch (value)\n {\n case StringSchema stringSchema:\n if (stringSchema.MinLength.HasValue)\n {\n writer.WriteNumber(\"minLength\", stringSchema.MinLength.Value);\n }\n if (stringSchema.MaxLength.HasValue)\n {\n writer.WriteNumber(\"maxLength\", stringSchema.MaxLength.Value);\n }\n if (stringSchema.Format is not null)\n {\n writer.WriteString(\"format\", stringSchema.Format);\n }\n break;\n\n case NumberSchema numberSchema:\n if (numberSchema.Minimum.HasValue)\n {\n writer.WriteNumber(\"minimum\", numberSchema.Minimum.Value);\n }\n if (numberSchema.Maximum.HasValue)\n {\n writer.WriteNumber(\"maximum\", numberSchema.Maximum.Value);\n }\n break;\n\n case BooleanSchema booleanSchema:\n if (booleanSchema.Default.HasValue)\n {\n writer.WriteBoolean(\"default\", booleanSchema.Default.Value);\n }\n break;\n\n case EnumSchema enumSchema:\n if (enumSchema.Enum is not null)\n {\n writer.WritePropertyName(\"enum\");\n JsonSerializer.Serialize(writer, enumSchema.Enum, McpJsonUtilities.JsonContext.Default.IListString);\n }\n if (enumSchema.EnumNames is not null)\n {\n writer.WritePropertyName(\"enumNames\");\n JsonSerializer.Serialize(writer, enumSchema.EnumNames, McpJsonUtilities.JsonContext.Default.IListString);\n }\n break;\n\n default:\n throw new JsonException($\"Unexpected schema type: {value.GetType().Name}\");\n }\n\n writer.WriteEndObject();\n }\n }\n }\n\n /// Represents a schema for a string type.\n public sealed class StringSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the minimum length for the string.\n [JsonPropertyName(\"minLength\")]\n public int? MinLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Minimum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the maximum length for the string.\n [JsonPropertyName(\"maxLength\")]\n public int? MaxLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Maximum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets a specific format for the string (\"email\", \"uri\", \"date\", or \"date-time\").\n [JsonPropertyName(\"format\")]\n public string? Format\n {\n get => field;\n set\n {\n if (value is not (null or \"email\" or \"uri\" or \"date\" or \"date-time\"))\n {\n throw new ArgumentException(\"Format must be 'email', 'uri', 'date', or 'date-time'.\", nameof(value));\n }\n\n field = value;\n }\n }\n }\n\n /// Represents a schema for a number or integer type.\n public sealed class NumberSchema : PrimitiveSchemaDefinition\n {\n /// \n [field: MaybeNull]\n public override string Type\n {\n get => field ??= \"number\";\n set\n {\n if (value is not (\"number\" or \"integer\"))\n {\n throw new ArgumentException(\"Type must be 'number' or 'integer'.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the minimum allowed value.\n [JsonPropertyName(\"minimum\")]\n public double? Minimum { get; set; }\n\n /// Gets or sets the maximum allowed value.\n [JsonPropertyName(\"maximum\")]\n public double? Maximum { get; set; }\n }\n\n /// Represents a schema for a Boolean type.\n public sealed class BooleanSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"boolean\";\n set\n {\n if (value is not \"boolean\")\n {\n throw new ArgumentException(\"Type must be 'boolean'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the default value for the Boolean.\n [JsonPropertyName(\"default\")]\n public bool? Default { get; set; }\n }\n\n /// Represents a schema for an enum type.\n public sealed class EnumSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the list of allowed string values for the enum.\n [JsonPropertyName(\"enum\")]\n [field: MaybeNull]\n public IList Enum\n {\n get => field ??= [];\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets optional display names corresponding to the enum values.\n [JsonPropertyName(\"enumNames\")]\n public IList? EnumNames { get; set; }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerHandlers.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a container for handlers used in the creation of an MCP server.\n/// \n/// \n/// \n/// This class provides a centralized collection of delegates that implement various capabilities of the Model Context Protocol.\n/// Each handler in this class corresponds to a specific endpoint in the Model Context Protocol and\n/// is responsible for processing a particular type of request. The handlers are used to customize\n/// the behavior of the MCP server by providing implementations for the various protocol operations.\n/// \n/// \n/// Handlers can be configured individually using the extension methods in \n/// such as and\n/// .\n/// \n/// \n/// When a client sends a request to the server, the appropriate handler is invoked to process the\n/// request and produce a response according to the protocol specification. Which handler is selected\n/// is done based on an ordinal, case-sensitive string comparison.\n/// \n/// \npublic sealed class McpServerHandlers\n{\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// \n /// \n /// This handler works alongside any tools defined in the collection.\n /// Tools from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the collection.\n /// The handler should implement logic to execute the requested tool and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available prompts when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more prompts.\n /// \n /// \n /// This handler works alongside any prompts defined in the collection.\n /// Prompts from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt that isn't found in the collection.\n /// The handler should implement logic to fetch or generate the requested prompt and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resource templates when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resource templates.\n /// \n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resources when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resources.\n /// \n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests the content of a specific resource identified by its URI.\n /// The handler should implement logic to locate and retrieve the requested resource.\n /// \n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler processes auto-completion requests, returning a list of suggestions based on the \n /// reference type and current argument value.\n /// \n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to receive notifications about changes to specific resources or resource patterns.\n /// The handler should implement logic to register the client's interest in the specified resources\n /// and set up the necessary infrastructure to send notifications when those resources change.\n /// \n /// \n /// After a successful subscription, the server should send resource change notifications to the client\n /// whenever a relevant resource is created, updated, or deleted.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to stop receiving notifications about previously subscribed resources.\n /// The handler should implement logic to remove the client's subscriptions to the specified resources\n /// and clean up any associated resources.\n /// \n /// \n /// After a successful unsubscription, the server should no longer send resource change notifications\n /// to the client for the specified resources.\n /// \n /// \n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler processes requests from clients. When set, it enables\n /// clients to control which log messages they receive by specifying a minimum severity threshold.\n /// \n /// \n /// After handling a level change request, the server typically begins sending log messages\n /// at or above the specified level to the client as notifications/message notifications.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n\n /// \n /// Overwrite any handlers in McpServerOptions with non-null handlers from this instance.\n /// \n /// \n /// \n internal void OverwriteWithSetHandlers(McpServerOptions options)\n {\n PromptsCapability? promptsCapability = options.Capabilities?.Prompts;\n if (ListPromptsHandler is not null || GetPromptHandler is not null)\n {\n promptsCapability ??= new();\n promptsCapability.ListPromptsHandler = ListPromptsHandler ?? promptsCapability.ListPromptsHandler;\n promptsCapability.GetPromptHandler = GetPromptHandler ?? promptsCapability.GetPromptHandler;\n }\n\n ResourcesCapability? resourcesCapability = options.Capabilities?.Resources;\n if (ListResourcesHandler is not null ||\n ReadResourceHandler is not null)\n {\n resourcesCapability ??= new();\n resourcesCapability.ListResourceTemplatesHandler = ListResourceTemplatesHandler ?? resourcesCapability.ListResourceTemplatesHandler;\n resourcesCapability.ListResourcesHandler = ListResourcesHandler ?? resourcesCapability.ListResourcesHandler;\n resourcesCapability.ReadResourceHandler = ReadResourceHandler ?? resourcesCapability.ReadResourceHandler;\n\n if (SubscribeToResourcesHandler is not null || UnsubscribeFromResourcesHandler is not null)\n {\n resourcesCapability.SubscribeToResourcesHandler = SubscribeToResourcesHandler ?? resourcesCapability.SubscribeToResourcesHandler;\n resourcesCapability.UnsubscribeFromResourcesHandler = UnsubscribeFromResourcesHandler ?? resourcesCapability.UnsubscribeFromResourcesHandler;\n resourcesCapability.Subscribe = true;\n }\n }\n\n ToolsCapability? toolsCapability = options.Capabilities?.Tools;\n if (ListToolsHandler is not null || CallToolHandler is not null)\n {\n toolsCapability ??= new();\n toolsCapability.ListToolsHandler = ListToolsHandler ?? toolsCapability.ListToolsHandler;\n toolsCapability.CallToolHandler = CallToolHandler ?? toolsCapability.CallToolHandler;\n }\n\n LoggingCapability? loggingCapability = options.Capabilities?.Logging;\n if (SetLoggingLevelHandler is not null)\n {\n loggingCapability ??= new();\n loggingCapability.SetLoggingLevelHandler = SetLoggingLevelHandler;\n }\n\n CompletionsCapability? completionsCapability = options.Capabilities?.Completions;\n if (CompleteHandler is not null)\n {\n completionsCapability ??= new();\n completionsCapability.CompleteHandler = CompleteHandler;\n }\n\n options.Capabilities ??= new();\n options.Capabilities.Prompts = promptsCapability;\n options.Capabilities.Resources = resourcesCapability;\n options.Capabilities.Tools = toolsCapability;\n options.Capabilities.Logging = loggingCapability;\n options.Capabilities.Completions = completionsCapability;\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/LongRunningTool.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class LongRunningTool\n{\n [McpServerTool(Name = \"longRunningOperation\"), Description(\"Demonstrates a long running operation with progress updates\")]\n public static async Task LongRunningOperation(\n IMcpServer server,\n RequestContext context,\n int duration = 10,\n int steps = 5)\n {\n var progressToken = context.Params?.ProgressToken;\n var stepDuration = duration / steps;\n\n for (int i = 1; i <= steps + 1; i++)\n {\n await Task.Delay(stepDuration * 1000);\n \n if (progressToken is not null)\n {\n await server.SendNotificationAsync(\"notifications/progress\", new\n {\n Progress = i,\n Total = steps,\n progressToken\n });\n }\n }\n\n return $\"Long running operation completed. Duration: {duration} seconds. Steps: {steps}.\";\n }\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Program.cs", "using Microsoft.AspNetCore.Authentication.JwtBearer;\nusing Microsoft.IdentityModel.Tokens;\nusing ModelContextProtocol.AspNetCore.Authentication;\nusing ProtectedMCPServer.Tools;\nusing System.Net.Http.Headers;\nusing System.Security.Claims;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nvar serverUrl = \"http://localhost:7071/\";\nvar inMemoryOAuthServerUrl = \"https://localhost:7029\";\n\nbuilder.Services.AddAuthentication(options =>\n{\n options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;\n options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;\n})\n.AddJwtBearer(options =>\n{\n // Configure to validate tokens from our in-memory OAuth server\n options.Authority = inMemoryOAuthServerUrl;\n options.TokenValidationParameters = new TokenValidationParameters\n {\n ValidateIssuer = true,\n ValidateAudience = true,\n ValidateLifetime = true,\n ValidateIssuerSigningKey = true,\n ValidAudience = serverUrl, // Validate that the audience matches the resource metadata as suggested in RFC 8707\n ValidIssuer = inMemoryOAuthServerUrl,\n NameClaimType = \"name\",\n RoleClaimType = \"roles\"\n };\n\n options.Events = new JwtBearerEvents\n {\n OnTokenValidated = context =>\n {\n var name = context.Principal?.Identity?.Name ?? \"unknown\";\n var email = context.Principal?.FindFirstValue(\"preferred_username\") ?? \"unknown\";\n Console.WriteLine($\"Token validated for: {name} ({email})\");\n return Task.CompletedTask;\n },\n OnAuthenticationFailed = context =>\n {\n Console.WriteLine($\"Authentication failed: {context.Exception.Message}\");\n return Task.CompletedTask;\n },\n OnChallenge = context =>\n {\n Console.WriteLine($\"Challenging client to authenticate with Entra ID\");\n return Task.CompletedTask;\n }\n };\n})\n.AddMcp(options =>\n{\n options.ResourceMetadata = new()\n {\n Resource = new Uri(serverUrl),\n ResourceDocumentation = new Uri(\"https://docs.example.com/api/weather\"),\n AuthorizationServers = { new Uri(inMemoryOAuthServerUrl) },\n ScopesSupported = [\"mcp:tools\"],\n };\n});\n\nbuilder.Services.AddAuthorization();\n\nbuilder.Services.AddHttpContextAccessor();\nbuilder.Services.AddMcpServer()\n .WithTools()\n .WithHttpTransport();\n\n// Configure HttpClientFactory for weather.gov API\nbuilder.Services.AddHttpClient(\"WeatherApi\", client =>\n{\n client.BaseAddress = new Uri(\"https://api.weather.gov\");\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n});\n\nvar app = builder.Build();\n\napp.UseAuthentication();\napp.UseAuthorization();\n\n// Use the default MCP policy name that we've configured\napp.MapMcp().RequireAuthorization();\n\nConsole.WriteLine($\"Starting MCP server with authorization at {serverUrl}\");\nConsole.WriteLine($\"Using in-memory OAuth server at {inMemoryOAuthServerUrl}\");\nConsole.WriteLine($\"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource\");\nConsole.WriteLine(\"Press Ctrl+C to stop the server\");\n\napp.Run(serverUrl);\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationOptions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Options for the MCP authentication handler.\n/// \npublic class McpAuthenticationOptions : AuthenticationSchemeOptions\n{\n private static readonly Uri DefaultResourceMetadataUri = new(\"/.well-known/oauth-protected-resource\", UriKind.Relative);\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationOptions()\n {\n // \"Bearer\" is JwtBearerDefaults.AuthenticationScheme, but we don't have a reference to the JwtBearer package here.\n ForwardAuthenticate = \"Bearer\";\n ResourceMetadataUri = DefaultResourceMetadataUri;\n Events = new McpAuthenticationEvents();\n }\n\n /// \n /// Gets or sets the events used to handle authentication events.\n /// \n public new McpAuthenticationEvents Events\n {\n get { return (McpAuthenticationEvents)base.Events!; }\n set { base.Events = value; }\n }\n\n /// \n /// The URI to the resource metadata document.\n /// \n /// \n /// This URI will be included in the WWW-Authenticate header when a 401 response is returned.\n /// \n public Uri ResourceMetadataUri { get; set; }\n\n /// \n /// Gets or sets the protected resource metadata.\n /// \n /// \n /// This contains the OAuth metadata for the protected resource, including authorization servers,\n /// supported scopes, and other information needed for clients to authenticate.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpJsonUtilities.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Authentication;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// Provides a collection of utility methods for working with JSON data in the context of MCP.\npublic static partial class McpJsonUtilities\n{\n /// \n /// Gets the singleton used as the default in JSON serialization operations.\n /// \n /// \n /// \n /// For Native AOT or applications disabling , this instance \n /// includes source generated contracts for all common exchange types contained in the ModelContextProtocol library.\n /// \n /// \n /// It additionally turns on the following settings:\n /// \n /// Enables defaults.\n /// Enables as the default ignore condition for properties.\n /// Enables as the default number handling for number types.\n /// \n /// \n /// \n public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();\n\n /// \n /// Creates default options to use for MCP-related serialization.\n /// \n /// The configured options.\n [UnconditionalSuppressMessage(\"ReflectionAnalysis\", \"IL3050:RequiresDynamicCode\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n [UnconditionalSuppressMessage(\"Trimming\", \"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n private static JsonSerializerOptions CreateDefaultOptions()\n {\n // Copy the configuration from the source generated context.\n JsonSerializerOptions options = new(JsonContext.Default.Options);\n\n // Chain with all supported types from MEAI.\n options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);\n\n // Add a converter for user-defined enums, if reflection is enabled by default.\n if (JsonSerializer.IsReflectionEnabledByDefault)\n {\n options.Converters.Add(new CustomizableJsonStringEnumConverter());\n }\n\n options.MakeReadOnly();\n return options;\n }\n\n internal static JsonTypeInfo GetTypeInfo(this JsonSerializerOptions options) =>\n (JsonTypeInfo)options.GetTypeInfo(typeof(T));\n\n internal static JsonElement DefaultMcpToolSchema { get; } = ParseJsonElement(\"\"\"{\"type\":\"object\"}\"\"\"u8);\n internal static object? AsObject(this JsonElement element) => element.ValueKind is JsonValueKind.Null ? null : element;\n\n internal static bool IsValidMcpToolSchema(JsonElement element)\n {\n if (element.ValueKind is not JsonValueKind.Object)\n {\n return false;\n }\n\n foreach (JsonProperty property in element.EnumerateObject())\n {\n if (property.NameEquals(\"type\"))\n {\n if (property.Value.ValueKind is not JsonValueKind.String ||\n !property.Value.ValueEquals(\"object\"))\n {\n return false;\n }\n\n return true; // No need to check other properties\n }\n }\n\n return false; // No type keyword found.\n }\n\n // Keep in sync with CreateDefaultOptions above.\n [JsonSourceGenerationOptions(JsonSerializerDefaults.Web,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n NumberHandling = JsonNumberHandling.AllowReadingFromString)]\n \n // JSON-RPC\n [JsonSerializable(typeof(JsonRpcMessage))]\n [JsonSerializable(typeof(JsonRpcMessage[]))]\n [JsonSerializable(typeof(JsonRpcRequest))]\n [JsonSerializable(typeof(JsonRpcNotification))]\n [JsonSerializable(typeof(JsonRpcResponse))]\n [JsonSerializable(typeof(JsonRpcError))]\n\n // MCP Notification Params\n [JsonSerializable(typeof(CancelledNotificationParams))]\n [JsonSerializable(typeof(InitializedNotificationParams))]\n [JsonSerializable(typeof(LoggingMessageNotificationParams))]\n [JsonSerializable(typeof(ProgressNotificationParams))]\n [JsonSerializable(typeof(PromptListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceUpdatedNotificationParams))]\n [JsonSerializable(typeof(RootsListChangedNotificationParams))]\n [JsonSerializable(typeof(ToolListChangedNotificationParams))]\n\n // MCP Request Params / Results\n [JsonSerializable(typeof(CallToolRequestParams))]\n [JsonSerializable(typeof(CallToolResult))]\n [JsonSerializable(typeof(CompleteRequestParams))]\n [JsonSerializable(typeof(CompleteResult))]\n [JsonSerializable(typeof(CreateMessageRequestParams))]\n [JsonSerializable(typeof(CreateMessageResult))]\n [JsonSerializable(typeof(ElicitRequestParams))]\n [JsonSerializable(typeof(ElicitResult))]\n [JsonSerializable(typeof(EmptyResult))]\n [JsonSerializable(typeof(GetPromptRequestParams))]\n [JsonSerializable(typeof(GetPromptResult))]\n [JsonSerializable(typeof(InitializeRequestParams))]\n [JsonSerializable(typeof(InitializeResult))]\n [JsonSerializable(typeof(ListPromptsRequestParams))]\n [JsonSerializable(typeof(ListPromptsResult))]\n [JsonSerializable(typeof(ListResourcesRequestParams))]\n [JsonSerializable(typeof(ListResourcesResult))]\n [JsonSerializable(typeof(ListResourceTemplatesRequestParams))]\n [JsonSerializable(typeof(ListResourceTemplatesResult))]\n [JsonSerializable(typeof(ListRootsRequestParams))]\n [JsonSerializable(typeof(ListRootsResult))]\n [JsonSerializable(typeof(ListToolsRequestParams))]\n [JsonSerializable(typeof(ListToolsResult))]\n [JsonSerializable(typeof(PingResult))]\n [JsonSerializable(typeof(ReadResourceRequestParams))]\n [JsonSerializable(typeof(ReadResourceResult))]\n [JsonSerializable(typeof(SetLevelRequestParams))]\n [JsonSerializable(typeof(SubscribeRequestParams))]\n [JsonSerializable(typeof(UnsubscribeRequestParams))]\n\n // MCP Content\n [JsonSerializable(typeof(ContentBlock))]\n [JsonSerializable(typeof(TextContentBlock))]\n [JsonSerializable(typeof(ImageContentBlock))]\n [JsonSerializable(typeof(AudioContentBlock))]\n [JsonSerializable(typeof(EmbeddedResourceBlock))]\n [JsonSerializable(typeof(ResourceLinkBlock))]\n [JsonSerializable(typeof(PromptReference))]\n [JsonSerializable(typeof(ResourceTemplateReference))]\n [JsonSerializable(typeof(BlobResourceContents))]\n [JsonSerializable(typeof(TextResourceContents))]\n\n // Other MCP Types\n [JsonSerializable(typeof(IReadOnlyDictionary))]\n [JsonSerializable(typeof(ProgressToken))]\n\n [JsonSerializable(typeof(ProtectedResourceMetadata))]\n [JsonSerializable(typeof(AuthorizationServerMetadata))]\n [JsonSerializable(typeof(TokenContainer))]\n [JsonSerializable(typeof(DynamicClientRegistrationRequest))]\n [JsonSerializable(typeof(DynamicClientRegistrationResponse))]\n\n // Primitive types for use in consuming AIFunctions\n [JsonSerializable(typeof(string))]\n [JsonSerializable(typeof(byte))]\n [JsonSerializable(typeof(byte?))]\n [JsonSerializable(typeof(sbyte))]\n [JsonSerializable(typeof(sbyte?))]\n [JsonSerializable(typeof(ushort))]\n [JsonSerializable(typeof(ushort?))]\n [JsonSerializable(typeof(short))]\n [JsonSerializable(typeof(short?))]\n [JsonSerializable(typeof(uint))]\n [JsonSerializable(typeof(uint?))]\n [JsonSerializable(typeof(int))]\n [JsonSerializable(typeof(int?))]\n [JsonSerializable(typeof(ulong))]\n [JsonSerializable(typeof(ulong?))]\n [JsonSerializable(typeof(long))]\n [JsonSerializable(typeof(long?))]\n [JsonSerializable(typeof(nuint))]\n [JsonSerializable(typeof(nuint?))]\n [JsonSerializable(typeof(nint))]\n [JsonSerializable(typeof(nint?))]\n [JsonSerializable(typeof(bool))]\n [JsonSerializable(typeof(bool?))]\n [JsonSerializable(typeof(char))]\n [JsonSerializable(typeof(char?))]\n [JsonSerializable(typeof(float))]\n [JsonSerializable(typeof(float?))]\n [JsonSerializable(typeof(double))]\n [JsonSerializable(typeof(double?))]\n [JsonSerializable(typeof(decimal))]\n [JsonSerializable(typeof(decimal?))]\n [JsonSerializable(typeof(Guid))]\n [JsonSerializable(typeof(Guid?))]\n [JsonSerializable(typeof(Uri))]\n [JsonSerializable(typeof(Version))]\n [JsonSerializable(typeof(TimeSpan))]\n [JsonSerializable(typeof(TimeSpan?))]\n [JsonSerializable(typeof(DateTime))]\n [JsonSerializable(typeof(DateTime?))]\n [JsonSerializable(typeof(DateTimeOffset))]\n [JsonSerializable(typeof(DateTimeOffset?))]\n#if NET\n [JsonSerializable(typeof(DateOnly))]\n [JsonSerializable(typeof(DateOnly?))]\n [JsonSerializable(typeof(TimeOnly))]\n [JsonSerializable(typeof(TimeOnly?))]\n [JsonSerializable(typeof(Half))]\n [JsonSerializable(typeof(Half?))]\n [JsonSerializable(typeof(Int128))]\n [JsonSerializable(typeof(Int128?))]\n [JsonSerializable(typeof(UInt128))]\n [JsonSerializable(typeof(UInt128?))]\n#endif\n\n [ExcludeFromCodeCoverage]\n internal sealed partial class JsonContext : JsonSerializerContext;\n\n private static JsonElement ParseJsonElement(ReadOnlySpan utf8Json)\n {\n Utf8JsonReader reader = new(utf8Json);\n return JsonElement.ParseValue(ref reader);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessage.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents any JSON-RPC message used in the Model Context Protocol (MCP).\n/// \n/// \n/// This interface serves as the foundation for all message types in the JSON-RPC 2.0 protocol\n/// used by MCP, including requests, responses, notifications, and errors. JSON-RPC is a stateless,\n/// lightweight remote procedure call (RPC) protocol that uses JSON as its data format.\n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessage()\n {\n }\n\n /// \n /// Gets the JSON-RPC protocol version used.\n /// \n /// \n [JsonPropertyName(\"jsonrpc\")]\n public string JsonRpc { get; init; } = \"2.0\";\n\n /// \n /// Gets or sets the transport the was received on or should be sent over.\n /// \n /// \n /// This is used to support the Streamable HTTP transport where the specification states that the server\n /// SHOULD include JSON-RPC responses in the HTTP response body for the POST request containing\n /// the corresponding JSON-RPC request. It may be for other transports.\n /// \n [JsonIgnore]\n public ITransport? RelatedTransport { get; set; }\n\n /// \n /// Gets or sets the that should be used to run any handlers\n /// \n /// \n /// This is used to support the Streamable HTTP transport in its default stateful mode. In this mode,\n /// the outlives the initial HTTP request context it was created on, and new\n /// JSON-RPC messages can originate from future HTTP requests. This allows the transport to flow the\n /// context with the JSON-RPC message. This is particularly useful for enabling IHttpContextAccessor\n /// in tool calls.\n /// \n [JsonIgnore]\n public ExecutionContext? ExecutionContext { get; set; }\n\n /// \n /// Provides a for messages,\n /// handling polymorphic deserialization of different message types.\n /// \n /// \n /// \n /// This converter is responsible for correctly deserializing JSON-RPC messages into their appropriate\n /// concrete types based on the message structure. It analyzes the JSON payload and determines if it\n /// represents a request, notification, successful response, or error response.\n /// \n /// \n /// The type determination rules follow the JSON-RPC 2.0 specification:\n /// \n /// Messages with \"method\" and \"id\" properties are deserialized as .\n /// Messages with \"method\" but no \"id\" property are deserialized as .\n /// Messages with \"id\" and \"result\" properties are deserialized as .\n /// Messages with \"id\" and \"error\" properties are deserialized as .\n /// \n /// \n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override JsonRpcMessage? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException(\"Expected StartObject token\");\n }\n\n using var doc = JsonDocument.ParseValue(ref reader);\n var root = doc.RootElement;\n\n // All JSON-RPC messages must have a jsonrpc property with value \"2.0\"\n if (!root.TryGetProperty(\"jsonrpc\", out var versionProperty) ||\n versionProperty.GetString() != \"2.0\")\n {\n throw new JsonException(\"Invalid or missing jsonrpc version\");\n }\n\n // Determine the message type based on the presence of id, method, and error properties\n bool hasId = root.TryGetProperty(\"id\", out _);\n bool hasMethod = root.TryGetProperty(\"method\", out _);\n bool hasError = root.TryGetProperty(\"error\", out _);\n\n var rawText = root.GetRawText();\n\n // Messages with an id but no method are responses\n if (hasId && !hasMethod)\n {\n // Messages with an error property are error responses\n if (hasError)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with a result property are success responses\n if (root.TryGetProperty(\"result\", out _))\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Response must have either result or error\");\n }\n\n // Messages with a method but no id are notifications\n if (hasMethod && !hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with both method and id are requests\n if (hasMethod && hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Invalid JSON-RPC message format\");\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, JsonRpcMessage value, JsonSerializerOptions options)\n {\n switch (value)\n {\n case JsonRpcRequest request:\n JsonSerializer.Serialize(writer, request, options.GetTypeInfo());\n break;\n case JsonRpcNotification notification:\n JsonSerializer.Serialize(writer, notification, options.GetTypeInfo());\n break;\n case JsonRpcResponse response:\n JsonSerializer.Serialize(writer, response, options.GetTypeInfo());\n break;\n case JsonRpcError error:\n JsonSerializer.Serialize(writer, error, options.GetTypeInfo());\n break;\n default:\n throw new JsonException($\"Unknown JSON-RPC message type: {value.GetType()}\");\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourcesCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the resources capability configuration.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ResourcesCapability\n{\n /// \n /// Gets or sets whether this server supports subscribing to resource updates.\n /// \n [JsonPropertyName(\"subscribe\")]\n public bool? Subscribe { get; set; }\n\n /// \n /// Gets or sets whether this server supports notifications for changes to the resource list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when resources are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their resource cache.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is called when clients request available resource templates that can be used\n /// to create resources within the Model Context Protocol server.\n /// Resource templates define the structure and URI patterns for resources accessible in the system,\n /// allowing clients to discover available resource types and their access patterns.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler responds to client requests for available resources and returns information about resources accessible through the server.\n /// The implementation should return a with the matching resources.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is responsible for retrieving the content of a specific resource identified by its URI in the Model Context Protocol.\n /// When a client sends a resources/read request, this handler is invoked with the resource URI.\n /// The handler should implement logic to locate and retrieve the requested resource, then return\n /// its contents in a ReadResourceResult object.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be subscribed to. The implementation should register the client's interest in receiving updates\n /// for the specified resource.\n /// Subscriptions allow clients to receive real-time notifications when resources change, without\n /// requiring polling.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be unsubscribed from. The implementation should remove the client's registration for receiving updates\n /// about the specified resource.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets a collection of resources served by the server.\n /// \n /// \n /// \n /// Resources specified via augment the , \n /// and handlers, if provided. Resources with template expressions in their URI templates are considered resource templates\n /// and are listed via ListResourceTemplate, whereas resources without template parameters are considered static resources and are listed with ListResources.\n /// \n /// \n /// ReadResource requests will first check the for the exact resource being requested. If no match is found, they'll proceed to\n /// try to match the resource against each resource template in . If no match is still found, the request will fall back to\n /// any handler registered for .\n /// \n /// \n [JsonIgnore]\n public McpServerResourceCollection? ResourceCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol/McpServerOptionsSetup.cs", "using Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Configures the McpServerOptions using addition services from DI.\n/// \n/// The server handlers configuration options.\n/// Tools individually registered.\n/// Prompts individually registered.\n/// Resources individually registered.\ninternal sealed class McpServerOptionsSetup(\n IOptions serverHandlers,\n IEnumerable serverTools,\n IEnumerable serverPrompts,\n IEnumerable serverResources) : IConfigureOptions\n{\n /// \n /// Configures the given McpServerOptions instance by setting server information\n /// and applying custom server handlers and tools.\n /// \n /// The options instance to be configured.\n public void Configure(McpServerOptions options)\n {\n Throw.IfNull(options);\n\n // Collect all of the provided tools into a tools collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection toolCollection = options.Capabilities?.Tools?.ToolCollection ?? [];\n foreach (var tool in serverTools)\n {\n toolCollection.TryAdd(tool);\n }\n\n if (!toolCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Tools ??= new();\n options.Capabilities.Tools.ToolCollection = toolCollection;\n }\n\n // Collect all of the provided prompts into a prompts collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection promptCollection = options.Capabilities?.Prompts?.PromptCollection ?? [];\n foreach (var prompt in serverPrompts)\n {\n promptCollection.TryAdd(prompt);\n }\n\n if (!promptCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Prompts ??= new();\n options.Capabilities.Prompts.PromptCollection = promptCollection;\n }\n\n // Collect all of the provided resources into a resources collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerResourceCollection resourceCollection = options.Capabilities?.Resources?.ResourceCollection ?? [];\n foreach (var resource in serverResources)\n {\n resourceCollection.TryAdd(resource);\n }\n\n if (!resourceCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Resources ??= new();\n options.Capabilities.Resources.ResourceCollection = resourceCollection;\n }\n\n // Apply custom server handlers.\n serverHandlers.Value.OverwriteWithSetHandlers(options);\n }\n}\n"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace QuickstartWeatherServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public static async Task GetAlerts(\n HttpClient client,\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public static async Task GetForecast(\n HttpClient client,\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace ProtectedMCPServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n private readonly IHttpClientFactory _httpClientFactory;\n\n public WeatherTools(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public async Task GetAlerts(\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public async Task GetForecast(\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/samples/ProtectedMCPClient/Program.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Text;\nusing System.Web;\n\nvar serverUrl = \"http://localhost:7071/\";\n\nConsole.WriteLine(\"Protected MCP Client\");\nConsole.WriteLine($\"Connecting to weather server at {serverUrl}...\");\nConsole.WriteLine();\n\n// We can customize a shared HttpClient with a custom handler if desired\nvar sharedHandler = new SocketsHttpHandler\n{\n PooledConnectionLifetime = TimeSpan.FromMinutes(2),\n PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1)\n};\nvar httpClient = new HttpClient(sharedHandler);\n\nvar consoleLoggerFactory = LoggerFactory.Create(builder =>\n{\n builder.AddConsole();\n});\n\nvar transport = new SseClientTransport(new()\n{\n Endpoint = new Uri(serverUrl),\n Name = \"Secure Weather Client\",\n OAuth = new()\n {\n ClientName = \"ProtectedMcpClient\",\n RedirectUri = new Uri(\"http://localhost:1179/callback\"),\n AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,\n }\n}, httpClient, consoleLoggerFactory);\n\nvar client = await McpClientFactory.CreateAsync(transport, loggerFactory: consoleLoggerFactory);\n\nvar tools = await client.ListToolsAsync();\nif (tools.Count == 0)\n{\n Console.WriteLine(\"No tools available on the server.\");\n return;\n}\n\nConsole.WriteLine($\"Found {tools.Count} tools on the server.\");\nConsole.WriteLine();\n\nif (tools.Any(t => t.Name == \"get_alerts\"))\n{\n Console.WriteLine(\"Calling get_alerts tool...\");\n\n var result = await client.CallToolAsync(\n \"get_alerts\",\n new Dictionary { { \"state\", \"WA\" } }\n );\n\n Console.WriteLine(\"Result: \" + ((TextContentBlock)result.Content[0]).Text);\n Console.WriteLine();\n}\n\n/// Handles the OAuth authorization URL by starting a local HTTP server and opening a browser.\n/// This implementation demonstrates how SDK consumers can provide their own authorization flow.\n/// \n/// The authorization URL to open in the browser.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// The authorization code extracted from the callback, or null if the operation failed.\nstatic async Task HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken)\n{\n Console.WriteLine(\"Starting OAuth authorization flow...\");\n Console.WriteLine($\"Opening browser to: {authorizationUrl}\");\n\n var listenerPrefix = redirectUri.GetLeftPart(UriPartial.Authority);\n if (!listenerPrefix.EndsWith(\"/\")) listenerPrefix += \"/\";\n\n using var listener = new HttpListener();\n listener.Prefixes.Add(listenerPrefix);\n\n try\n {\n listener.Start();\n Console.WriteLine($\"Listening for OAuth callback on: {listenerPrefix}\");\n\n OpenBrowser(authorizationUrl);\n\n var context = await listener.GetContextAsync();\n var query = HttpUtility.ParseQueryString(context.Request.Url?.Query ?? string.Empty);\n var code = query[\"code\"];\n var error = query[\"error\"];\n\n string responseHtml = \"

Authentication complete

You can close this window now.

\";\n byte[] buffer = Encoding.UTF8.GetBytes(responseHtml);\n context.Response.ContentLength64 = buffer.Length;\n context.Response.ContentType = \"text/html\";\n context.Response.OutputStream.Write(buffer, 0, buffer.Length);\n context.Response.Close();\n\n if (!string.IsNullOrEmpty(error))\n {\n Console.WriteLine($\"Auth error: {error}\");\n return null;\n }\n\n if (string.IsNullOrEmpty(code))\n {\n Console.WriteLine(\"No authorization code received\");\n return null;\n }\n\n Console.WriteLine(\"Authorization code received successfully.\");\n return code;\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error getting auth code: {ex.Message}\");\n return null;\n }\n finally\n {\n if (listener.IsListening) listener.Stop();\n }\n}\n\n/// \n/// Opens the specified URL in the default browser.\n/// \n/// The URL to open.\nstatic void OpenBrowser(Uri url)\n{\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = url.ToString(),\n UseShellExecute = true\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error opening browser. {ex.Message}\");\n Console.WriteLine($\"Please manually open this URL: {url}\");\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Diagnostics.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\n\nnamespace ModelContextProtocol;\n\ninternal static class Diagnostics\n{\n internal static ActivitySource ActivitySource { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Meter Meter { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Histogram CreateDurationHistogram(string name, string description, bool longBuckets) =>\n Meter.CreateHistogram(name, \"s\", description\n#if NET9_0_OR_GREATER\n , advice: longBuckets ? LongSecondsBucketBoundaries : ShortSecondsBucketBoundaries\n#endif\n );\n\n#if NET9_0_OR_GREATER\n /// \n /// Follows boundaries from http.server.request.duration/http.client.request.duration\n /// \n private static InstrumentAdvice ShortSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n };\n\n /// \n /// Not based on a standard. Larger bucket sizes for longer lasting operations, e.g. HTTP connection duration.\n /// See https://github.com/open-telemetry/semantic-conventions/issues/336\n /// \n private static InstrumentAdvice LongSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300],\n };\n#endif\n\n internal static ActivityContext ExtractActivityContext(this DistributedContextPropagator propagator, JsonRpcMessage message)\n {\n propagator.ExtractTraceIdAndState(message, ExtractContext, out var traceparent, out var tracestate);\n ActivityContext.TryParse(traceparent, tracestate, true, out var activityContext);\n return activityContext;\n }\n\n private static void ExtractContext(object? message, string fieldName, out string? fieldValue, out IEnumerable? fieldValues)\n {\n fieldValues = null;\n fieldValue = null;\n\n JsonNode? meta = null;\n switch (message)\n {\n case JsonRpcRequest request:\n meta = request.Params?[\"_meta\"];\n break;\n\n case JsonRpcNotification notification:\n meta = notification.Params?[\"_meta\"];\n break;\n }\n\n if (meta?[fieldName] is JsonValue value && value.GetValueKind() == JsonValueKind.String)\n {\n fieldValue = value.GetValue();\n }\n }\n\n internal static void InjectActivityContext(this DistributedContextPropagator propagator, Activity? activity, JsonRpcMessage message)\n {\n // noop if activity is null\n propagator.Inject(activity, message, InjectContext);\n }\n\n private static void InjectContext(object? message, string key, string value)\n {\n JsonNode? parameters = null;\n switch (message)\n {\n case JsonRpcRequest request:\n parameters = request.Params;\n break;\n\n case JsonRpcNotification notification:\n parameters = notification.Params;\n break;\n }\n\n // Replace any params._meta with the current value\n if (parameters is JsonObject jsonObject)\n {\n if (jsonObject[\"_meta\"] is not JsonObject meta)\n {\n meta = new JsonObject();\n jsonObject[\"_meta\"] = meta;\n }\n meta[key] = value;\n }\n }\n\n internal static bool ShouldInstrumentMessage(JsonRpcMessage message) =>\n ActivitySource.HasListeners() &&\n message switch\n {\n JsonRpcRequest => true,\n JsonRpcNotification notification => notification.Method != NotificationMethods.LoggingMessageNotification,\n _ => false\n };\n\n internal static ActivityLink[] ActivityLinkFromCurrent() => Activity.Current is null ? [] : [new ActivityLink(Activity.Current.Context)];\n}\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/Protocol/ReadResourceResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ReadResourceResult : Result\n{\n /// \n /// Gets or sets a list of objects that this resource contains.\n /// \n /// \n /// This property contains the actual content of the requested resource, which can be\n /// either text-based () or binary ().\n /// The type of content included depends on the resource being accessed.\n /// \n [JsonPropertyName(\"contents\")]\n public IList Contents { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/TextResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents text-based contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when textual data needs to be exchanged through\n/// the Model Context Protocol. The text is stored directly in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for binary resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class TextResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the text of the item.\n /// \n [JsonPropertyName(\"text\")]\n public string Text { get; set; } = string.Empty;\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/SampleLlmTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses dependency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n ChatOptions options = new()\n {\n Instructions = \"You are a helpful test server.\",\n MaxOutputTokens = maxTokens,\n Temperature = 0.7f,\n };\n\n var samplingResponse = await thisServer.AsSamplingChatClient().GetResponseAsync(prompt, options, cancellationToken);\n\n return $\"LLM sampling result: {samplingResponse}\";\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.Core/Protocol/BlobResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the binary contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when binary data needs to be exchanged through\n/// the Model Context Protocol. The binary data is represented as a base64-encoded string\n/// in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for text-based resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class BlobResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the base64-encoded string representing the binary data of the item.\n /// \n [JsonPropertyName(\"blob\")]\n public string Blob { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/Common/CancellableStreamReader/ValueStringBuilder.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.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n#nullable enable\n\nnamespace System.Text\n{\n internal ref partial struct ValueStringBuilder\n {\n private char[]? _arrayToReturnToPool;\n private Span _chars;\n private int _pos;\n\n public ValueStringBuilder(Span initialBuffer)\n {\n _arrayToReturnToPool = null;\n _chars = initialBuffer;\n _pos = 0;\n }\n\n public ValueStringBuilder(int initialCapacity)\n {\n _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity);\n _chars = _arrayToReturnToPool;\n _pos = 0;\n }\n\n public int Length\n {\n get => _pos;\n set\n {\n Debug.Assert(value >= 0);\n Debug.Assert(value <= _chars.Length);\n _pos = value;\n }\n }\n\n public int Capacity => _chars.Length;\n\n public void EnsureCapacity(int capacity)\n {\n // This is not expected to be called this with negative capacity\n Debug.Assert(capacity >= 0);\n\n // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.\n if ((uint)capacity > (uint)_chars.Length)\n Grow(capacity - _pos);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// Does not ensure there is a null char after \n /// This overload is pattern matched in the C# 7.3+ compiler so you can omit\n /// the explicit method call, and write eg \"fixed (char* c = builder)\"\n /// \n public ref char GetPinnableReference()\n {\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// \n /// Ensures that the builder has a null char after \n public ref char GetPinnableReference(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n public ref char this[int index]\n {\n get\n {\n Debug.Assert(index < _pos);\n return ref _chars[index];\n }\n }\n\n public override string ToString()\n {\n string s = _chars.Slice(0, _pos).ToString();\n Dispose();\n return s;\n }\n\n /// Returns the underlying storage of the builder.\n public Span RawChars => _chars;\n\n /// \n /// Returns a span around the contents of the builder.\n /// \n /// Ensures that the builder has a null char after \n public ReadOnlySpan AsSpan(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return _chars.Slice(0, _pos);\n }\n\n public ReadOnlySpan AsSpan() => _chars.Slice(0, _pos);\n public ReadOnlySpan AsSpan(int start) => _chars.Slice(start, _pos - start);\n public ReadOnlySpan AsSpan(int start, int length) => _chars.Slice(start, length);\n\n public bool TryCopyTo(Span destination, out int charsWritten)\n {\n if (_chars.Slice(0, _pos).TryCopyTo(destination))\n {\n charsWritten = _pos;\n Dispose();\n return true;\n }\n else\n {\n charsWritten = 0;\n Dispose();\n return false;\n }\n }\n\n public void Insert(int index, char value, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n _chars.Slice(index, count).Fill(value);\n _pos += count;\n }\n\n public void Insert(int index, string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int count = s.Length;\n\n if (_pos > (_chars.Length - count))\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(index));\n _pos += count;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(char c)\n {\n int pos = _pos;\n Span chars = _chars;\n if ((uint)pos < (uint)chars.Length)\n {\n chars[pos] = c;\n _pos = pos + 1;\n }\n else\n {\n GrowAndAppend(c);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int pos = _pos;\n if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.\n {\n _chars[pos] = s[0];\n _pos = pos + 1;\n }\n else\n {\n AppendSlow(s);\n }\n }\n\n private void AppendSlow(string s)\n {\n int pos = _pos;\n if (pos > _chars.Length - s.Length)\n {\n Grow(s.Length);\n }\n\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(pos));\n _pos += s.Length;\n }\n\n public void Append(char c, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n Span dst = _chars.Slice(_pos, count);\n for (int i = 0; i < dst.Length; i++)\n {\n dst[i] = c;\n }\n _pos += count;\n }\n\n public void Append(scoped ReadOnlySpan value)\n {\n int pos = _pos;\n if (pos > _chars.Length - value.Length)\n {\n Grow(value.Length);\n }\n\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public Span AppendSpan(int length)\n {\n int origPos = _pos;\n if (origPos > _chars.Length - length)\n {\n Grow(length);\n }\n\n _pos = origPos + length;\n return _chars.Slice(origPos, length);\n }\n\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowAndAppend(char c)\n {\n Grow(1);\n Append(c);\n }\n\n /// \n /// Resize the internal buffer either by doubling current buffer size or\n /// by adding to\n /// whichever is greater.\n /// \n /// \n /// Number of chars requested beyond current position.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void Grow(int additionalCapacityBeyondPos)\n {\n Debug.Assert(additionalCapacityBeyondPos > 0);\n Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, \"Grow called incorrectly, no resize is needed.\");\n\n const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength\n\n // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try\n // to double the size if possible, bounding the doubling to not go beyond the max array length.\n int newCapacity = (int)Math.Max(\n (uint)(_pos + additionalCapacityBeyondPos),\n Math.Min((uint)_chars.Length * 2, ArrayMaxLength));\n\n // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.\n // This could also go negative if the actual required length wraps around.\n char[] poolArray = ArrayPool.Shared.Rent(newCapacity);\n\n _chars.Slice(0, _pos).CopyTo(poolArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = poolArray;\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Dispose()\n {\n char[]? toReturn = _arrayToReturnToPool;\n this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestId.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC request identifier, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct RequestId : IEquatable\n{\n /// The id, either a string or a boxed long or null.\n private readonly object? _id;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(string value)\n {\n Throw.IfNull(value);\n _id = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(long value)\n {\n // Box the long. Request IDs are almost always strings in practice, so this should be rare.\n _id = value;\n }\n\n /// Gets the underlying object for this id.\n /// This will either be a , a boxed , or .\n public object? Id => _id;\n\n /// \n public override string ToString() =>\n _id is string stringValue ? stringValue :\n _id is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n string.Empty;\n\n /// \n public bool Equals(RequestId other) => Equals(_id, other._id);\n\n /// \n public override bool Equals(object? obj) => obj is RequestId other && Equals(other);\n\n /// \n public override int GetHashCode() => _id?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(RequestId left, RequestId right) => left.Equals(right);\n\n /// \n public static bool operator !=(RequestId left, RequestId right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override RequestId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"requestId must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, RequestId value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._id)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client,\n/// containing available resource templates.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover \n/// available resource templates on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resource templates.\n/// The server can provide the property to indicate there are more\n/// resource templates available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourceTemplatesResult : PaginatedResult\n{\n /// \n /// Gets or sets a list of resource templates that the server offers.\n /// \n /// \n /// This collection contains all the resource templates returned in the current page of results.\n /// Each provides metadata about resources available on the server,\n /// including URI templates, names, descriptions, and MIME types.\n /// \n [JsonPropertyName(\"resourceTemplates\")]\n public IList ResourceTemplates { get; set; } = [];\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/IdleTrackingBackgroundService.cs", "using System.Runtime.InteropServices;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed partial class IdleTrackingBackgroundService(\n StreamableHttpHandler handler,\n IOptions options,\n IHostApplicationLifetime appLifetime,\n ILogger logger) : BackgroundService\n{\n // The compiler will complain about the parameter being unused otherwise despite the source generator.\n private readonly ILogger _logger = logger;\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n // Still run loop given infinite IdleTimeout to enforce the MaxIdleSessionCount and assist graceful shutdown.\n if (options.Value.IdleTimeout != Timeout.InfiniteTimeSpan)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.IdleTimeout, TimeSpan.Zero);\n }\n\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.MaxIdleSessionCount, 0);\n\n try\n {\n var timeProvider = options.Value.TimeProvider;\n using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);\n\n var idleTimeoutTicks = options.Value.IdleTimeout.Ticks;\n var maxIdleSessionCount = options.Value.MaxIdleSessionCount;\n\n // Create two lists that will be reused between runs.\n // This assumes that the number of idle sessions is not breached frequently.\n // If the idle sessions often breach the maximum, a priority queue could be considered.\n var idleSessionsTimestamps = new List();\n var idleSessionSessionIds = new List();\n\n while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))\n {\n var idleActivityCutoff = idleTimeoutTicks switch\n {\n < 0 => long.MinValue,\n var ticks => timeProvider.GetTimestamp() - ticks,\n };\n\n foreach (var (_, session) in handler.Sessions)\n {\n if (session.IsActive || session.SessionClosed.IsCancellationRequested)\n {\n // There's a request currently active or the session is already being closed.\n continue;\n }\n\n if (session.LastActivityTicks < idleActivityCutoff)\n {\n RemoveAndCloseSession(session.Id);\n continue;\n }\n\n // Add the timestamp and the session\n idleSessionsTimestamps.Add(session.LastActivityTicks);\n idleSessionSessionIds.Add(session.Id);\n\n // Emit critical log at most once every 5 seconds the idle count it exceeded,\n // since the IdleTimeout will no longer be respected.\n if (idleSessionsTimestamps.Count == maxIdleSessionCount + 1)\n {\n LogMaxSessionIdleCountExceeded(maxIdleSessionCount);\n }\n }\n\n if (idleSessionsTimestamps.Count > maxIdleSessionCount)\n {\n var timestamps = CollectionsMarshal.AsSpan(idleSessionsTimestamps);\n\n // Sort only if the maximum is breached and sort solely by the timestamp. Sort both collections.\n timestamps.Sort(CollectionsMarshal.AsSpan(idleSessionSessionIds));\n\n var sessionsToPrune = CollectionsMarshal.AsSpan(idleSessionSessionIds)[..^maxIdleSessionCount];\n foreach (var id in sessionsToPrune)\n {\n RemoveAndCloseSession(id);\n }\n }\n\n idleSessionsTimestamps.Clear();\n idleSessionSessionIds.Clear();\n }\n }\n catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)\n {\n }\n finally\n {\n try\n {\n List disposeSessionTasks = [];\n\n foreach (var (sessionKey, _) in handler.Sessions)\n {\n if (handler.Sessions.TryRemove(sessionKey, out var session))\n {\n disposeSessionTasks.Add(DisposeSessionAsync(session));\n }\n }\n\n await Task.WhenAll(disposeSessionTasks);\n }\n finally\n {\n if (!stoppingToken.IsCancellationRequested)\n {\n // Something went terribly wrong. A very unexpected exception must be bubbling up, but let's ensure we also stop the application,\n // so that it hopefully gets looked at and restarted. This shouldn't really be reachable.\n appLifetime.StopApplication();\n IdleTrackingBackgroundServiceStoppedUnexpectedly();\n }\n }\n }\n }\n\n private void RemoveAndCloseSession(string sessionId)\n {\n if (!handler.Sessions.TryRemove(sessionId, out var session))\n {\n return;\n }\n\n LogSessionIdle(session.Id);\n // Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown.\n _ = DisposeSessionAsync(session);\n }\n\n private async Task DisposeSessionAsync(HttpMcpSession session)\n {\n try\n {\n await session.DisposeAsync();\n }\n catch (Exception ex)\n {\n LogSessionDisposeError(session.Id, ex);\n }\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Closing idle session {sessionId}.\")]\n private partial void LogSessionIdle(string sessionId);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"Error disposing session {sessionId}.\")]\n private partial void LogSessionDisposeError(string sessionId, Exception ex);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"Exceeded maximum of {maxIdleSessionCount} idle sessions. Now closing sessions active more recently than configured IdleTimeout.\")]\n private partial void LogMaxSessionIdleCountExceeded(int maxIdleSessionCount);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"The IdleTrackingBackgroundService has stopped unexpectedly.\")]\n private partial void IdleTrackingBackgroundServiceStoppedUnexpectedly();\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.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/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/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/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/Authentication/AuthenticatingMcpHttpClient.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Net.Http.Headers;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// A delegating handler that adds authentication tokens to requests and handles 401 responses.\n/// \ninternal sealed class AuthenticatingMcpHttpClient(HttpClient httpClient, ClientOAuthProvider credentialProvider) : McpHttpClient(httpClient)\n{\n // Select first supported scheme as the default\n private string _currentScheme = credentialProvider.SupportedSchemes.FirstOrDefault() ??\n throw new ArgumentException(\"Authorization provider must support at least one authentication scheme.\", nameof(credentialProvider));\n\n /// \n /// Sends an HTTP request with authentication handling.\n /// \n internal override async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (request.Headers.Authorization == null)\n {\n await AddAuthorizationHeaderAsync(request, _currentScheme, cancellationToken).ConfigureAwait(false);\n }\n\n var response = await base.SendAsync(request, message, cancellationToken).ConfigureAwait(false);\n\n if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)\n {\n return await HandleUnauthorizedResponseAsync(request, message, response, cancellationToken).ConfigureAwait(false);\n }\n\n return response;\n }\n\n /// \n /// Handles a 401 Unauthorized response by attempting to authenticate and retry the request.\n /// \n private async Task HandleUnauthorizedResponseAsync(\n HttpRequestMessage originalRequest,\n JsonRpcMessage? originalJsonRpcMessage,\n HttpResponseMessage response,\n CancellationToken cancellationToken)\n {\n // Gather the schemes the server wants us to use from WWW-Authenticate headers\n var serverSchemes = ExtractServerSupportedSchemes(response);\n\n if (!serverSchemes.Contains(_currentScheme))\n {\n // Find the first server scheme that's in our supported set\n var bestSchemeMatch = serverSchemes.Intersect(credentialProvider.SupportedSchemes, StringComparer.OrdinalIgnoreCase).FirstOrDefault();\n\n if (bestSchemeMatch is not null)\n {\n _currentScheme = bestSchemeMatch;\n }\n else if (serverSchemes.Count > 0)\n {\n // If no match was found, either throw an exception or use default\n throw new McpException(\n $\"The server does not support any of the provided authentication schemes.\" +\n $\"Server supports: [{string.Join(\", \", serverSchemes)}], \" +\n $\"Provider supports: [{string.Join(\", \", credentialProvider.SupportedSchemes)}].\");\n }\n }\n\n // Try to handle the 401 response with the selected scheme\n await credentialProvider.HandleUnauthorizedResponseAsync(_currentScheme, response, cancellationToken).ConfigureAwait(false);\n\n using var retryRequest = new HttpRequestMessage(originalRequest.Method, originalRequest.RequestUri);\n\n // Copy headers except Authorization which we'll set separately\n foreach (var header in originalRequest.Headers)\n {\n if (!header.Key.Equals(\"Authorization\", StringComparison.OrdinalIgnoreCase))\n {\n retryRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);\n }\n }\n\n await AddAuthorizationHeaderAsync(retryRequest, _currentScheme, cancellationToken).ConfigureAwait(false);\n return await base.SendAsync(retryRequest, originalJsonRpcMessage, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Extracts the authentication schemes that the server supports from the WWW-Authenticate headers.\n /// \n private static HashSet ExtractServerSupportedSchemes(HttpResponseMessage response)\n {\n var serverSchemes = new HashSet(StringComparer.OrdinalIgnoreCase);\n\n foreach (var header in response.Headers.WwwAuthenticate)\n {\n serverSchemes.Add(header.Scheme);\n }\n\n return serverSchemes;\n }\n\n /// \n /// Adds an authorization header to the request.\n /// \n private async Task AddAuthorizationHeaderAsync(HttpRequestMessage request, string scheme, CancellationToken cancellationToken)\n {\n if (request.RequestUri is null)\n {\n return;\n }\n\n var token = await credentialProvider.GetCredentialAsync(scheme, request.RequestUri, cancellationToken).ConfigureAwait(false);\n if (string.IsNullOrEmpty(token))\n {\n return;\n }\n\n request.Headers.Authorization = new AuthenticationHeaderValue(scheme, token);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Resource.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource that the server is capable of reading.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Resource : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource. Clients can use this information to filter or prioritize resources for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Net.ServerSentEvents;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Handles processing the request/response body pairs for the Streamable HTTP transport.\n/// This is typically used via .\n/// \ninternal sealed class StreamableHttpPostTransport(StreamableHttpServerTransport parentTransport, IDuplexPipe httpBodies) : ITransport\n{\n private readonly SseWriter _sseWriter = new();\n private RequestId _pendingRequest;\n\n public ChannelReader MessageReader => throw new NotSupportedException(\"JsonRpcMessage.RelatedTransport should only be used for sending messages.\");\n\n string? ITransport.SessionId => parentTransport.SessionId;\n\n /// \n /// True, if data was written to the respond body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async ValueTask RunAsync(CancellationToken cancellationToken)\n {\n var message = await JsonSerializer.DeserializeAsync(httpBodies.Input.AsStream(),\n McpJsonUtilities.JsonContext.Default.JsonRpcMessage, cancellationToken).ConfigureAwait(false);\n await OnMessageReceivedAsync(message, cancellationToken).ConfigureAwait(false);\n\n if (_pendingRequest.Id is null)\n {\n return false;\n }\n\n _sseWriter.MessageFilter = StopOnFinalResponseFilter;\n await _sseWriter.WriteAllAsync(httpBodies.Output.AsStream(), cancellationToken).ConfigureAwait(false);\n return true;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (parentTransport.Stateless && message is JsonRpcRequest)\n {\n throw new InvalidOperationException(\"Server to client requests are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n private async IAsyncEnumerable> StopOnFinalResponseFilter(IAsyncEnumerable> messages, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n await foreach (var message in messages.WithCancellation(cancellationToken))\n {\n yield return message;\n\n if (message.Data is JsonRpcResponse or JsonRpcError && ((JsonRpcMessageWithId)message.Data).Id == _pendingRequest)\n {\n // Complete the SSE response stream now that all pending requests have been processed.\n break;\n }\n }\n }\n\n private async ValueTask OnMessageReceivedAsync(JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (message is null)\n {\n throw new InvalidOperationException(\"Received invalid null message.\");\n }\n\n if (message is JsonRpcRequest request)\n {\n _pendingRequest = request.Id;\n\n // Invoke the initialize request callback if applicable.\n if (parentTransport.OnInitRequestReceived is { } onInitRequest && request.Method == RequestMethods.Initialize)\n {\n var initializeRequest = JsonSerializer.Deserialize(request.Params, McpJsonUtilities.JsonContext.Default.InitializeRequestParams);\n await onInitRequest(initializeRequest).ConfigureAwait(false);\n }\n }\n\n message.RelatedTransport = this;\n\n if (parentTransport.FlowExecutionContextFromRequests)\n {\n message.ExecutionContext = ExecutionContext.Capture();\n }\n\n await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpSession.cs", "using ModelContextProtocol.AspNetCore.Stateless;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Security.Claims;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed class HttpMcpSession(\n string sessionId,\n TTransport transport,\n UserIdClaim? userId,\n TimeProvider timeProvider) : IAsyncDisposable\n where TTransport : ITransport\n{\n private int _referenceCount;\n private int _getRequestStarted;\n private CancellationTokenSource _disposeCts = new();\n\n public string Id { get; } = sessionId;\n public TTransport Transport { get; } = transport;\n public UserIdClaim? UserIdClaim { get; } = userId;\n\n public CancellationToken SessionClosed => _disposeCts.Token;\n\n public bool IsActive => !SessionClosed.IsCancellationRequested && _referenceCount > 0;\n public long LastActivityTicks { get; private set; } = timeProvider.GetTimestamp();\n\n private TimeProvider TimeProvider => timeProvider;\n\n public IMcpServer? Server { get; set; }\n public Task? ServerRunTask { get; set; }\n\n public IDisposable AcquireReference()\n {\n Interlocked.Increment(ref _referenceCount);\n return new UnreferenceDisposable(this);\n }\n\n public bool TryStartGetRequest() => Interlocked.Exchange(ref _getRequestStarted, 1) == 0;\n\n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n\n if (ServerRunTask is not null)\n {\n await ServerRunTask;\n }\n }\n catch (OperationCanceledException)\n {\n }\n finally\n {\n try\n {\n if (Server is not null)\n {\n await Server.DisposeAsync();\n }\n }\n finally\n {\n await Transport.DisposeAsync();\n _disposeCts.Dispose();\n }\n }\n }\n\n public bool HasSameUserId(ClaimsPrincipal user)\n => UserIdClaim == StreamableHttpHandler.GetUserIdClaim(user);\n\n private sealed class UnreferenceDisposable(HttpMcpSession session) : IDisposable\n {\n public void Dispose()\n {\n if (Interlocked.Decrement(ref session._referenceCount) == 0)\n {\n session.LastActivityTicks = session.TimeProvider.GetTimestamp();\n }\n }\n }\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.AspNetCore/Authentication/ResourceMetadataRequestContext.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Context for resource metadata request events.\n/// \npublic class ResourceMetadataRequestContext : HandleRequestContext\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The HTTP context.\n /// The authentication scheme.\n /// The authentication options.\n public ResourceMetadataRequestContext(\n HttpContext context,\n AuthenticationScheme scheme,\n McpAuthenticationOptions options)\n : base(context, scheme, options)\n {\n }\n\n /// \n /// Gets or sets the protected resource metadata for the current request.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\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/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/Protocol/ProgressNotificationParams.cs", "using Microsoft.Extensions.Logging.Abstractions;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an out-of-band notification used to inform the receiver of a progress update for a long-running request.\n/// \n/// \n/// See the schema for more details.\n/// \n[JsonConverter(typeof(Converter))]\npublic sealed class ProgressNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the progress token which was given in the initial request, used to associate this notification with \n /// the corresponding request.\n /// \n /// \n /// \n /// This token acts as a correlation identifier that links progress updates to their corresponding request.\n /// \n /// \n /// When an endpoint initiates a request with a in its metadata, \n /// the receiver can send progress notifications using this same token. This allows both sides to \n /// correlate the notifications with the original request.\n /// \n /// \n public required ProgressToken ProgressToken { get; init; }\n\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// This should increase for each notification issued as part of the same request, even if the total is unknown.\n /// \n public required ProgressNotificationValue Progress { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressNotificationParams? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n ProgressToken? progressToken = null;\n float? progress = null;\n float? total = null;\n string? message = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType == JsonTokenType.PropertyName)\n {\n var propertyName = reader.GetString();\n reader.Read();\n switch (propertyName)\n {\n case \"progressToken\":\n progressToken = (ProgressToken)JsonSerializer.Deserialize(ref reader, options.GetTypeInfo(typeof(ProgressToken)))!;\n break;\n\n case \"progress\":\n progress = reader.GetSingle();\n break;\n\n case \"total\":\n total = reader.GetSingle();\n break;\n\n case \"message\":\n message = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n }\n }\n }\n\n if (progress is null)\n {\n throw new JsonException(\"Missing required property 'progress'.\");\n }\n\n if (progressToken is null)\n {\n throw new JsonException(\"Missing required property 'progressToken'.\");\n }\n\n return new ProgressNotificationParams\n {\n ProgressToken = progressToken.GetValueOrDefault(),\n Progress = new ProgressNotificationValue\n {\n Progress = progress.GetValueOrDefault(),\n Total = total,\n Message = message,\n },\n Meta = meta,\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressNotificationParams value, JsonSerializerOptions options)\n {\n writer.WriteStartObject();\n\n writer.WritePropertyName(\"progressToken\");\n JsonSerializer.Serialize(writer, value.ProgressToken, options.GetTypeInfo(typeof(ProgressToken)));\n\n writer.WriteNumber(\"progress\", value.Progress.Progress);\n\n if (value.Progress.Total is { } total)\n {\n writer.WriteNumber(\"total\", total);\n }\n\n if (value.Progress.Message is { } message)\n {\n writer.WriteString(\"message\", message);\n }\n\n if (value.Meta is { } meta)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ProgressToken.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a progress token, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct ProgressToken : IEquatable\n{\n /// The token, either a string or a boxed long or null.\n private readonly object? _token;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(string value)\n {\n Throw.IfNull(value);\n _token = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(long value)\n {\n // Box the long. Progress tokens are almost always strings in practice, so this should be rare.\n _token = value;\n }\n\n /// Gets the underlying object for this token.\n /// This will either be a , a boxed , or .\n public object? Token => _token;\n\n /// \n public override string? ToString() =>\n _token is string stringValue ? stringValue :\n _token is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n null;\n\n /// \n public bool Equals(ProgressToken other) => Equals(_token, other._token);\n\n /// \n public override bool Equals(object? obj) => obj is ProgressToken other && Equals(other);\n\n /// \n public override int GetHashCode() => _token?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(ProgressToken left, ProgressToken right) => left.Equals(right);\n\n /// \n public static bool operator !=(ProgressToken left, ProgressToken right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"progressToken must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressToken value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._token)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/samples/EverythingServer/LoggingUpdateMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace EverythingServer;\n\npublic class LoggingUpdateMessageSender(IMcpServer server, Func getMinLevel) : BackgroundService\n{\n readonly Dictionary _loggingLevelMap = new()\n {\n { LoggingLevel.Debug, \"Debug-level message\" },\n { LoggingLevel.Info, \"Info-level message\" },\n { LoggingLevel.Notice, \"Notice-level message\" },\n { LoggingLevel.Warning, \"Warning-level message\" },\n { LoggingLevel.Error, \"Error-level message\" },\n { LoggingLevel.Critical, \"Critical-level message\" },\n { LoggingLevel.Alert, \"Alert-level message\" },\n { LoggingLevel.Emergency, \"Emergency-level message\" }\n };\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n var newLevel = (LoggingLevel)Random.Shared.Next(_loggingLevelMap.Count);\n\n var message = new\n {\n Level = newLevel.ToString().ToLower(),\n Data = _loggingLevelMap[newLevel],\n };\n\n if (newLevel > getMinLevel())\n {\n await server.SendNotificationAsync(\"notifications/message\", message, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(15000, stoppingToken);\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ProtectedResourceMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the resource metadata for OAuth authorization as defined in RFC 9396.\n/// Defined by RFC 9728.\n/// \npublic sealed class ProtectedResourceMetadata\n{\n /// \n /// The resource URI.\n /// \n /// \n /// REQUIRED. The protected resource's resource identifier.\n /// \n [JsonPropertyName(\"resource\")]\n public required Uri Resource { get; set; }\n\n /// \n /// The list of authorization server URIs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of OAuth authorization server issuer identifiers\n /// for authorization servers that can be used with this protected resource.\n /// \n [JsonPropertyName(\"authorization_servers\")]\n public List AuthorizationServers { get; set; } = [];\n\n /// \n /// The supported bearer token methods.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the supported methods of sending an OAuth 2.0 bearer token\n /// to the protected resource. Defined values are [\"header\", \"body\", \"query\"].\n /// \n [JsonPropertyName(\"bearer_methods_supported\")]\n public List BearerMethodsSupported { get; set; } = [\"header\"];\n\n /// \n /// The supported scopes.\n /// \n /// \n /// RECOMMENDED. JSON array containing a list of scope values that are used in authorization\n /// requests to request access to this protected resource.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List ScopesSupported { get; set; } = [];\n\n /// \n /// URL of the protected resource's JSON Web Key (JWK) Set document.\n /// \n /// \n /// OPTIONAL. This contains public keys belonging to the protected resource, such as signing key(s)\n /// that the resource server uses to sign resource responses. This URL MUST use the https scheme.\n /// \n [JsonPropertyName(\"jwks_uri\")]\n public Uri? JwksUri { get; set; }\n\n /// \n /// List of the JWS signing algorithms supported by the protected resource for signing resource responses.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS signing algorithms (alg values) supported by the protected resource\n /// for signing resource responses. No default algorithms are implied if this entry is omitted. The value none MUST NOT be used.\n /// \n [JsonPropertyName(\"resource_signing_alg_values_supported\")]\n public List? ResourceSigningAlgValuesSupported { get; set; }\n\n /// \n /// Human-readable name of the protected resource intended for display to the end user.\n /// \n /// \n /// RECOMMENDED. It is recommended that protected resource metadata include this field.\n /// The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_name\")]\n public string? ResourceName { get; set; }\n\n /// \n /// The URI to the resource documentation.\n /// \n /// \n /// OPTIONAL. URL of a page containing human-readable information that developers might want or need to know\n /// when using the protected resource.\n /// \n [JsonPropertyName(\"resource_documentation\")]\n public Uri? ResourceDocumentation { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's requirements.\n /// \n /// \n /// OPTIONAL. Information about how the client can use the data provided by the protected resource.\n /// \n [JsonPropertyName(\"resource_policy_uri\")]\n public Uri? ResourcePolicyUri { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's terms of service.\n /// \n /// \n /// OPTIONAL. The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_tos_uri\")]\n public Uri? ResourceTosUri { get; set; }\n\n /// \n /// Boolean value indicating protected resource support for mutual-TLS client certificate-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"tls_client_certificate_bound_access_tokens\")]\n public bool? TlsClientCertificateBoundAccessTokens { get; set; }\n\n /// \n /// List of the authorization details type values supported by the resource server.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the authorization details type values supported by the resource server\n /// when the authorization_details request parameter is used.\n /// \n [JsonPropertyName(\"authorization_details_types_supported\")]\n public List? AuthorizationDetailsTypesSupported { get; set; }\n\n /// \n /// List of the JWS algorithm values supported by the resource server for validating DPoP proof JWTs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS alg values supported by the resource server\n /// for validating Demonstrating Proof of Possession (DPoP) proof JWTs.\n /// \n [JsonPropertyName(\"dpop_signing_alg_values_supported\")]\n public List? DpopSigningAlgValuesSupported { get; set; }\n\n /// \n /// Boolean value specifying whether the protected resource always requires the use of DPoP-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"dpop_bound_access_tokens_required\")]\n public bool? DpopBoundAccessTokensRequired { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a resource provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting resource data.\n/// See the schema for details.\n/// \npublic sealed class ReadResourceRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/McpEndpointRouteBuilderExtensions.cs", "using Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Metadata;\nusing Microsoft.AspNetCore.Routing;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.AspNetCore.Builder;\n\n/// \n/// Provides extension methods for to add MCP endpoints.\n/// \npublic static class McpEndpointRouteBuilderExtensions\n{\n /// \n /// Sets up endpoints for handling MCP Streamable HTTP transport.\n /// See the 2025-06-18 protocol specification for details about the Streamable HTTP transport.\n /// Also maps legacy SSE endpoints for backward compatibility at the path \"/sse\" and \"/message\". the 2024-11-05 protocol specification for details about the HTTP with SSE transport.\n /// \n /// The web application to attach MCP HTTP endpoints.\n /// The route pattern prefix to map to.\n /// Returns a builder for configuring additional endpoint conventions like authorization policies.\n public static IEndpointConventionBuilder MapMcp(this IEndpointRouteBuilder endpoints, [StringSyntax(\"Route\")] string pattern = \"\")\n {\n var streamableHttpHandler = endpoints.ServiceProvider.GetService() ??\n throw new InvalidOperationException(\"You must call WithHttpTransport(). Unable to find required services. Call builder.Services.AddMcpServer().WithHttpTransport() in application startup code.\");\n\n var mcpGroup = endpoints.MapGroup(pattern);\n var streamableHttpGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP Streamable HTTP | {b.DisplayName}\")\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status404NotFound, typeof(JsonRpcError), contentTypes: [\"application/json\"]));\n\n streamableHttpGroup.MapPost(\"\", streamableHttpHandler.HandlePostRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n\n if (!streamableHttpHandler.HttpServerTransportOptions.Stateless)\n {\n // The GET and DELETE endpoints are not mapped in Stateless mode since there's no way to send unsolicited messages\n // for the GET to handle, and there is no server-side state for the DELETE to clean up.\n streamableHttpGroup.MapGet(\"\", streamableHttpHandler.HandleGetRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n streamableHttpGroup.MapDelete(\"\", streamableHttpHandler.HandleDeleteRequestAsync);\n\n // Map legacy HTTP with SSE endpoints only if not in Stateless mode, because we cannot guarantee the /message requests\n // will be handled by the same process as the /sse request.\n var sseHandler = endpoints.ServiceProvider.GetRequiredService();\n var sseGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP HTTP with SSE | {b.DisplayName}\");\n\n sseGroup.MapGet(\"/sse\", sseHandler.HandleSseRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n sseGroup.MapPost(\"/message\", sseHandler.HandleMessageRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n }\n\n return mcpGroup;\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/dd75c45c123055baacd7aa4418f425f412797a29/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs\n// and then modified to build on netstandard2.0.\n\n#if !NET\nusing System.Buffers;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Provides a handler used by the language compiler to process interpolated strings into instances.\n internal ref struct DefaultInterpolatedStringHandler\n {\n // Implementation note:\n // As this type lives in CompilerServices and is only intended to be targeted by the compiler,\n // public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input\n // when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException.\n\n /// Expected average length of formatted data used for an individual interpolation expression result.\n /// \n /// This is inherited from string.Format, and could be changed based on further data.\n /// string.Format actually uses `format.Length + args.Length * 8`, but format.Length\n /// includes the format items themselves, e.g. \"{0}\", and since it's rare to have double-digit\n /// numbers of items, we bump the 8 up to 11 to account for the three extra characters in \"{d}\",\n /// since the compiler-provided base length won't include the equivalent character count.\n /// \n private const int GuessedLengthPerHole = 11;\n /// Minimum size array to rent from the pool.\n /// Same as stack-allocation size used today by string.Format.\n private const int MinimumArrayPoolLength = 256;\n\n /// Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.\n private readonly IFormatProvider? _provider;\n /// Array rented from the array pool and used to back .\n private char[]? _arrayToReturnToPool;\n /// The span to write into.\n private Span _chars;\n /// Position at which to write the next character.\n private int _pos;\n /// Whether provides an ICustomFormatter.\n /// \n /// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive\n /// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field\n /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider\n /// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a\n /// formatter, we pay for the extra interface call on each AppendFormatted that needs it.\n /// \n private readonly bool _hasCustomFormatter;\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)\n {\n _provider = null;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = false;\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)\n {\n _provider = provider;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer)\n {\n _provider = provider;\n _chars = initialBuffer;\n _arrayToReturnToPool = null;\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Derives a default length with which to seed the handler.\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant\n internal static int GetDefaultLength(int literalLength, int formattedCount) =>\n Math.Max(MinimumArrayPoolLength, literalLength + (formattedCount * GuessedLengthPerHole));\n\n /// Gets the built .\n /// The built string.\n public override string ToString() => Text.ToString();\n\n /// Gets the built and clears the handler.\n /// The built string.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after\n /// is called on any one of them.\n /// \n public string ToStringAndClear()\n {\n string result = Text.ToString();\n Clear();\n return result;\n }\n\n /// Clears the handler.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after \n /// is called on any one of them.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Clear()\n {\n char[]? toReturn = _arrayToReturnToPool;\n\n // Defensive clear\n _arrayToReturnToPool = null;\n _chars = default;\n _pos = 0;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n /// Gets a span of the characters appended to the handler.\n public ReadOnlySpan Text => _chars.Slice(0, _pos);\n\n /// Writes the specified string to the handler.\n /// The string to write.\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void AppendLiteral(string value)\n {\n if (value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopyString(value);\n }\n }\n\n #region AppendFormatted\n // Design note:\n // The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression;\n // if it can't find an appropriate overload, for handlers in general it'll simply fail to compile.\n // (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to\n // its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case,\n // interpolated strings will still work, but it has the downside that a developer generally won't know\n // if the fallback is happening and they're paying more.)\n //\n // At a minimum, then, we would need an overload that accepts:\n // (object value, int alignment = 0, string? format = null)\n // Such an overload would provide the same expressiveness as string.Format. However, this has several\n // shortcomings:\n // - Every value type in an interpolation expression would be boxed.\n // - ReadOnlySpan could not be used in interpolation expressions.\n // - Every AppendFormatted call would have three arguments at the call site, bloating the IL further.\n // - Every invocation would be more expensive, due to lack of specialization, every call needing to account\n // for alignment and format, etc.\n //\n // To address that, we could just have overloads for T and ReadOnlySpan:\n // (T)\n // (T, int alignment)\n // (T, string? format)\n // (T, int alignment, string? format)\n // (ReadOnlySpan)\n // (ReadOnlySpan, int alignment)\n // (ReadOnlySpan, string? format)\n // (ReadOnlySpan, int alignment, string? format)\n // but this also has shortcomings:\n // - Some expressions that would have worked with an object overload will now force a fallback to string.Format\n // (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler\n // can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully\n // be passed as an argument of type `object` but not of type `T`.\n // - Reference types get no benefit from going through the generic code paths, and actually incur some overheads\n // from doing so.\n // - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate\n // at compile time for value types but don't (currently) if the Nullable goes through the same code paths\n // (see https://github.com/dotnet/runtime/issues/50915).\n //\n // We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common handler\n // and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads for each of:\n // (T, ...) where T : struct\n // (T?, ...) where T : struct\n // (object, ...)\n // (ReadOnlySpan, ...)\n // (string, ...)\n // but this also has shortcomings, most importantly:\n // - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object overload.\n // This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, so without those\n // they'd all map to the object overloads as well.\n // - Any reference type with an implicit cast to ROS will fail to compile due to ambiguities between the overloads. string\n // is one such type, hence needing dedicated overloads for it that can be bound to more tightly.\n //\n // A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, would be the set:\n // (T, ...) with no constraint\n // (ReadOnlySpan) and (ReadOnlySpan, int)\n // (object, int alignment = 0, string? format = null)\n // (string) and (string, int)\n // This would address most of the concerns, at the expense of:\n // - Most reference types going through the generic code paths and so being a bit more expensive.\n // - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed.\n // We could choose to add a T? where T : struct set of overloads if necessary.\n // Strings don't require their own overloads here, but as they're expected to be very common and as we can\n // optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't\n // need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them.\n //\n // Hole values are formatted according to the following policy:\n // 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if the value is null).\n // 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat.\n // 3. If the type implements IFormattable, use IFormattable.ToString.\n // 4. Otherwise, use object.ToString.\n // This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this doesn't\n // apply is ReadOnlySpan, which isn't supported by either string.Format nor StringBuilder.AppendFormat, but more\n // importantly which can't be boxed to be passed to ICustomFormatter.Format.\n\n #region AppendFormatted T\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The type of the value to write.\n public void AppendFormatted(T value)\n {\n // This method could delegate to AppendFormatted with a null format, but explicitly passing\n // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined,\n // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format.\n\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n return;\n }\n\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n public void AppendFormatted(T value, string? format)\n {\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format);\n return;\n }\n\n // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter\n // requires the former. For value types, it won't matter as the type checks devolve into\n // JIT-time constants. For reference types, they're more likely to implement IFormattable\n // than they are to implement ISpanFormattable: if they don't implement either, we save an\n // interface check over first checking for ISpanFormattable and then for IFormattable, and\n // if it only implements IFormattable, we come out even: only if it implements both do we\n // end up paying for an extra interface check.\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment)\n {\n int startingPos = _pos;\n AppendFormatted(value);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment, string? format)\n {\n int startingPos = _pos;\n AppendFormatted(value, format);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n #endregion\n\n #region AppendFormatted ReadOnlySpan\n /// Writes the specified character span to the handler.\n /// The span to write.\n public void AppendFormatted(scoped ReadOnlySpan value)\n {\n // Fast path for when the value fits in the current buffer\n if (value.TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopySpan(value);\n }\n }\n\n /// Writes the specified string of chars to the handler.\n /// The span to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(scoped ReadOnlySpan value, int alignment = 0, string? format = null)\n {\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingRequired = alignment - value.Length;\n if (paddingRequired <= 0)\n {\n // The value is as large or larger than the required amount of padding,\n // so just write the value.\n AppendFormatted(value);\n return;\n }\n\n // Write the value along with the appropriate padding.\n EnsureCapacityForAdditionalChars(value.Length + paddingRequired);\n if (leftAlign)\n {\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n }\n else\n {\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n #endregion\n\n #region AppendFormatted string\n /// Writes the specified value to the handler.\n /// The value to write.\n public void AppendFormatted(string? value)\n {\n // Fast-path for no custom formatter and a non-null string that fits in the current destination buffer.\n if (!_hasCustomFormatter &&\n value is not null &&\n value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n AppendFormattedSlow(value);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// \n /// Slow path to handle a custom formatter, potentially null value,\n /// or a string that doesn't fit in the current buffer.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendFormattedSlow(string? value)\n {\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n }\n else if (value is not null)\n {\n EnsureCapacityForAdditionalChars(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>\n // Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload\n // simply to disambiguate between ROS and object, just in case someone does specify a format, as\n // string is implicitly convertible to both. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n\n #region AppendFormatted object\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>\n // This overload is expected to be used rarely, only if either a) something strongly typed as object is\n // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It\n // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n #endregion\n\n /// Gets whether the provider provides a custom formatter.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites\n internal static bool HasCustomFormatter(IFormatProvider provider)\n {\n Debug.Assert(provider is not null);\n Debug.Assert(provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, \"Expected CultureInfo to not provide a custom formatter\");\n return\n provider!.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case\n provider.GetFormat(typeof(ICustomFormatter)) != null;\n }\n\n /// Formats the value using the custom formatter from the provider.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendCustomFormatter(T value, string? format)\n {\n // This case is very rare, but we need to handle it prior to the other checks in case\n // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.\n // We do the cast here rather than in the ctor, even though this could be executed multiple times per\n // formatting, to make the cast pay for play.\n Debug.Assert(_hasCustomFormatter);\n Debug.Assert(_provider != null);\n\n ICustomFormatter? formatter = (ICustomFormatter?)_provider!.GetFormat(typeof(ICustomFormatter));\n Debug.Assert(formatter != null, \"An incorrectly written provider said it implemented ICustomFormatter, and then didn't\");\n\n if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted)\n {\n AppendLiteral(customFormatted);\n }\n }\n\n /// Handles adding any padding required for aligning a formatted value in an interpolation expression.\n /// The position at which the written value started.\n /// Non-zero minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)\n {\n Debug.Assert(startingPos >= 0 && startingPos <= _pos);\n Debug.Assert(alignment != 0);\n\n int charsWritten = _pos - startingPos;\n\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingNeeded = alignment - charsWritten;\n if (paddingNeeded > 0)\n {\n EnsureCapacityForAdditionalChars(paddingNeeded);\n\n if (leftAlign)\n {\n _chars.Slice(_pos, paddingNeeded).Fill(' ');\n }\n else\n {\n _chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded));\n _chars.Slice(startingPos, paddingNeeded).Fill(' ');\n }\n\n _pos += paddingNeeded;\n }\n }\n\n /// Ensures has the capacity to store beyond .\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void EnsureCapacityForAdditionalChars(int additionalChars)\n {\n if (_chars.Length - _pos < additionalChars)\n {\n Grow(additionalChars);\n }\n }\n\n /// Fallback for fast path in when there's not enough space in the destination.\n /// The string to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopyString(string value)\n {\n Grow(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Fallback for for when not enough space exists in the current buffer.\n /// The span to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopySpan(scoped ReadOnlySpan value)\n {\n Grow(value.Length);\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Grows to have the capacity to store at least beyond .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow(int additionalChars)\n {\n // This method is called when the remaining space (_chars.Length - _pos) is\n // insufficient to store a specific number of additional characters. Thus, we\n // need to grow to at least that new total. GrowCore will handle growing by more\n // than that if possible.\n Debug.Assert(additionalChars > _chars.Length - _pos);\n GrowCore((uint)_pos + (uint)additionalChars);\n }\n\n /// Grows the size of .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow()\n {\n // This method is called when the remaining space in _chars isn't sufficient to continue\n // the operation. Thus, we need at least one character beyond _chars.Length. GrowCore\n // will handle growing by more than that if possible.\n GrowCore((uint)_chars.Length + 1);\n }\n\n /// Grow the size of to at least the specified .\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines\n private void GrowCore(uint requiredMinCapacity)\n {\n // We want the max of how much space we actually required and doubling our capacity (without going beyond the max allowed length). We\n // also want to avoid asking for small arrays, to reduce the number of times we need to grow, and since we're working with unsigned\n // ints that could technically overflow if someone tried to, for example, append a huge string to a huge string, we also clamp to int.MaxValue.\n // Even if the array creation fails in such a case, we may later fail in ToStringAndClear.\n\n const int StringMaxLength = 0x3FFFFFDF;\n uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, StringMaxLength));\n int arraySize = (int)Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue);\n\n char[] newArray = ArrayPool.Shared.Rent(arraySize);\n _chars.Slice(0, _pos).CopyTo(newArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = newArray;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n private static uint Clamp(uint value, uint min, uint max)\n {\n Debug.Assert(min <= max);\n\n if (value < min)\n {\n return min;\n }\n else if (value > max)\n {\n return max;\n }\n\n return value;\n }\n }\n}\n#endif"], ["/csharp-sdk/samples/EverythingServer/Prompts/SimplePromptType.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class SimplePromptType\n{\n [McpServerPrompt(Name = \"simple_prompt\"), Description(\"A prompt without arguments\")]\n public static string SimplePrompt() => \"This is a simple prompt without arguments\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientSessionTransport.cs", "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 protected override async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)\n {\n // Only clean up once.\n if (Interlocked.Exchange(ref _cleanedUp, 1) != 0)\n {\n return;\n }\n\n // We've not yet forcefully terminated the server. If it's already shut down, something went wrong,\n // so create an exception with details about that.\n error ??= await GetUnexpectedExitExceptionAsync(cancellationToken).ConfigureAwait(false);\n\n // Now terminate the server process.\n try\n {\n StdioClientTransport.DisposeProcess(_process, processRunning: true, _options.ShutdownTimeout, Name);\n }\n catch (Exception ex)\n {\n LogTransportShutdownFailed(Name, ex);\n }\n\n // And handle cleanup in the base type.\n await base.CleanupAsync(error, cancellationToken);\n }\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"], ["/csharp-sdk/src/Common/Polyfills/System/PasteArguments.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/d2650b6ae7023a2d9d2c74c56116f1f18472ab04/src/libraries/System.Private.CoreLib/src/System/PasteArguments.cs\n// and changed from using ValueStringBuilder to StringBuilder.\n\n#if !NET\nusing System.Text;\n\nnamespace System;\n\ninternal static partial class PasteArguments\n{\n internal static void AppendArgument(StringBuilder stringBuilder, string argument)\n {\n if (stringBuilder.Length != 0)\n {\n stringBuilder.Append(' ');\n }\n\n // Parsing rules for non-argv[0] arguments:\n // - Backslash is a normal character except followed by a quote.\n // - 2N backslashes followed by a quote ==> N literal backslashes followed by unescaped quote\n // - 2N+1 backslashes followed by a quote ==> N literal backslashes followed by a literal quote\n // - Parsing stops at first whitespace outside of quoted region.\n // - (post 2008 rule): A closing quote followed by another quote ==> literal quote, and parsing remains in quoting mode.\n if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument))\n {\n // Simple case - no quoting or changes needed.\n stringBuilder.Append(argument);\n }\n else\n {\n stringBuilder.Append(Quote);\n int idx = 0;\n while (idx < argument.Length)\n {\n char c = argument[idx++];\n if (c == Backslash)\n {\n int numBackSlash = 1;\n while (idx < argument.Length && argument[idx] == Backslash)\n {\n idx++;\n numBackSlash++;\n }\n\n if (idx == argument.Length)\n {\n // We'll emit an end quote after this so must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2);\n }\n else if (argument[idx] == Quote)\n {\n // Backslashes will be followed by a quote. Must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2 + 1);\n stringBuilder.Append(Quote);\n idx++;\n }\n else\n {\n // Backslash will not be followed by a quote, so emit as normal characters.\n stringBuilder.Append(Backslash, numBackSlash);\n }\n\n continue;\n }\n\n if (c == Quote)\n {\n // Escape the quote so it appears as a literal. This also guarantees that we won't end up generating a closing quote followed\n // by another quote (which parses differently pre-2008 vs. post-2008.)\n stringBuilder.Append(Backslash);\n stringBuilder.Append(Quote);\n continue;\n }\n\n stringBuilder.Append(c);\n }\n\n stringBuilder.Append(Quote);\n }\n }\n\n private static bool ContainsNoWhitespaceOrQuotes(string s)\n {\n for (int i = 0; i < s.Length; i++)\n {\n char c = s[i];\n if (char.IsWhiteSpace(c) || c == Quote)\n {\n return false;\n }\n }\n\n return true;\n }\n\n private const char Quote = '\\\"';\n private const char Backslash = '\\\\';\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StdioServerTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implemented via \"stdio\" (standard input/output).\n/// \npublic sealed class StdioServerTransport : StreamServerTransport\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The server options.\n /// Optional logger factory used for logging employed by the transport.\n /// is or contains a null name.\n public StdioServerTransport(McpServerOptions serverOptions, ILoggerFactory? loggerFactory = null)\n : this(GetServerName(serverOptions), loggerFactory: loggerFactory)\n {\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the server.\n /// Optional logger factory used for logging employed by the transport.\n /// is .\n public StdioServerTransport(string serverName, ILoggerFactory? loggerFactory = null)\n : base(new CancellableStdinStream(Console.OpenStandardInput()),\n new BufferedStream(Console.OpenStandardOutput()),\n serverName ?? throw new ArgumentNullException(nameof(serverName)),\n loggerFactory)\n {\n }\n\n private static string GetServerName(McpServerOptions serverOptions)\n {\n Throw.IfNull(serverOptions);\n\n return serverOptions.ServerInfo?.Name ?? McpServer.DefaultImplementation.Name;\n }\n\n // Neither WindowsConsoleStream nor UnixConsoleStream respect CancellationTokens or cancel any I/O on Dispose.\n // WindowsConsoleStream will return an EOS on Ctrl-C, but that is not the only reason the shutdownToken may fire.\n private sealed class CancellableStdinStream(Stream stdinStream) : Stream\n {\n public override bool CanRead => true;\n public override bool CanSeek => false;\n public override bool CanWrite => false;\n\n public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n => stdinStream.ReadAsync(buffer, offset, count, cancellationToken).WaitAsync(cancellationToken);\n\n#if NET\n public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)\n {\n ValueTask vt = stdinStream.ReadAsync(buffer, cancellationToken);\n return vt.IsCompletedSuccessfully ? vt : new(vt.AsTask().WaitAsync(cancellationToken));\n }\n#endif\n\n // The McpServer shouldn't call flush on the stdin Stream, but it doesn't need to throw just in case.\n public override void Flush() { }\n\n public override long Length => throw new NotSupportedException();\n\n public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }\n\n public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();\n\n public override void SetLength(long value) => throw new NotSupportedException();\n public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/CustomizableJsonStringEnumConverter.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.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\n#if !NET9_0_OR_GREATER\nusing System.Reflection;\n#endif\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n#if !NET9_0_OR_GREATER\nusing ModelContextProtocol;\n#endif\n\n// NOTE:\n// This is a workaround for lack of System.Text.Json's JsonStringEnumConverter\n// 9.x support for JsonStringEnumMemberNameAttribute. Once all builds use the System.Text.Json 9.x\n// version, this whole file can be removed. Note that the type is public so that external source\n// generators can use it, so removing it is a potential breaking change.\n\nnamespace ModelContextProtocol\n{\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// The enum type to convert.\n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class CustomizableJsonStringEnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum> :\n JsonStringEnumConverter where TEnum : struct, Enum\n {\n#if !NET9_0_OR_GREATER\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The converter automatically detects any enum members decorated with \n /// and uses those values during serialization and deserialization.\n /// \n public CustomizableJsonStringEnumConverter() :\n base(namingPolicy: ResolveNamingPolicy())\n {\n }\n\n private static JsonNamingPolicy? ResolveNamingPolicy()\n {\n var map = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)\n .Select(f => (f.Name, AttributeName: f.GetCustomAttribute()?.Name))\n .Where(pair => pair.AttributeName != null)\n .ToDictionary(pair => pair.Name, pair => pair.AttributeName);\n\n return map.Count > 0 ? new EnumMemberNamingPolicy(map!) : null;\n }\n\n private sealed class EnumMemberNamingPolicy(Dictionary map) : JsonNamingPolicy\n {\n public override string ConvertName(string name) =>\n map.TryGetValue(name, out string? newName) ?\n newName :\n name;\n }\n#endif\n }\n\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n [RequiresUnreferencedCode(\"Requires unreferenced code to instantiate the generic enum converter.\")]\n [RequiresDynamicCode(\"Requires dynamic code to instantiate the generic enum converter.\")]\n public sealed class CustomizableJsonStringEnumConverter : JsonConverterFactory\n {\n /// \n public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum;\n /// \n public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)\n {\n Type converterType = typeof(CustomizableJsonStringEnumConverter<>).MakeGenericType(typeToConvert)!;\n var factory = (JsonConverterFactory)Activator.CreateInstance(converterType)!;\n return factory.CreateConverter(typeToConvert, options);\n }\n }\n}\n\n#if !NET9_0_OR_GREATER\nnamespace System.Text.Json.Serialization\n{\n /// \n /// Determines the custom string value that should be used when serializing an enum member using JSON.\n /// \n /// \n /// This attribute is a temporary workaround for lack of System.Text.Json's support for custom enum member naming\n /// in versions prior to .NET 9. It works together with \n /// to provide customized string representations of enum values during JSON serialization and deserialization.\n /// \n [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\n internal sealed class JsonStringEnumMemberNameAttribute : Attribute\n {\n /// \n /// Creates new attribute instance with a specified enum member name.\n /// \n /// The name to apply to the current enum member when serialized to JSON.\n public JsonStringEnumMemberNameAttribute(string name)\n {\n Name = name;\n }\n\n /// \n /// Gets the custom JSON name of the enum member.\n /// \n public string Name { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseWriter.cs", "using ModelContextProtocol.Protocol;\nusing System.Buffers;\nusing System.Net.ServerSentEvents;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class SseWriter(string? messageEndpoint = null, BoundedChannelOptions? channelOptions = null) : IAsyncDisposable\n{\n private readonly Channel> _messages = Channel.CreateBounded>(channelOptions ?? new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private Utf8JsonWriter? _jsonWriter;\n private Task? _writeTask;\n private CancellationToken? _writeCancellationToken;\n\n private readonly SemaphoreSlim _disposeLock = new(1, 1);\n private bool _disposed;\n\n public Func>, CancellationToken, IAsyncEnumerable>>? MessageFilter { get; set; }\n\n public Task WriteAllAsync(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n // When messageEndpoint is set, the very first SSE event isn't really an IJsonRpcMessage, but there's no API to write a single\n // item of a different type, so we fib and special-case the \"endpoint\" event type in the formatter.\n if (messageEndpoint is not null && !_messages.Writer.TryWrite(new SseItem(null, \"endpoint\")))\n {\n throw new InvalidOperationException(\"You must call RunAsync before calling SendMessageAsync.\");\n }\n\n _writeCancellationToken = cancellationToken;\n\n var messages = _messages.Reader.ReadAllAsync(cancellationToken);\n if (MessageFilter is not null)\n {\n messages = MessageFilter(messages, cancellationToken);\n }\n\n _writeTask = SseFormatter.WriteAsync(messages, sseResponseStream, WriteJsonRpcMessageToBuffer, cancellationToken);\n return _writeTask;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(message);\n\n using var _ = await _disposeLock.LockAsync(cancellationToken).ConfigureAwait(false);\n\n if (_disposed)\n {\n // Don't throw an ODE, because this is disposed internally when the transport disconnects due to an abort\n // or sending all the responses for the a give given Streamable HTTP POST request, so the user might not be at fault.\n // There's precedence for no-oping here similar to writing to the response body of an aborted request in ASP.NET Core.\n return;\n }\n\n // Emit redundant \"event: message\" lines for better compatibility with other SDKs.\n await _messages.Writer.WriteAsync(new SseItem(message, SseParser.EventTypeDefault), cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);\n\n if (_disposed)\n {\n return;\n }\n\n _messages.Writer.Complete();\n try\n {\n if (_writeTask is not null)\n {\n await _writeTask.ConfigureAwait(false);\n }\n }\n catch (OperationCanceledException) when (_writeCancellationToken?.IsCancellationRequested == true)\n {\n // Ignore exceptions caused by intentional cancellation during shutdown.\n }\n finally\n {\n _jsonWriter?.Dispose();\n _disposed = true;\n }\n }\n\n private void WriteJsonRpcMessageToBuffer(SseItem item, IBufferWriter writer)\n {\n if (item.EventType == \"endpoint\" && messageEndpoint is not null)\n {\n writer.Write(Encoding.UTF8.GetBytes(messageEndpoint));\n return;\n }\n\n JsonSerializer.Serialize(GetUtf8JsonWriter(writer), item.Data, McpJsonUtilities.JsonContext.Default.JsonRpcMessage!);\n }\n\n private Utf8JsonWriter GetUtf8JsonWriter(IBufferWriter writer)\n {\n if (_jsonWriter is null)\n {\n _jsonWriter = new Utf8JsonWriter(writer);\n }\n else\n {\n _jsonWriter.Reset(writer);\n }\n\n return _jsonWriter;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as\n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \npublic sealed class StreamableHttpServerTransport : ITransport\n{\n // For JsonRpcMessages without a RelatedTransport, we don't want to block just because the client didn't make a GET request to handle unsolicited messages.\n private readonly SseWriter _sseWriter = new(channelOptions: new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n FullMode = BoundedChannelFullMode.DropOldest,\n });\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n private readonly CancellationTokenSource _disposeCts = new();\n\n private int _getRequestStarted;\n\n /// \n public string? SessionId { get; set; }\n\n /// \n /// Configures whether the transport should be in stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process. Unsolicited server-to-client messages are not supported in this mode,\n /// so calling results in an .\n /// Server-to-client requests are also unsupported, because the responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// \n public bool Stateless { get; init; }\n\n /// \n /// Gets a value indicating whether the execution context should flow from the calls to \n /// to the corresponding emitted by the .\n /// \n /// \n /// Defaults to .\n /// \n public bool FlowExecutionContextFromRequests { get; init; }\n\n /// \n /// Gets or sets a callback to be invoked before handling the initialize request.\n /// \n public Func? OnInitRequestReceived { get; set; }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n internal ChannelWriter MessageWriter => _incomingChannel.Writer;\n\n /// \n /// Handles an optional SSE GET request a client using the Streamable HTTP transport might make by\n /// writing any unsolicited JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The response stream to write MCP JSON-RPC messages as SSE events to.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task HandleGetRequest(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"GET requests are not supported in stateless mode.\");\n }\n\n if (Interlocked.Exchange(ref _getRequestStarted, 1) == 1)\n {\n throw new InvalidOperationException(\"Session resumption is not yet supported. Please start a new session.\");\n }\n\n // We do not need to reference _disposeCts like in HandlePostRequest, because the session ending completes the _sseWriter gracefully.\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles a Streamable HTTP POST request processing both the request body and response body ensuring that\n /// and other correlated messages are sent back to the client directly in response\n /// to the that initiated the message.\n /// \n /// The duplex pipe facilitates the reading and writing of HTTP request and response data.\n /// This token allows for the operation to be canceled if needed.\n /// \n /// True, if data was written to the response body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async Task HandlePostRequest(IDuplexPipe httpBodies, CancellationToken cancellationToken)\n {\n using var postCts = CancellationTokenSource.CreateLinkedTokenSource(_disposeCts.Token, cancellationToken);\n await using var postTransport = new StreamableHttpPostTransport(this, httpBodies);\n return await postTransport.RunAsync(postCts.Token).ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"Unsolicited server to client messages are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n }\n finally\n {\n try\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n finally\n {\n _disposeCts.Dispose();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AugmentedServiceProvider.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Augments a service provider with additional request-related services.\ninternal sealed class RequestServiceProvider(\n RequestContext request, IServiceProvider? innerServices) :\n IServiceProvider, IKeyedServiceProvider,\n IServiceProviderIsService, IServiceProviderIsKeyedService,\n IDisposable, IAsyncDisposable\n where TRequestParams : RequestParams\n{\n /// Gets the request associated with this instance.\n public RequestContext Request => request;\n\n /// Gets whether the specified type is in the list of additional types this service provider wraps around the one in a provided request's services.\n public static bool IsAugmentedWith(Type serviceType) =>\n serviceType == typeof(RequestContext) ||\n serviceType == typeof(IMcpServer) ||\n serviceType == typeof(IProgress);\n\n /// \n public object? GetService(Type serviceType) =>\n serviceType == typeof(RequestContext) ? request :\n serviceType == typeof(IMcpServer) ? request.Server :\n serviceType == typeof(IProgress) ?\n (request.Params?.ProgressToken is { } progressToken ? new TokenProgress(request.Server, progressToken) : NullProgress.Instance) :\n innerServices?.GetService(serviceType);\n\n /// \n public bool IsService(Type serviceType) =>\n IsAugmentedWith(serviceType) ||\n (innerServices as IServiceProviderIsService)?.IsService(serviceType) is true;\n\n /// \n public bool IsKeyedService(Type serviceType, object? serviceKey) =>\n (serviceKey is null && IsService(serviceType)) ||\n (innerServices as IServiceProviderIsKeyedService)?.IsKeyedService(serviceType, serviceKey) is true;\n\n /// \n public object? GetKeyedService(Type serviceType, object? serviceKey) =>\n serviceKey is null ? GetService(serviceType) :\n (innerServices as IKeyedServiceProvider)?.GetKeyedService(serviceType, serviceKey);\n\n /// \n public object GetRequiredKeyedService(Type serviceType, object? serviceKey) =>\n GetKeyedService(serviceType, serviceKey) ??\n throw new InvalidOperationException($\"No service of type '{serviceType}' with key '{serviceKey}' is registered.\");\n\n /// \n public void Dispose() =>\n (innerServices as IDisposable)?.Dispose();\n\n /// \n public ValueTask DisposeAsync() =>\n innerServices is IAsyncDisposable asyncDisposable ? asyncDisposable.DisposeAsync() : default;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Tool.cs", "using System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a tool that the server is capable of calling.\n/// \npublic sealed class Tool : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the tool.\n /// \n /// \n /// \n /// This description helps the AI model understand what the tool does and when to use it.\n /// It should be clear, concise, and accurately describe the tool's purpose and functionality.\n /// \n /// \n /// The description is typically presented to AI models to help them determine when\n /// and how to use the tool based on user requests.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a JSON Schema object defining the expected parameters for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema typically defines the properties (parameters) that the tool accepts, \n /// their types, and which ones are required. This helps AI models understand\n /// how to structure their calls to the tool.\n /// \n /// \n /// If not explicitly set, a default minimal schema of {\"type\":\"object\"} is used.\n /// \n /// \n [JsonPropertyName(\"inputSchema\")]\n public JsonElement InputSchema \n { \n get => field; \n set\n {\n if (!McpJsonUtilities.IsValidMcpToolSchema(value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool input JSON schema.\", nameof(InputSchema));\n }\n\n field = value;\n }\n\n } = McpJsonUtilities.DefaultMcpToolSchema;\n\n /// \n /// Gets or sets a JSON Schema object defining the expected structured outputs for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema should describe the shape of the data as returned in .\n /// \n /// \n [JsonPropertyName(\"outputSchema\")]\n public JsonElement? OutputSchema\n {\n get => field;\n set\n {\n if (value is not null && !McpJsonUtilities.IsValidMcpToolSchema(value.Value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool output JSON schema.\", nameof(OutputSchema));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets optional additional tool information and behavior hints.\n /// \n /// \n /// These annotations provide metadata about the tool's behavior, such as whether it's read-only,\n /// destructive, idempotent, or operates in an open world. They also can include a human-readable title.\n /// Note that these are hints and should not be relied upon for security decisions.\n /// \n [JsonPropertyName(\"annotations\")]\n public ToolAnnotations? Annotations { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/SseClientTransportOptions.cs", "using ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class SseClientTransportOptions\n{\n /// \n /// Gets or sets the base address of the server for SSE connections.\n /// \n public required Uri Endpoint\n {\n get;\n set\n {\n if (value is null)\n {\n throw new ArgumentNullException(nameof(value), \"Endpoint cannot be null.\");\n }\n if (!value.IsAbsoluteUri)\n {\n throw new ArgumentException(\"Endpoint must be an absolute URI.\", nameof(value));\n }\n if (value.Scheme != Uri.UriSchemeHttp && value.Scheme != Uri.UriSchemeHttps)\n {\n throw new ArgumentException(\"Endpoint must use HTTP or HTTPS scheme.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the transport mode to use for the connection. Defaults to .\n /// \n /// \n /// \n /// When set to (the default), the client will first attempt to use\n /// Streamable HTTP transport and automatically fall back to SSE transport if the server doesn't support it.\n /// \n /// \n /// Streamable HTTP transport specification.\n /// HTTP with SSE transport specification.\n /// \n /// \n public HttpTransportMode TransportMode { get; set; } = HttpTransportMode.AutoDetect;\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets a timeout used to establish the initial connection to the SSE server. Defaults to 30 seconds.\n /// \n /// \n /// This timeout controls how long the client waits for:\n /// \n /// The initial HTTP connection to be established with the SSE server\n /// The endpoint event to be received, which indicates the message endpoint URL\n /// \n /// If the timeout expires before the connection is established, a will be thrown.\n /// \n public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);\n\n /// \n /// Gets custom HTTP headers to include in requests to the SSE server.\n /// \n /// \n /// Use this property to specify custom HTTP headers that should be sent with each request to the server.\n /// \n public IDictionary? AdditionalHeaders { get; set; }\n\n /// \n /// Gets sor sets the authorization provider to use for authentication.\n /// \n public ClientOAuthOptions? OAuth { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for all request parameters.\n/// \n/// \n/// See the schema for details.\n/// \npublic abstract class RequestParams\n{\n /// Prevent external derivations.\n private protected RequestParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n [JsonIgnore]\n public ProgressToken? ProgressToken\n {\n get\n {\n if (Meta?[\"progressToken\"] is JsonValue progressToken)\n {\n if (progressToken.TryGetValue(out string? stringValue))\n {\n return new ProgressToken(stringValue);\n }\n\n if (progressToken.TryGetValue(out long longValue))\n {\n return new ProgressToken(longValue);\n }\n }\n\n return null;\n }\n set\n {\n if (value is null)\n {\n Meta?.Remove(\"progressToken\");\n }\n else\n {\n (Meta ??= [])[\"progressToken\"] = value.Value.Token switch\n {\n string s => JsonValue.Create(s),\n long l => JsonValue.Create(l),\n _ => throw new InvalidOperationException(\"ProgressToken must be a string or a long.\")\n };\n }\n }\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/PrintEnvTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class PrintEnvTool\n{\n private static readonly JsonSerializerOptions options = new()\n {\n WriteIndented = true\n };\n\n [McpServerTool(Name = \"printEnv\"), Description(\"Prints all environment variables, helpful for debugging MCP server configuration\")]\n public static string PrintEnv() =>\n JsonSerializer.Serialize(Environment.GetEnvironmentVariables(), options);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.ObjectModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides an that calls a tool via an .\n/// \n/// \n/// \n/// The class encapsulates an along with a description of \n/// a tool available via that client, allowing it to be invoked as an . This enables integration\n/// with AI models that support function calling capabilities.\n/// \n/// \n/// Tools retrieved from an MCP server can be customized for model presentation using methods like\n/// and without changing the underlying tool functionality.\n/// \n/// \n/// Typically, you would get instances of this class by calling the \n/// or extension methods on an instance.\n/// \n/// \npublic sealed class McpClientTool : AIFunction\n{\n /// Additional properties exposed from tools.\n private static readonly ReadOnlyDictionary s_additionalProperties =\n new(new Dictionary()\n {\n [\"Strict\"] = false, // some MCP schemas may not meet \"strict\" requirements\n });\n\n private readonly IMcpClient _client;\n private readonly string _name;\n private readonly string _description;\n private readonly IProgress? _progress;\n\n internal McpClientTool(\n IMcpClient client,\n Tool tool,\n JsonSerializerOptions serializerOptions,\n string? name = null,\n string? description = null,\n IProgress? progress = null)\n {\n _client = client;\n ProtocolTool = tool;\n JsonSerializerOptions = serializerOptions;\n _name = name ?? tool.Name;\n _description = description ?? tool.Description ?? string.Empty;\n _progress = progress;\n }\n\n /// \n /// Gets the protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the tool,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// It contains the original metadata about the tool as provided by the server, including its\n /// name, description, and schema information before any customizations applied through methods\n /// like or .\n /// \n public Tool ProtocolTool { get; }\n\n /// \n public override string Name => _name;\n\n /// Gets the tool's title.\n public string? Title => ProtocolTool.Title ?? ProtocolTool.Annotations?.Title;\n\n /// \n public override string Description => _description;\n\n /// \n public override JsonElement JsonSchema => ProtocolTool.InputSchema;\n\n /// \n public override JsonElement? ReturnJsonSchema => ProtocolTool.OutputSchema;\n\n /// \n public override JsonSerializerOptions JsonSerializerOptions { get; }\n\n /// \n public override IReadOnlyDictionary AdditionalProperties => s_additionalProperties;\n\n /// \n protected async override ValueTask InvokeCoreAsync(\n AIFunctionArguments arguments, CancellationToken cancellationToken)\n {\n CallToolResult result = await CallAsync(arguments, _progress, JsonSerializerOptions, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult);\n }\n\n /// \n /// Invokes the tool on the server.\n /// \n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// \n /// The base method is overridden to invoke this method.\n /// The only difference in behavior is will serialize the resulting \"/>\n /// such that the returned is a containing the serialized .\n /// This method is intended to be called directly by user code, whereas the base \n /// is intended to be used polymorphically via the base class, typically as part of an operation.\n /// \n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// var result = await tool.CallAsync(\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public ValueTask CallAsync(\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default) =>\n _client.CallToolAsync(ProtocolTool.Name, arguments, progress, serializerOptions, cancellationToken);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified name from its property.\n /// \n /// The model-facing name to give the tool.\n /// A new instance of with the provided name.\n /// \n /// \n /// This is useful for optimizing the tool name for specific models or for prefixing the tool name \n /// with a namespace to avoid conflicts.\n /// \n /// \n /// Changing the name can help with:\n /// \n /// \n /// Making the tool name more intuitive for the model\n /// Preventing name collisions when using tools from multiple sources\n /// Creating specialized versions of a general tool for specific contexts\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool name, so no mapping is required on the server side. This new name only affects\n /// the value returned from this instance's .\n /// \n /// \n public McpClientTool WithName(string name) =>\n new(_client, ProtocolTool, JsonSerializerOptions, name, _description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified description from its property.\n /// \n /// The description to give the tool.\n /// \n /// \n /// Changing the description can help the model better understand the tool's purpose or provide more\n /// context about how the tool should be used. This is particularly useful when:\n /// \n /// \n /// The original description is too technical or lacks clarity for the model\n /// You want to add example usage scenarios to improve the model's understanding\n /// You need to tailor the tool's description for specific model requirements\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool description, so no mapping is required on the server side. This new description only affects\n /// the value returned from this instance's .\n /// \n /// \n /// A new instance of with the provided description.\n public McpClientTool WithDescription(string description) =>\n new(_client, ProtocolTool, JsonSerializerOptions, _name, description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to report progress via the specified .\n /// \n /// The to which progress notifications should be reported.\n /// \n /// \n /// Adding an to the tool does not impact how it is reported to any AI model.\n /// Rather, when the tool is invoked, the request to the MCP server will include a unique progress token,\n /// and any progress notifications issued by the server with that progress token while the operation is in\n /// flight will be reported to the instance.\n /// \n /// \n /// Only one can be specified at a time. Calling again\n /// will overwrite any previously specified progress instance.\n /// \n /// \n /// A new instance of , configured with the provided progress instance.\n public McpClientTool WithProgress(IProgress progress)\n {\n Throw.IfNull(progress);\n\n return new McpClientTool(_client, ProtocolTool, JsonSerializerOptions, _name, _description, progress);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcRequest.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A request message in the JSON-RPC protocol.\n/// \n/// \n/// Requests are messages that require a response from the receiver. Each request includes a unique ID\n/// that will be included in the corresponding response message (either a success response or an error).\n/// \n/// The receiver of a request message is expected to execute the specified method with the provided parameters\n/// and return either a with the result, or a \n/// if the method execution fails.\n/// \npublic sealed class JsonRpcRequest : JsonRpcMessageWithId\n{\n /// \n /// Name of the method to invoke.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Optional parameters for the method.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n\n internal JsonRpcRequest WithId(RequestId id)\n {\n return new JsonRpcRequest\n {\n JsonRpc = JsonRpc,\n Id = id,\n Method = Method,\n Params = Params,\n RelatedTransport = RelatedTransport,\n };\n }\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Program.cs", "using OpenTelemetry;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\nusing TestServerWithHosting.Tools;\nusing TestServerWithHosting.Resources;\n\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Services.AddMcpServer()\n .WithHttpTransport()\n .WithTools()\n .WithTools()\n .WithResources();\n\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithMetrics(b => b.AddMeter(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithLogging()\n .UseOtlpExporter();\n\nvar app = builder.Build();\n\napp.MapMcp();\n\napp.Run();\n"], ["/csharp-sdk/samples/QuickstartClient/Program.cs", "using Anthropic.SDK;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Client;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Configuration\n .AddEnvironmentVariables()\n .AddUserSecrets();\n\nvar (command, arguments) = GetCommandAndArguments(args);\n\nvar clientTransport = new StdioClientTransport(new()\n{\n Name = \"Demo Server\",\n Command = command,\n Arguments = arguments,\n});\n\nawait using var mcpClient = await McpClientFactory.CreateAsync(clientTransport);\n\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\"Connected to server with tools: {tool.Name}\");\n}\n\nusing var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration[\"ANTHROPIC_API_KEY\"]))\n .Messages\n .AsBuilder()\n .UseFunctionInvocation()\n .Build();\n\nvar options = new ChatOptions\n{\n MaxOutputTokens = 1000,\n ModelId = \"claude-3-5-sonnet-20241022\",\n Tools = [.. tools]\n};\n\nConsole.ForegroundColor = ConsoleColor.Green;\nConsole.WriteLine(\"MCP Client Started!\");\nConsole.ResetColor();\n\nPromptForInput();\nwhile(Console.ReadLine() is string query && !\"exit\".Equals(query, StringComparison.OrdinalIgnoreCase))\n{\n if (string.IsNullOrWhiteSpace(query))\n {\n PromptForInput();\n continue;\n }\n\n await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))\n {\n Console.Write(message);\n }\n Console.WriteLine();\n\n PromptForInput();\n}\n\nstatic void PromptForInput()\n{\n Console.WriteLine(\"Enter a command (or 'exit' to quit):\");\n Console.ForegroundColor = ConsoleColor.Cyan;\n Console.Write(\"> \");\n Console.ResetColor();\n}\n\n/// \n/// Determines the command (executable) to run and the script/path to pass to it. This allows different\n/// languages/runtime environments to be used as the MCP server.\n/// \n/// \n/// This method uses the file extension of the first argument to determine the command, if it's py, it'll run python,\n/// if it's js, it'll run node, if it's a directory or a csproj file, it'll run dotnet.\n/// \n/// If no arguments are provided, it defaults to running the QuickstartWeatherServer project from the current repo.\n/// \n/// This method would only be required if you're creating a generic client, such as we use for the quickstart.\n/// \nstatic (string command, string[] arguments) GetCommandAndArguments(string[] args)\n{\n return args switch\n {\n [var script] when script.EndsWith(\".py\") => (\"python\", args),\n [var script] when script.EndsWith(\".js\") => (\"node\", args),\n [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(\".csproj\")) => (\"dotnet\", [\"run\", \"--project\", script]),\n _ => (\"dotnet\", [\"run\", \"--project\", Path.Combine(GetCurrentSourceDirectory(), \"../QuickstartWeatherServer\")])\n };\n}\n\nstatic string GetCurrentSourceDirectory([CallerFilePath] string? currentFile = null)\n{\n Debug.Assert(!string.IsNullOrWhiteSpace(currentFile));\n return Path.GetDirectoryName(currentFile) ?? throw new InvalidOperationException(\"Unable to determine source directory.\");\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/NotificationHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol;\n\n/// Provides thread-safe storage for notification handlers.\ninternal sealed class NotificationHandlers\n{\n /// A dictionary of linked lists of registrations, indexed by the notification method.\n private readonly Dictionary _handlers = [];\n\n /// Gets the object to be used for all synchronization.\n private object SyncObj => _handlers;\n\n /// \n /// Registers a collection of notification handlers at once.\n /// \n /// \n /// A collection of notification method names paired with their corresponding handler functions.\n /// Each key in the collection is a notification method name, and each value is a handler function\n /// that will be invoked when a notification with that method name is received.\n /// \n /// \n /// \n /// This method is typically used during client or server initialization to register\n /// all notification handlers provided in capabilities.\n /// \n /// \n /// Registrations completed with this method are permanent and non-removable.\n /// This differs from handlers registered with which can be temporary.\n /// \n /// \n /// When multiple handlers are registered for the same method, all handlers will be invoked\n /// in reverse order of registration (newest first) when a notification is received.\n /// \n /// \n /// The registered handlers will be invoked by when a notification\n /// with the corresponding method name is received.\n /// \n /// \n public void RegisterRange(IEnumerable>> handlers)\n {\n foreach (var entry in handlers)\n {\n _ = Register(entry.Key, entry.Value, temporary: false);\n }\n }\n\n /// \n /// Adds a notification handler as part of configuring the endpoint.\n /// \n /// The notification method for which the handler is being registered.\n /// The handler being registered.\n /// \n /// if the registration can be removed later; if it cannot.\n /// If , the registration will be permanent: calling \n /// on the returned instance will not unregister the handler.\n /// \n /// \n /// An that when disposed will unregister the handler if is .\n /// \n /// \n /// Multiple handlers can be registered for the same method. When a notification for that method is received,\n /// all registered handlers will be invoked in reverse order of registration (newest first).\n /// \n public IAsyncDisposable Register(\n string method, Func handler, bool temporary = true)\n {\n // Create the new registration instance.\n Registration reg = new(this, method, handler, temporary);\n\n // Store the registration into the dictionary. If there's not currently a registration for the method,\n // then this registration instance just becomes the single value. If there is currently a registration,\n // then this new registration becomes the new head of the linked list, and the old head becomes the next\n // item in the list.\n lock (SyncObj)\n {\n if (_handlers.TryGetValue(method, out var existingHandlerHead))\n {\n reg.Next = existingHandlerHead;\n existingHandlerHead.Prev = reg;\n }\n\n _handlers[method] = reg;\n }\n\n // Return the new registration. It must be disposed of when no longer used, or it will end up being\n // leaked into the list. This is the same as with CancellationToken.Register.\n return reg;\n }\n\n /// \n /// Invokes all registered handlers for the specified notification method.\n /// \n /// The notification method name to invoke handlers for.\n /// The notification object to pass to each handler.\n /// A token that can be used to cancel the operation.\n /// \n /// Handlers are invoked in reverse order of registration (newest first).\n /// If any handler throws an exception, all handlers will still be invoked, and an \n /// containing all exceptions will be thrown after all handlers have been invoked.\n /// \n public async Task InvokeHandlers(string method, JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // If there are no handlers registered for this method, we're done.\n Registration? reg;\n lock (SyncObj)\n {\n if (!_handlers.TryGetValue(method, out reg))\n {\n return;\n }\n }\n\n // Invoke each handler in the list. We guarantee that we'll try to invoke\n // any handlers that were in the list when the list was fetched from the dictionary,\n // which is why DisposeAsync doesn't modify the Prev/Next of the registration being\n // disposed; if those were nulled out, we'd be unable to walk around it in the list\n // if we happened to be on that item when it was disposed.\n List? exceptions = null;\n while (reg is not null)\n {\n try\n {\n await reg.InvokeAsync(notification, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e)\n {\n (exceptions ??= []).Add(e);\n }\n\n lock (SyncObj)\n {\n reg = reg.Next;\n }\n }\n\n if (exceptions is not null)\n {\n throw new AggregateException(exceptions);\n }\n }\n\n /// Provides storage for a handler registration.\n private sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable) : IAsyncDisposable\n {\n /// Used to prevent deadlocks during disposal.\n /// \n /// The task returned from does not complete until all invocations of the handler\n /// have completed and no more will be performed, so that the consumer can then trust that any resources accessed\n /// by that handler are no longer in use and may be cleaned up. If were to be invoked\n /// and its task awaited from within the invocation of the handler, however, that would result in deadlock, since\n /// the task wouldn't complete until the invocation completed, and the invocation wouldn't complete until the task\n /// completed. To circument that, we track via an in-flight invocations. If\n /// detects it's being invoked from within an invocation, it will avoid waiting. For\n /// simplicity, we don't require that it's the same handler.\n /// \n private static readonly AsyncLocal s_invokingAncestor = new();\n\n /// The parent to which this registration belongs.\n private readonly NotificationHandlers _handlers = handlers;\n\n /// The method with which this registration is associated.\n private readonly string _method = method;\n \n /// The handler this registration represents.\n private readonly Func _handler = handler;\n\n /// true if this instance is temporary; false if it's permanent\n private readonly bool _temporary = unregisterable;\n\n /// Provides a task that can await to know when all in-flight invocations have completed.\n /// \n /// This will only be initialized if sees in-flight invocations, in which case it'll initialize\n /// this and then await its task. The task will be completed when the last\n /// in-flight notification completes.\n /// \n private TaskCompletionSource? _disposeTcs;\n \n /// The number of remaining references to this registration.\n /// \n /// The ref count starts life at 1 to represent the whole registration; that ref count will be subtracted when\n /// the instance is disposed. Every invocation then temporarily increases the ref count before invocation and\n /// decrements it after. When is called, it decrements the ref count. In the common\n /// case, that'll bring the count down to 0, in which case the instance will never be subsequently invoked.\n /// If, however, after that decrement the count is still positive, then there are in-flight invocations; the last\n /// one of those to complete will end up decrementing the ref count to 0.\n /// \n private int _refCount = 1;\n\n /// Tracks whether has ever been invoked.\n /// \n /// It's rare but possible is called multiple times. Only the first\n /// should decrement the initial ref count, but they all must wait until all invocations have quiesced.\n /// \n private bool _disposedCalled = false;\n\n /// The next registration in the linked list.\n public Registration? Next;\n /// \n /// The previous registration in the linked list of handlers for a specific notification method.\n /// Used to maintain the bidirectional linked list when handlers are added or removed.\n /// \n public Registration? Prev;\n\n /// Removes the registration.\n public async ValueTask DisposeAsync()\n {\n if (!_temporary)\n {\n return;\n }\n\n lock (_handlers.SyncObj)\n {\n // If DisposeAsync was previously called, we don't want to do all of the work again\n // to remove the registration from the list, and we must not do the work again to\n // decrement the ref count and possibly initialize the _disposeTcs.\n if (!_disposedCalled)\n {\n _disposedCalled = true;\n\n // If this handler is the head of the list for this method, we need to update\n // the dictionary, either to point to a different head, or if this is the only\n // item in the list, to remove the entry from the dictionary entirely.\n if (_handlers._handlers.TryGetValue(_method, out var handlers) && handlers == this)\n {\n if (Next is not null)\n {\n _handlers._handlers[_method] = Next;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n\n // Remove the registration from the linked list by routing the nodes around it\n // to point past this one. Importantly, we do not modify this node's Next or Prev.\n // We want to ensure that an enumeration through all of the registrations can still\n // progress through this one.\n if (Prev is not null)\n {\n Prev.Next = Next;\n }\n if (Next is not null)\n {\n Next.Prev = Prev;\n }\n\n // Decrement the ref count. In the common case, there's no in-flight invocation for\n // this handler. However, in the uncommon case that there is, we need to wait for\n // that invocation to complete. To do that, initialize the _disposeTcs. It's created\n // with RunContinuationsAsynchronously so that completing it doesn't run the continuation\n // under any held locks.\n if (--_refCount != 0)\n {\n Debug.Assert(_disposeTcs is null);\n _disposeTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);\n }\n }\n }\n\n // Ensure that DisposeAsync doesn't complete until all in-flight invocations have completed,\n // unless our call chain includes one of those in-flight invocations, in which case waiting\n // would deadlock.\n if (_disposeTcs is not null && s_invokingAncestor.Value == 0)\n {\n await _disposeTcs.Task.ConfigureAwait(false);\n }\n }\n\n /// Invoke the handler associated with the registration.\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // For permanent registrations, skip all the tracking overhead and just invoke the handler.\n if (!_temporary)\n {\n return _handler(notification, cancellationToken);\n }\n\n // For temporary registrations, track the invocation and coordinate with disposal.\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n\n /// Invoke the handler associated with the temporary registration.\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // Check whether we need to handle this registration. If DisposeAsync has been called,\n // then even if there are in-flight invocations for it, we avoid adding more.\n // If DisposeAsync has not been called, then we need to increment the ref count to\n // signal that there's another in-flight invocation.\n lock (_handlers.SyncObj)\n {\n Debug.Assert(_refCount != 0 || _disposedCalled, $\"Expected {nameof(_disposedCalled)} == true when {nameof(_refCount)} == 0\");\n if (_disposedCalled)\n {\n return;\n }\n\n Debug.Assert(_refCount > 0);\n _refCount++;\n }\n\n // Ensure that if DisposeAsync is called from within the handler, it won't deadlock by waiting\n // for the in-flight invocation to complete.\n s_invokingAncestor.Value++;\n\n try\n {\n // Invoke the handler.\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n // Undo the in-flight tracking.\n s_invokingAncestor.Value--;\n\n // Now decrement the ref count we previously incremented. If that brings the ref count to 0,\n // DisposeAsync must have been called while this was in-flight, which also means it's now\n // waiting on _disposeTcs; unblock it.\n lock (_handlers.SyncObj)\n {\n _refCount--;\n if (_refCount == 0)\n {\n Debug.Assert(_disposedCalled);\n Debug.Assert(_disposeTcs is not null);\n bool completed = _disposeTcs!.TrySetResult(true);\n Debug.Assert(completed);\n }\n }\n }\n }\n }\n}\n"], ["/csharp-sdk/samples/ChatWithTools/Program.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing OpenAI;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\n\nusing var tracerProvider = Sdk.CreateTracerProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddSource(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var metricsProvider = Sdk.CreateMeterProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddMeter(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var loggerFactory = LoggerFactory.Create(builder => builder.AddOpenTelemetry(opt => opt.AddOtlpExporter()));\n\n// Connect to an MCP server\nConsole.WriteLine(\"Connecting client to MCP 'everything' server\");\n\n// Create OpenAI client (or any other compatible with IChatClient)\n// Provide your own OPENAI_API_KEY via an environment variable.\nvar openAIClient = new OpenAIClient(Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")).GetChatClient(\"gpt-4o-mini\");\n\n// Create a sampling client.\nusing IChatClient samplingClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\nvar mcpClient = await McpClientFactory.CreateAsync(\n new StdioClientTransport(new()\n {\n Command = \"npx\",\n Arguments = [\"-y\", \"--verbose\", \"@modelcontextprotocol/server-everything\"],\n Name = \"Everything\",\n }),\n clientOptions: new()\n {\n Capabilities = new() { Sampling = new() { SamplingHandler = samplingClient.CreateSamplingHandler() } },\n },\n loggerFactory: loggerFactory);\n\n// Get all available tools\nConsole.WriteLine(\"Tools available:\");\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\" {tool}\");\n}\n\nConsole.WriteLine();\n\n// Create an IChatClient that can use the tools.\nusing IChatClient chatClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseFunctionInvocation()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\n// Have a conversation, making all tools available to the LLM.\nList messages = [];\nwhile (true)\n{\n Console.Write(\"Q: \");\n messages.Add(new(ChatRole.User, Console.ReadLine()));\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, new() { Tools = [.. tools] }))\n {\n Console.Write(update);\n updates.Add(update);\n }\n Console.WriteLine();\n\n messages.AddMessages(updates);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing members that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing members that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithResourcesFromAssembly, it enables automatic registration of resources without explicitly listing each\n/// resource class. The attribute is not necessary when a reference to the type is provided directly to a method\n/// like McpServerBuilderExtensions.WithResources.\n/// \n/// \n/// Within a class marked with this attribute, individual members that should be exposed as\n/// resources must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerResourceTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of tools created with\n/// . They provide control over naming, description,\n/// tool properties, and dependency injection integration.\n/// \n/// \n/// When creating tools programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerToolCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisfied from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Destructive { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Idempotent { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? OpenWorld { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? ReadOnly { get; set; }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerToolCreateOptions Clone() =>\n new McpServerToolCreateOptions\n {\n Services = Services,\n Name = Name,\n Description = Description,\n Title = Title,\n Destructive = Destructive,\n Idempotent = Idempotent,\n OpenWorld = OpenWorld,\n ReadOnly = ReadOnly,\n UseStructuredContent = UseStructuredContent,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\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/samples/EverythingServer/SubscriptionMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\ninternal class SubscriptionMessageSender(IMcpServer server, HashSet subscriptions) : BackgroundService\n{\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n foreach (var uri in subscriptions)\n {\n await server.SendNotificationAsync(\"notifications/resource/updated\",\n new\n {\n Uri = uri,\n }, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(5000, stoppingToken);\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrimitiveCollection.cs", "using System.Collections;\nusing System.Collections.Concurrent;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their names.\n/// Specifies the type of primitive stored in the collection.\npublic class McpServerPrimitiveCollection : ICollection, IReadOnlyCollection\n where T : IMcpServerPrimitive\n{\n /// Concurrent dictionary of primitives, indexed by their names.\n private readonly ConcurrentDictionary _primitives;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPrimitiveCollection(IEqualityComparer? keyComparer = null)\n {\n _primitives = new(keyComparer ?? EqualityComparer.Default);\n }\n\n /// Occurs when the collection is changed.\n /// \n /// By default, this is raised when a primitive is added or removed. However, a derived implementation\n /// may raise this event for other reasons, such as when a primitive is modified.\n /// \n public event EventHandler? Changed;\n\n /// Gets the number of primitives in the collection.\n public int Count => _primitives.Count;\n\n /// Gets whether there are any primitives in the collection.\n public bool IsEmpty => _primitives.IsEmpty;\n\n /// Raises if there are registered handlers.\n protected void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);\n\n /// Gets the with the specified from the collection.\n /// The name of the primitive to retrieve.\n /// The with the specified name.\n /// is .\n /// An primitive with the specified name does not exist in the collection.\n public T this[string name]\n {\n get\n {\n Throw.IfNull(name);\n return _primitives[name];\n }\n }\n\n /// Clears all primitives from the collection.\n public virtual void Clear()\n {\n _primitives.Clear();\n RaiseChanged();\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// is .\n /// A primitive with the same name as already exists in the collection.\n public void Add(T primitive)\n {\n if (!TryAdd(primitive))\n {\n throw new ArgumentException($\"A primitive with the same name '{primitive.Id}' already exists in the collection.\", nameof(primitive));\n }\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// if the primitive was added; otherwise, .\n /// is .\n public virtual bool TryAdd(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool added = _primitives.TryAdd(primitive.Id, primitive);\n if (added)\n {\n RaiseChanged();\n }\n\n return added;\n }\n\n /// Removes the specified primitivefrom the collection.\n /// The primitive to be removed from the collection.\n /// \n /// if the primitive was found in the collection and removed; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool Remove(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool removed = ((ICollection>)_primitives).Remove(new(primitive.Id, primitive));\n if (removed)\n {\n RaiseChanged();\n }\n\n return removed;\n }\n\n /// Attempts to get the primitive with the specified name from the collection.\n /// The name of the primitive to retrieve.\n /// The primitive, if found; otherwise, .\n /// \n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool TryGetPrimitive(string name, [NotNullWhen(true)] out T? primitive)\n {\n Throw.IfNull(name);\n return _primitives.TryGetValue(name, out primitive);\n }\n\n /// Checks if a specific primitive is present in the collection of primitives.\n /// The primitive to search for in the collection.\n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// is .\n public virtual bool Contains(T primitive)\n {\n Throw.IfNull(primitive);\n return ((ICollection>)_primitives).Contains(new(primitive.Id, primitive));\n }\n\n /// Gets the names of all of the primitives in the collection.\n public virtual ICollection PrimitiveNames => _primitives.Keys;\n\n /// Creates an array containing all of the primitives in the collection.\n /// An array containing all of the primitives in the collection.\n public virtual T[] ToArray() => _primitives.Values.ToArray();\n\n /// \n public virtual void CopyTo(T[] array, int arrayIndex)\n {\n Throw.IfNull(array);\n\n _primitives.Values.CopyTo(array, arrayIndex);\n }\n\n /// \n public virtual IEnumerator GetEnumerator()\n {\n foreach (var entry in _primitives)\n {\n yield return entry.Value;\n }\n }\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n bool ICollection.IsReadOnly => false;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpEndpointExtensions.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class provides strongly-typed methods for working with the Model Context Protocol (MCP) endpoints,\n/// simplifying JSON-RPC communication by handling serialization and deserialization of parameters and results.\n/// \n/// \n/// These extension methods are designed to be used with both client () and\n/// server () implementations of the interface.\n/// \n/// \npublic static class McpEndpointExtensions\n{\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The request id for the request.\n /// The options governing request serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n public static ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo paramsTypeInfo = serializerOptions.GetTypeInfo();\n JsonTypeInfo resultTypeInfo = serializerOptions.GetTypeInfo();\n return SendRequestAsync(endpoint, method, parameters, paramsTypeInfo, resultTypeInfo, requestId, cancellationToken);\n }\n\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The type information for request parameter deserialization.\n /// The request id for the request.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n internal static async ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n JsonTypeInfo resultTypeInfo,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n Throw.IfNull(resultTypeInfo);\n\n JsonRpcRequest jsonRpcRequest = new()\n {\n Id = requestId,\n Method = method,\n Params = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo),\n };\n\n JsonRpcResponse response = await endpoint.SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.Deserialize(response.Result, resultTypeInfo) ?? throw new JsonException(\"Unexpected JSON result in response.\");\n }\n\n /// \n /// Sends a parameterless notification to the connected endpoint.\n /// \n /// The MCP client or server instance.\n /// The notification method name.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification without any parameters. Notifications are one-way messages \n /// that don't expect a response. They are commonly used for events, status updates, or to signal \n /// changes in state.\n /// \n /// \n public static Task SendNotificationAsync(this IMcpEndpoint client, string method, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(method);\n return client.SendMessageAsync(new JsonRpcNotification { Method = method }, cancellationToken);\n }\n\n /// \n /// Sends a notification with parameters to the connected endpoint.\n /// \n /// The type of the notification parameters to serialize.\n /// The MCP client or server instance.\n /// The JSON-RPC method name for the notification.\n /// Object representing the notification parameters.\n /// The options governing parameter serialization. If null, default options are used.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification with parameters to the connected endpoint. Notifications are one-way \n /// messages that don't expect a response, commonly used for events, status updates, or signaling changes.\n /// \n /// \n /// The parameters object is serialized to JSON according to the provided serializer options or the default \n /// options if none are specified.\n /// \n /// \n /// The Model Context Protocol defines several standard notification methods in ,\n /// but custom methods can also be used for application-specific notifications.\n /// \n /// \n public static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo parametersTypeInfo = serializerOptions.GetTypeInfo();\n return SendNotificationAsync(endpoint, method, parameters, parametersTypeInfo, cancellationToken);\n }\n\n /// \n /// Sends a notification to the server with parameters.\n /// \n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The to monitor for cancellation requests. The default is .\n internal static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n\n JsonNode? parametersJson = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo);\n return endpoint.SendMessageAsync(new JsonRpcNotification { Method = method, Params = parametersJson }, cancellationToken);\n }\n\n /// \n /// Notifies the connected endpoint of progress for a long-running operation.\n /// \n /// The endpoint issuing the notification.\n /// The identifying the operation for which progress is being reported.\n /// The progress update to send, containing information such as percentage complete or status message.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the completion of the notification operation (not the operation being tracked).\n /// is .\n /// \n /// \n /// This method sends a progress notification to the connected endpoint using the Model Context Protocol's\n /// standardized progress notification format. Progress updates are identified by a \n /// that allows the recipient to correlate multiple updates with a specific long-running operation.\n /// \n /// \n /// Progress notifications are sent asynchronously and don't block the operation from continuing.\n /// \n /// \n public static Task NotifyProgressAsync(\n this IMcpEndpoint endpoint,\n ProgressToken progressToken,\n ProgressNotificationValue progress, \n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n\n return endpoint.SendNotificationAsync(\n NotificationMethods.ProgressNotification,\n new ProgressNotificationParams\n {\n ProgressToken = progressToken,\n Progress = progress,\n },\n McpJsonUtilities.JsonContext.Default.ProgressNotificationParams,\n cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientFactory.cs", "using Microsoft.Extensions.Logging;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides factory methods for creating Model Context Protocol (MCP) clients.\n/// \n/// \n/// This factory class is the primary way to instantiate instances\n/// that connect to MCP servers. It handles the creation and connection\n/// of appropriate implementations through the supplied transport.\n/// \npublic static partial class McpClientFactory\n{\n /// Creates an , connecting it to the specified server.\n /// The transport instance used to communicate with the server.\n /// \n /// A client configuration object which specifies client capabilities and protocol version.\n /// If , details based on the current process will be employed.\n /// \n /// A logger factory for creating loggers for clients.\n /// The to monitor for cancellation requests. The default is .\n /// An that's connected to the specified server.\n /// is .\n /// is .\n public static async Task CreateAsync(\n IClientTransport clientTransport,\n McpClientOptions? clientOptions = null,\n ILoggerFactory? loggerFactory = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(clientTransport);\n\n McpClient client = new(clientTransport, clientOptions, loggerFactory);\n try\n {\n await client.ConnectAsync(cancellationToken).ConfigureAwait(false);\n if (loggerFactory?.CreateLogger(typeof(McpClientFactory)) is ILogger logger)\n {\n logger.LogClientCreated(client.EndpointName);\n }\n }\n catch\n {\n await client.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n\n return client;\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} client created and connected.\")]\n private static partial void LogClientCreated(this ILogger logger, string endpointName);\n}"], ["/csharp-sdk/src/Common/Polyfills/System/IO/StreamExtensions.cs", "using ModelContextProtocol;\nusing System.Buffers;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n#if !NET\nnamespace System.IO;\n\ninternal static class StreamExtensions\n{\n public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return WriteAsyncCore(stream, buffer, cancellationToken);\n\n static async ValueTask WriteAsyncCore(Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n buffer.Span.CopyTo(array);\n await stream.WriteAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n\n public static ValueTask ReadAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.ReadAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return ReadAsyncCore(stream, buffer, cancellationToken);\n static async ValueTask ReadAsyncCore(Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n int bytesRead = await stream.ReadAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n array.AsSpan(0, bytesRead).CopyTo(buffer.Span);\n return bytesRead;\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationEvents.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Represents the authentication events for Model Context Protocol.\n/// \npublic class McpAuthenticationEvents\n{\n /// \n /// Gets or sets the function that is invoked when resource metadata is requested.\n /// \n /// \n /// This function is called when a resource metadata request is made to the protected resource metadata endpoint.\n /// The implementer should set the property\n /// to provide the appropriate metadata for the current request.\n /// \n public Func OnResourceMetadataRequest { get; set; } = context => Task.CompletedTask;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to request real-time notifications from the server whenever a particular resource changes.\n/// \n/// \n/// \n/// The subscription mechanism allows clients to be notified about changes to specific resources\n/// identified by their URI. When a subscribed resource changes, the server sends a notification\n/// to the client with the updated resource information.\n/// \n/// \n/// Subscriptions remain active until explicitly canceled using \n/// or until the connection is terminated.\n/// \n/// \n/// The server may refuse or limit subscriptions based on its capabilities or resource constraints.\n/// \n/// \npublic sealed class SubscribeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the URI of the resource to subscribe to.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resource templates available from the server.\n/// \n/// \n/// The server responds with a containing the available resource templates.\n/// See the schema for details.\n/// \npublic sealed class ListResourceTemplatesRequestParams : PaginatedRequestParams;"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/UnsubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Sent from the client to cancel resource update notifications from the server for a specific resource.\n/// \n/// \n/// \n/// After a client has subscribed to resource updates using , \n/// this message can be sent to stop receiving notifications for a specific resource. \n/// This is useful for conserving resources and network bandwidth when \n/// the client no longer needs to track changes to a particular resource.\n/// \n/// \n/// The unsubscribe operation is idempotent, meaning it can be called multiple times \n/// for the same resource without causing errors, even if there is no active subscription.\n/// \n/// \npublic sealed class UnsubscribeRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to unsubscribe from. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Throw.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace ModelContextProtocol;\n\n/// Provides helper methods for throwing exceptions.\ninternal static class Throw\n{\n // NOTE: Most of these should be replaced with extension statics for the relevant extension\n // type as downlevel polyfills once the C# 14 extension everything feature is available.\n\n public static void IfNull([NotNull] object? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n }\n\n public static void IfNullOrWhiteSpace([NotNull] string? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null || arg.AsSpan().IsWhiteSpace())\n {\n ThrowArgumentNullOrWhiteSpaceException(parameterName);\n }\n }\n\n public static void IfNegative(int arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg < 0)\n {\n Throw(parameterName);\n static void Throw(string? parameterName) => throw new ArgumentOutOfRangeException(parameterName, \"must not be negative.\");\n }\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullOrWhiteSpaceException(string? parameterName)\n {\n if (parameterName is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n\n throw new ArgumentException(\"Value cannot be empty or composed entirely of whitespace.\", parameterName);\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullException(string? parameterName) => throw new ArgumentNullException(parameterName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceUpdatedNotificationParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a subscribed resource changes.\n/// \n/// \n/// \n/// When a client subscribes to resource updates using , the server will\n/// send notifications with this payload whenever the subscribed resource is modified. These notifications\n/// allow clients to maintain synchronized state without needing to poll the server for changes.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceUpdatedNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the URI of the resource that was updated.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\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/Server/McpServerPromptCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of prompts created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating prompts programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerPromptCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerPromptCreateOptions Clone() =>\n new McpServerPromptCreateOptions\n {\n Services = Services,\n Name = Name,\n Title = Title,\n Description = Description,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Tasks/TaskExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class TaskExtensions\n{\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n await WaitAsync((Task)task, timeout, cancellationToken).ConfigureAwait(false);\n return task.Result;\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(task);\n\n if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan)\n {\n throw new ArgumentOutOfRangeException(nameof(timeout));\n }\n\n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n cts.CancelAfter(timeout);\n\n var cancellationTask = new TaskCompletionSource();\n using var _ = cts.Token.Register(tcs => ((TaskCompletionSource)tcs!).TrySetResult(true), cancellationTask);\n await Task.WhenAny(task, cancellationTask.Task).ConfigureAwait(false);\n \n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n throw new TimeoutException();\n }\n }\n\n await task.ConfigureAwait(false);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptMessage.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message within the Model Context Protocol (MCP) system, used for communication between clients and AI models.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be\n/// text, images, audio, or embedded resources.\n/// \n/// \n/// This class is similar to , but with enhanced support for embedding resources from the MCP server.\n/// It serves as a core data structure in the MCP message exchange flow, particularly in prompt formation and model responses.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent complete conversations or prompt sequences. They can be converted to and from \n/// objects using the extension methods and\n/// .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptMessage\n{\n /// \n /// Gets or sets the content of the message, which can be text, image, audio, or an embedded resource.\n /// \n /// \n /// The object contains all the message payload, whether it's simple text,\n /// base64-encoded binary data (for images/audio), or a reference to an embedded resource.\n /// The property indicates the specific content type.\n /// \n [JsonPropertyName(\"content\")]\n public ContentBlock Content { get; set; } = new TextContentBlock { Text = \"\" };\n\n /// \n /// Gets or sets the role of the message sender, specifying whether it's from a \"user\" or an \"assistant\".\n /// \n /// \n /// In the Model Context Protocol, each message must have a clear role assignment to maintain\n /// the conversation flow. User messages represent queries or inputs from users, while assistant\n /// messages represent responses generated by AI models.\n /// \n [JsonPropertyName(\"role\")]\n public Role Role { get; set; } = Role.User;\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/AddTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AddTool\n{\n [McpServerTool(Name = \"add\"), Description(\"Adds two numbers.\")]\n public static string Add(int a, int b) => $\"The sum of {a} and {b} is {a + b}\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientPrompt.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named prompt that can be retrieved from an MCP server and invoked with arguments.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a prompt defined on an MCP server. It allows\n/// retrieving the prompt's content by sending a request to the server with optional arguments.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \n/// Each prompt has a name and optionally a description, and it can be invoked with arguments\n/// to produce customized prompt content from the server.\n/// \n/// \npublic sealed class McpClientPrompt\n{\n private readonly IMcpClient _client;\n\n internal McpClientPrompt(IMcpClient client, Prompt prompt)\n {\n _client = client;\n ProtocolPrompt = prompt;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the prompt,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Prompt ProtocolPrompt { get; }\n\n /// Gets the name of the prompt.\n public string Name => ProtocolPrompt.Name;\n\n /// Gets the title of the prompt.\n public string? Title => ProtocolPrompt.Title;\n\n /// Gets a description of the prompt.\n public string? Description => ProtocolPrompt.Description;\n\n /// \n /// Gets this prompt's content by sending a request to the server with optional arguments.\n /// \n /// Optional arguments to pass to the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to execute this prompt with the provided arguments.\n /// The server will process the request and return a result containing messages or other content.\n /// \n /// \n /// This is a convenience method that internally calls \n /// with this prompt's name and arguments.\n /// \n /// \n public async ValueTask GetAsync(\n IEnumerable>? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n IReadOnlyDictionary? argDict =\n arguments as IReadOnlyDictionary ??\n arguments?.ToDictionary();\n\n return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, serializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/RequestContext.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Provides a context container that provides access to the client request parameters and resources for the request.\n/// \n/// Type of the request parameters specific to each MCP operation.\n/// \n/// The encapsulates all contextual information for handling an MCP request.\n/// This type is typically received as a parameter in handler delegates registered with IMcpServerBuilder,\n/// and may be injected as parameters into s.\n/// \npublic sealed class RequestContext\n{\n /// The server with which this instance is associated.\n private IMcpServer _server;\n\n /// \n /// Initializes a new instance of the class with the specified server.\n /// \n /// The server with which this instance is associated.\n public RequestContext(IMcpServer server)\n {\n Throw.IfNull(server);\n\n _server = server;\n Services = server.Services;\n }\n\n /// Gets or sets the server with which this instance is associated.\n public IMcpServer Server \n {\n get => _server;\n set\n {\n Throw.IfNull(value);\n _server = value;\n }\n }\n\n /// Gets or sets the services associated with this request.\n /// \n /// This may not be the same instance stored in \n /// if was true, in which case this\n /// might be a scoped derived from the server's\n /// .\n /// \n public IServiceProvider? Services { get; set; }\n\n /// Gets or sets the parameters associated with this request.\n public TParams? Params { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpHttpClient.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\n#if NET\nusing System.Net.Http.Json;\n#else\nusing System.Text;\nusing System.Text.Json;\n#endif\n\nnamespace ModelContextProtocol.Client;\n\ninternal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n Debug.Assert(request.Content is null, \"The request body should only be supplied as a JsonRpcMessage\");\n Debug.Assert(message is null || request.Method == HttpMethod.Post, \"All messages should be sent in POST requests.\");\n\n using var content = CreatePostBodyContent(message);\n request.Content = content;\n return await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);\n }\n\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null)\n {\n return null;\n }\n\n#if NET\n return JsonContent.Create(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n#else\n return new StringContent(\n JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage),\n Encoding.UTF8,\n \"application/json\"\n );\n#endif\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Serilog;\nusing TestServerWithHosting.Tools;\n\nLog.Logger = new LoggerConfiguration()\n .MinimumLevel.Verbose() // Capture all log levels\n .WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"logs\", \"TestServer_.log\"),\n rollingInterval: RollingInterval.Day,\n outputTemplate: \"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}\")\n .WriteTo.Debug()\n .WriteTo.Console(standardErrorFromLevel: Serilog.Events.LogEventLevel.Verbose)\n .CreateLogger();\n\ntry\n{\n Log.Information(\"Starting server...\");\n\n var builder = Host.CreateApplicationBuilder(args);\n builder.Services.AddSerilog();\n builder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools();\n\n var app = builder.Build();\n\n await app.RunAsync();\n return 0;\n}\ncatch (Exception ex)\n{\n Log.Fatal(ex, \"Host terminated unexpectedly\");\n return 1;\n}\nfinally\n{\n Log.CloseAndFlush();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCollection.cs", "namespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their URI templates.\npublic sealed class McpServerResourceCollection()\n : McpServerPrimitiveCollection(UriTemplate.UriTemplateComparer.Instance);"], ["/csharp-sdk/src/ModelContextProtocol.Core/RequestHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\ninternal sealed class RequestHandlers : Dictionary>>\n{\n /// \n /// Registers a handler for incoming requests of a specific method in the MCP protocol.\n /// \n /// Type of request payload that will be deserialized from incoming JSON\n /// Type of response payload that will be serialized to JSON (not full RPC response)\n /// Method identifier to register for (e.g., \"tools/list\", \"logging/setLevel\")\n /// Handler function to be called when a request with the specified method identifier is received\n /// The JSON contract governing request parameter deserialization\n /// The JSON contract governing response serialization\n /// \n /// \n /// This method is used internally by the MCP infrastructure to register handlers for various protocol methods.\n /// When an incoming request matches the specified method, the registered handler will be invoked with the\n /// deserialized request parameters.\n /// \n /// \n /// The handler function receives the deserialized request object and a cancellation token, and should return\n /// a response object that will be serialized back to the client.\n /// \n /// \n public void Set(\n string method,\n Func> handler,\n JsonTypeInfo requestTypeInfo,\n JsonTypeInfo responseTypeInfo)\n {\n Throw.IfNull(method);\n Throw.IfNull(handler);\n Throw.IfNull(requestTypeInfo);\n Throw.IfNull(responseTypeInfo);\n\n this[method] = async (request, cancellationToken) =>\n {\n TRequest? typedRequest = JsonSerializer.Deserialize(request.Params, requestTypeInfo);\n object? result = await handler(typedRequest, request.RelatedTransport, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToNode(result, responseTypeInfo);\n };\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class EchoTool\n{\n [McpServerTool(Name = \"echo\"), Description(\"Echoes the message back to the client.\")]\n public static string Echo(string message) => $\"Echo: {message}\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable tool used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP tool for use in the server (as opposed\n/// to , which provides the protocol representation of a tool, and , which\n/// provides a client-side representation of a tool). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithToolsFromAssembly and WithTools. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \npublic abstract class McpServerTool : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerTool()\n {\n }\n\n /// Gets the protocol type for this instance.\n public abstract Tool ProtocolTool { get; }\n\n /// Invokes the .\n /// The request information resulting in the invocation of this tool.\n /// The to monitor for cancellation requests. The default is .\n /// The call response from invoking the tool.\n /// is .\n public abstract ValueTask InvokeAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerTool Create(\n MethodInfo method, \n object? target = null,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerTool Create(\n AIFunction function,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(function, options);\n\n /// \n public override string ToString() => ProtocolTool.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolTool.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StreamClientTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides an implemented around a pair of input/output streams.\n/// \n/// \n/// This transport is useful for scenarios where you already have established streams for communication,\n/// such as custom network protocols, pipe connections, or for testing purposes. It works with any\n/// readable and writable streams.\n/// \npublic sealed class StreamClientTransport : IClientTransport\n{\n private readonly Stream _serverInput;\n private readonly Stream _serverOutput;\n private readonly ILoggerFactory? _loggerFactory;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The stream representing the connected server's input. \n /// Writes to this stream will be sent to the server.\n /// \n /// \n /// The stream representing the connected server's output.\n /// Reads from this stream will receive messages from the server.\n /// \n /// A logger factory for creating loggers.\n public StreamClientTransport(\n Stream serverInput, Stream serverOutput, ILoggerFactory? loggerFactory = null)\n {\n Throw.IfNull(serverInput);\n Throw.IfNull(serverOutput);\n\n _serverInput = serverInput;\n _serverOutput = serverOutput;\n _loggerFactory = loggerFactory;\n }\n\n /// \n public string Name => \"in-memory-stream\";\n\n /// \n public Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n return Task.FromResult(new StreamClientSessionTransport(\n _serverInput,\n _serverOutput,\n encoding: null,\n \"Client (stream)\",\n _loggerFactory));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common request methods used in the MCP protocol.\n/// \npublic static class RequestMethods\n{\n /// \n /// The name of the request method sent from the client to request a list of the server's tools.\n /// \n public const string ToolsList = \"tools/list\";\n\n /// \n /// The name of the request method sent from the client to request that the server invoke a specific tool.\n /// \n public const string ToolsCall = \"tools/call\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's prompts.\n /// \n public const string PromptsList = \"prompts/list\";\n\n /// \n /// The name of the request method sent by the client to get a prompt provided by the server.\n /// \n public const string PromptsGet = \"prompts/get\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resources.\n /// \n public const string ResourcesList = \"resources/list\";\n\n /// \n /// The name of the request method sent from the client to read a specific server resource.\n /// \n public const string ResourcesRead = \"resources/read\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resource templates.\n /// \n public const string ResourcesTemplatesList = \"resources/templates/list\";\n\n /// \n /// The name of the request method sent from the client to request \n /// notifications from the server whenever a particular resource changes.\n /// \n public const string ResourcesSubscribe = \"resources/subscribe\";\n\n /// \n /// The name of the request method sent from the client to request unsubscribing from \n /// notifications from the server.\n /// \n public const string ResourcesUnsubscribe = \"resources/unsubscribe\";\n\n /// \n /// The name of the request method sent from the server to request a list of the client's roots.\n /// \n public const string RootsList = \"roots/list\";\n\n /// \n /// The name of the request method sent by either endpoint to check that the connected endpoint is still alive.\n /// \n public const string Ping = \"ping\";\n\n /// \n /// The name of the request method sent from the client to the server to adjust the logging level.\n /// \n /// \n /// This request allows clients to control which log messages they receive from the server\n /// by setting a minimum severity threshold. After processing this request, the server will\n /// send log messages with severity at or above the specified level to the client as\n /// notifications.\n /// \n public const string LoggingSetLevel = \"logging/setLevel\";\n\n /// \n /// The name of the request method sent from the client to the server to ask for completion suggestions.\n /// \n /// \n /// This is used to provide autocompletion-like functionality for arguments in a resource reference or a prompt template.\n /// The client provides a reference (resource or prompt), argument name, and partial value, and the server \n /// responds with matching completion options.\n /// \n public const string CompletionComplete = \"completion/complete\";\n\n /// \n /// The name of the request method sent from the server to sample an large language model (LLM) via the client.\n /// \n /// \n /// This request allows servers to utilize an LLM available on the client side to generate text or image responses\n /// based on provided messages. It is part of the sampling capability in the Model Context Protocol and enables servers to access\n /// client-side AI models without needing direct API access to those models.\n /// \n public const string SamplingCreateMessage = \"sampling/createMessage\";\n\n /// \n /// The name of the request method sent from the client to the server to elicit additional information from the user via the client.\n /// \n /// \n /// This request is used when the server needs more information from the client to proceed with a task or interaction.\n /// Servers can request structured data from users, with optional JSON schemas to validate responses.\n /// \n public const string ElicitationCreate = \"elicitation/create\";\n\n /// \n /// The name of the request method sent from the client to the server when it first connects, asking it initialize.\n /// \n /// \n /// The initialize request is the first request sent by the client to the server. It provides client information\n /// and capabilities to the server during connection establishment. The server responds with its own capabilities\n /// and information, establishing the protocol version and available features for the session.\n /// \n public const string Initialize = \"initialize\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as tools in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as tools that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to when the tool is invoked rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided when the tool is invoked rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerToolAttribute : Attribute\n{\n // Defaults based on the spec\n private const bool DestructiveDefault = true;\n private const bool IdempotentDefault = false;\n private const bool OpenWorldDefault = true;\n private const bool ReadOnlyDefault = false;\n\n // Nullable backing fields so we can distinguish\n internal bool? _destructive;\n internal bool? _idempotent;\n internal bool? _openWorld;\n internal bool? _readOnly;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerToolAttribute()\n {\n }\n\n /// Gets the name of the tool.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Destructive \n {\n get => _destructive ?? DestructiveDefault; \n set => _destructive = value; \n }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Idempotent \n {\n get => _idempotent ?? IdempotentDefault;\n set => _idempotent = value; \n }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool OpenWorld\n {\n get => _openWorld ?? OpenWorldDefault; \n set => _openWorld = value; \n }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool ReadOnly \n {\n get => _readOnly ?? ReadOnlyDefault; \n set => _readOnly = value; \n }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common notification methods used in the MCP protocol.\n/// \npublic static class NotificationMethods\n{\n /// \n /// The name of notification sent by a server when the list of available tools changes.\n /// \n /// \n /// This notification informs clients that the set of available tools has been modified.\n /// Changes may include tools being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their tool list by calling the appropriate \n /// method to get the updated list of tools.\n /// \n public const string ToolListChangedNotification = \"notifications/tools/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available prompts changes.\n /// \n /// \n /// This notification informs clients that the set of available prompts has been modified.\n /// Changes may include prompts being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their prompt list by calling the appropriate \n /// method to get the updated list of prompts.\n /// \n public const string PromptListChangedNotification = \"notifications/prompts/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available resources changes.\n /// \n /// \n /// This notification informs clients that the set of available resources has been modified.\n /// Changes may include resources being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their resource list by calling the appropriate \n /// method to get the updated list of resources.\n /// \n public const string ResourceListChangedNotification = \"notifications/resources/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a resource is updated.\n /// \n /// \n /// This notification is used to inform clients about changes to a specific resource they have subscribed to.\n /// When a resource is updated, the server sends this notification to all clients that have subscribed to that resource.\n /// \n public const string ResourceUpdatedNotification = \"notifications/resources/updated\";\n\n /// \n /// The name of the notification sent by the client when roots have been updated.\n /// \n /// \n /// \n /// This notification informs the server that the client's \"roots\" have changed. \n /// Roots define the boundaries of where servers can operate within the filesystem, \n /// allowing them to understand which directories and files they have access to. Servers \n /// can request the list of roots from supporting clients and receive notifications when that list changes.\n /// \n /// \n /// After receiving this notification, servers may refresh their knowledge of roots by calling the appropriate \n /// method to get the updated list of roots from the client.\n /// \n /// \n public const string RootsListChangedNotification = \"notifications/roots/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a log message is generated.\n /// \n /// \n /// \n /// This notification is used by the server to send log messages to clients. Log messages can include\n /// different severity levels, such as debug, info, warning, or error, and an optional logger name to\n /// identify the source component.\n /// \n /// \n /// The minimum logging level that triggers notifications can be controlled by clients using the\n /// request. If no level has been set by a client, \n /// the server may determine which messages to send based on its own configuration.\n /// \n /// \n public const string LoggingMessageNotification = \"notifications/message\";\n\n /// \n /// The name of the notification sent from the client to the server after initialization has finished.\n /// \n /// \n /// \n /// This notification is sent by the client after it has received and processed the server's response to the \n /// request. It signals that the client is ready to begin normal operation \n /// and that the initialization phase is complete.\n /// \n /// \n /// After receiving this notification, the server can begin sending notifications and processing\n /// further requests from the client.\n /// \n /// \n public const string InitializedNotification = \"notifications/initialized\";\n\n /// \n /// The name of the notification sent to inform the receiver of a progress update for a long-running request.\n /// \n /// \n /// \n /// This notification provides updates on the progress of long-running operations. It includes\n /// a progress token that associates the notification with a specific request, the current progress value,\n /// and optionally, a total value and a descriptive message.\n /// \n /// \n /// Progress notifications may be sent by either the client or the server, depending on the context.\n /// Progress notifications enable clients to display progress indicators for operations that might take\n /// significant time to complete, such as large file uploads, complex computations, or resource-intensive\n /// processing tasks.\n /// \n /// \n public const string ProgressNotification = \"notifications/progress\";\n\n /// \n /// The name of the notification sent to indicate that a previously-issued request should be canceled.\n /// \n /// \n /// \n /// From the issuer's perspective, the request should still be in-flight. However, due to communication latency,\n /// it is always possible that this notification may arrive after the request has already finished.\n /// \n /// \n /// This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n /// \n /// \n /// A client must not attempt to cancel its `initialize` request.\n /// \n /// \n public const string CancelledNotification = \"notifications/cancelled\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompletionsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the completions capability for providing auto-completion suggestions\n/// for prompt arguments and resource references.\n/// \n/// \n/// \n/// When enabled, this capability allows a Model Context Protocol server to provide \n/// auto-completion suggestions. This capability is advertised to clients during the initialize handshake.\n/// \n/// \n/// The primary function of this capability is to improve the user experience by offering\n/// contextual suggestions for argument values or resource identifiers based on partial input.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompletionsCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for completion requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler receives a reference type (e.g., \"ref/prompt\" or \"ref/resource\") and the current argument value,\n /// and should return appropriate completion suggestions.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable prompt used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP prompt for use in the server (as opposed\n/// to , which provides the protocol representation of a prompt, and , which\n/// provides a client-side representation of a prompt). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithPromptsFromAssembly and WithPrompts. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to \n/// rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerPrompt : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerPrompt()\n {\n }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolPrompt property represents the underlying prompt definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the prompt's name,\n /// description, and acceptable arguments.\n /// \n public abstract Prompt ProtocolPrompt { get; }\n\n /// \n /// Gets the prompt, rendering it with the provided request parameters and returning the prompt result.\n /// \n /// \n /// The request context containing information about the prompt invocation, including any arguments\n /// passed to the prompt. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the prompt content and messages.\n /// \n /// is .\n /// The prompt implementation returns or an unsupported result type.\n public abstract ValueTask GetAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerPrompt Create(\n MethodInfo method, \n object? target = null,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerPrompt Create(\n AIFunction function,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(function, options);\n\n /// \n public override string ToString() => ProtocolPrompt.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolPrompt.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DestinationBoundMcpServer.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class DestinationBoundMcpServer(McpServer server, ITransport? transport) : IMcpServer\n{\n public string EndpointName => server.EndpointName;\n public string? SessionId => transport?.SessionId ?? server.SessionId;\n public ClientCapabilities? ClientCapabilities => server.ClientCapabilities;\n public Implementation? ClientInfo => server.ClientInfo;\n public McpServerOptions ServerOptions => server.ServerOptions;\n public IServiceProvider? Services => server.Services;\n public LoggingLevel? LoggingLevel => server.LoggingLevel;\n\n public ValueTask DisposeAsync() => server.DisposeAsync();\n\n public IAsyncDisposable RegisterNotificationHandler(string method, Func handler) => server.RegisterNotificationHandler(method, handler);\n\n // This will throw because the server must already be running for this class to be constructed, but it should give us a good Exception message.\n public Task RunAsync(CancellationToken cancellationToken) => server.RunAsync(cancellationToken);\n\n public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Debug.Assert(message.RelatedTransport is null);\n message.RelatedTransport = transport;\n return server.SendMessageAsync(message, cancellationToken);\n }\n\n public Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)\n {\n Debug.Assert(request.RelatedTransport is null);\n request.RelatedTransport = transport;\n return server.SendRequestAsync(request, cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ClientOAuthOptions.cs", "namespace ModelContextProtocol.Authentication;\n\n/// \n/// Provides configuration options for the .\n/// \npublic sealed class ClientOAuthOptions\n{\n /// \n /// Gets or sets the OAuth redirect URI.\n /// \n public required Uri RedirectUri { get; set; }\n\n /// \n /// Gets or sets the OAuth client ID. If not provided, the client will attempt to register dynamically.\n /// \n public string? ClientId { get; set; }\n\n /// \n /// Gets or sets the OAuth client secret.\n /// \n /// \n /// This is optional for public clients or when using PKCE without client authentication.\n /// \n public string? ClientSecret { get; set; }\n\n /// \n /// Gets or sets the OAuth scopes to request.\n /// \n /// \n /// \n /// When specified, these scopes will be used instead of the scopes advertised by the protected resource.\n /// If not specified, the provider will use the scopes from the protected resource metadata.\n /// \n /// \n /// Common OAuth scopes include \"openid\", \"profile\", \"email\", etc.\n /// \n /// \n public IEnumerable? Scopes { get; set; }\n\n /// \n /// Gets or sets the authorization redirect delegate for handling the OAuth authorization flow.\n /// \n /// \n /// \n /// This delegate is responsible for handling the OAuth authorization URL and obtaining the authorization code.\n /// If not specified, a default implementation will be used that prompts the user to enter the code manually.\n /// \n /// \n /// Custom implementations might open a browser, start an HTTP listener, or use other mechanisms to capture\n /// the authorization code from the OAuth redirect.\n /// \n /// \n public AuthorizationRedirectDelegate? AuthorizationRedirectDelegate { get; set; }\n\n /// \n /// Gets or sets the authorization server selector function.\n /// \n /// \n /// \n /// This function is used to select which authorization server to use when multiple servers are available.\n /// If not specified, the first available server will be selected.\n /// \n /// \n /// The function receives a list of available authorization server URIs and should return the selected server,\n /// or null if no suitable server is found.\n /// \n /// \n public Func, Uri?>? AuthServerSelector { get; set; }\n\n /// \n /// Gets or sets the client name to use during dynamic client registration.\n /// \n /// \n /// This is a human-readable name for the client that may be displayed to users during authorization.\n /// Only used when a is not specified.\n /// \n public string? ClientName { get; set; }\n\n /// \n /// Gets or sets the client URI to use during dynamic client registration.\n /// \n /// \n /// This should be a URL pointing to the client's home page or information page.\n /// Only used when a is not specified.\n /// \n public Uri? ClientUri { get; set; }\n\n /// \n /// Gets or sets additional parameters to include in the query string of the OAuth authorization request\n /// providing extra information or fulfilling specific requirements of the OAuth provider.\n /// \n /// \n /// \n /// Parameters specified cannot override or append to any automatically set parameters like the \"redirect_uri\"\n /// which should instead be configured via .\n /// \n /// \n public IDictionary AdditionalAuthorizationParameters { get; set; } = new Dictionary();\n}"], ["/csharp-sdk/src/ModelContextProtocol/McpServerServiceCollectionExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides extension methods for configuring MCP servers with dependency injection.\n/// \npublic static class McpServerServiceCollectionExtensions\n{\n /// \n /// Adds the Model Context Protocol (MCP) server to the service collection with default options.\n /// \n /// The to add the server to.\n /// Optional callback to configure the .\n /// An that can be used to further configure the MCP server.\n\n public static IMcpServerBuilder AddMcpServer(this IServiceCollection services, Action? configureOptions = null)\n {\n services.AddOptions();\n services.TryAddEnumerable(ServiceDescriptor.Transient, McpServerOptionsSetup>());\n if (configureOptions is not null)\n {\n services.Configure(configureOptions);\n }\n\n return new DefaultMcpServerBuilder(services);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationExtensions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.AspNetCore.Authentication;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Extension methods for adding MCP authorization support to ASP.NET Core applications.\n/// \npublic static class McpAuthenticationExtensions\n{\n /// \n /// Adds MCP authorization support to the application.\n /// \n /// The authentication builder.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n Action? configureOptions = null)\n {\n return AddMcp(\n builder,\n McpAuthenticationDefaults.AuthenticationScheme,\n McpAuthenticationDefaults.DisplayName,\n configureOptions);\n }\n\n /// \n /// Adds MCP authorization support to the application with a custom scheme name.\n /// \n /// The authentication builder.\n /// The authentication scheme name to use.\n /// The display name for the authentication scheme.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n string authenticationScheme,\n string displayName,\n Action? configureOptions = null)\n {\n return builder.AddScheme(\n authenticationScheme,\n displayName,\n configureOptions);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingMessage.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued to or received from an LLM API within the Model Context Protocol.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be text or images.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent prompts or queries for LLM sampling. They form the core data structure for text generation requests\n/// within the Model Context Protocol.\n/// \n/// \n/// While similar to , the is focused on direct LLM sampling\n/// operations rather than the enhanced resource embedding capabilities provided by .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class SamplingMessage\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the role of the message sender, indicating whether it's from a \"user\" or an \"assistant\".\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerPrompt.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building prompts that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner prompt instance.\n/// \npublic abstract class DelegatingMcpServerPrompt : McpServerPrompt\n{\n private readonly McpServerPrompt _innerPrompt;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner prompt wrapped by this delegating prompt.\n protected DelegatingMcpServerPrompt(McpServerPrompt innerPrompt)\n {\n Throw.IfNull(innerPrompt);\n _innerPrompt = innerPrompt;\n }\n\n /// \n public override Prompt ProtocolPrompt => _innerPrompt.ProtocolPrompt;\n\n /// \n public override ValueTask GetAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerPrompt.GetAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerPrompt.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerTool.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building tools that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner tool instance.\n/// \npublic abstract class DelegatingMcpServerTool : McpServerTool\n{\n private readonly McpServerTool _innerTool;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner tool wrapped by this delegating tool.\n protected DelegatingMcpServerTool(McpServerTool innerTool)\n {\n Throw.IfNull(innerTool);\n _innerTool = innerTool;\n }\n\n /// \n public override Tool ProtocolTool => _innerTool.ProtocolTool;\n\n /// \n public override ValueTask InvokeAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerTool.InvokeAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerTool.ToString();\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Channels/ChannelExtensions.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading.Channels;\n\ninternal static class ChannelExtensions\n{\n public static async IAsyncEnumerable ReadAllAsync(this ChannelReader reader, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))\n {\n while (reader.TryRead(out var item))\n {\n yield return item;\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's response to a request, \n/// containing suggested values for a given argument.\n/// \n/// \n/// \n/// is returned by the server in response to a \n/// request from the client. It provides suggested completions or valid values for a specific argument in a tool or resource reference.\n/// \n/// \n/// The result contains a object with suggested values, pagination information,\n/// and the total number of available completions. This is similar to auto-completion functionality in code editors.\n/// \n/// \n/// Clients typically use this to implement auto-suggestion features when users are inputting parameters\n/// for tool calls or resource references.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteResult : Result\n{\n /// \n /// Gets or sets the completion object containing the suggested values and pagination information.\n /// \n /// \n /// If no completions are available for the given input, the \n /// collection will be empty.\n /// \n [JsonPropertyName(\"completion\")]\n public Completion Completion { get; set; } = new Completion();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring HTTP MCP servers via dependency injection.\n/// \npublic static class HttpMcpServerBuilderExtensions\n{\n /// \n /// Adds the services necessary for \n /// to handle MCP requests and sessions using the MCP Streamable HTTP transport. For more information on configuring the underlying HTTP server\n /// to control things like port binding custom TLS certificates, see the Minimal APIs quick reference.\n /// \n /// The builder instance.\n /// Configures options for the Streamable HTTP transport. This allows configuring per-session\n /// and running logic before and after a session.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithHttpTransport(this IMcpServerBuilder builder, Action? configureOptions = null)\n {\n ArgumentNullException.ThrowIfNull(builder);\n\n builder.Services.TryAddSingleton();\n builder.Services.TryAddSingleton();\n builder.Services.AddHostedService();\n builder.Services.AddDataProtection();\n\n if (configureOptions is not null)\n {\n builder.Services.Configure(configureOptions);\n }\n\n return builder;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Annotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents annotations that can be attached to content, resources, and resource templates.\n/// \n/// \n/// Annotations enable filtering and prioritization of content for different audiences.\n/// See the schema for details.\n/// \npublic sealed class Annotations\n{\n /// \n /// Gets or sets the intended audience for this content as an array of values.\n /// \n [JsonPropertyName(\"audience\")]\n public IList? Audience { get; init; }\n\n /// \n /// Gets or sets a value indicating how important this data is for operating the server.\n /// \n /// \n /// The value is a floating-point number between 0 and 1, where 0 represents the lowest priority\n /// 1 represents highest priority.\n /// \n [JsonPropertyName(\"priority\")]\n public float? Priority { get; init; }\n\n /// \n /// Gets or sets the moment the resource was last modified.\n /// \n /// \n /// The corresponding JSON should be an ISO 8601 formatted string (e.g., \\\"2025-01-12T15:00:58Z\\\").\n /// Examples: last activity timestamp in an open file, timestamp when the resource was attached, etc.\n /// \n [JsonPropertyName(\"lastModified\")]\n public DateTimeOffset? LastModified { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/SingleSessionMcpServerHostedService.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Hosted service for a single-session (e.g. stdio) MCP server.\n/// \n/// The server representing the session being hosted.\n/// \n/// The host's application lifetime. If available, it will have termination requested when the session's run completes.\n/// \ninternal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime? lifetime = null) : BackgroundService\n{\n /// \n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n try\n {\n await session.RunAsync(stoppingToken).ConfigureAwait(false);\n }\n finally\n {\n lifetime?.StopApplication();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpException.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents an exception that is thrown when an Model Context Protocol (MCP) error occurs.\n/// \n/// \n/// This exception is used to represent failures to do with protocol-level concerns, such as invalid JSON-RPC requests,\n/// invalid parameters, or internal errors. It is not intended to be used for application-level errors.\n/// or from a may be \n/// propagated to the remote endpoint; sensitive information should not be included. If sensitive details need\n/// to be included, a different exception type should be used.\n/// \npublic class McpException : Exception\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpException()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public McpException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n public McpException(string message, Exception? innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// A .\n public McpException(string message, McpErrorCode errorCode) : this(message, null, errorCode)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message, inner exception, and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n /// A .\n public McpException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)\n {\n ErrorCode = errorCode;\n }\n\n /// \n /// Gets the error code associated with this exception.\n /// \n /// \n /// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:\n /// \n /// -32700: Parse error - Invalid JSON received\n /// -32600: Invalid request - The JSON is not a valid Request object\n /// -32601: Method not found - The method does not exist or is not available\n /// -32602: Invalid params - Invalid method parameters\n /// -32603: Internal error - Internal JSON-RPC error\n /// \n /// \n public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientTransportOptions.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class StdioClientTransportOptions\n{\n /// \n /// Gets or sets the command to execute to start the server process.\n /// \n public required string Command\n {\n get;\n set\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Command cannot be null or empty.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the arguments to pass to the server process when it is started.\n /// \n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the working directory for the server process.\n /// \n public string? WorkingDirectory { get; set; }\n\n /// \n /// Gets or sets environment variables to set for the server process.\n /// \n /// \n /// \n /// This property allows you to specify environment variables that will be set in the server process's\n /// environment. This is useful for passing configuration, authentication information, or runtime flags\n /// to the server without modifying its code.\n /// \n /// \n /// By default, when starting the server process, the server process will inherit the current environment's variables,\n /// as discovered via . After those variables are found, the entries\n /// in this dictionary are used to augment and overwrite the entries read from the environment.\n /// That includes removing the variables for any of this collection's entries with a null value.\n /// \n /// \n public IDictionary? EnvironmentVariables { get; set; }\n\n /// \n /// Gets or sets the timeout to wait for the server to shut down gracefully.\n /// \n /// \n /// \n /// This property dictates how long the client should wait for the server process to exit cleanly during shutdown\n /// before forcibly terminating it. This balances between giving the server enough time to clean up \n /// resources and not hanging indefinitely if a server process becomes unresponsive.\n /// \n /// \n /// The default is five seconds.\n /// \n /// \n public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5);\n\n /// \n /// Gets or sets a callback that is invoked for each line of stderr received from the server process.\n /// \n public Action? StandardErrorLines { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerFactory.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a factory for creating instances.\n/// \n/// \n/// This is the recommended way to create instances.\n/// The factory handles proper initialization of server instances with the required dependencies.\n/// \npublic static class McpServerFactory\n{\n /// \n /// Creates a new instance of an .\n /// \n /// Transport to use for the server representing an already-established MCP session.\n /// Configuration options for this server, including capabilities. \n /// Logger factory to use for logging. If null, logging will be disabled.\n /// Optional service provider to create new instances of tools and other dependencies.\n /// An instance that should be disposed when no longer needed.\n /// is .\n /// is .\n public static IMcpServer Create(\n ITransport transport,\n McpServerOptions serverOptions,\n ILoggerFactory? loggerFactory = null,\n IServiceProvider? serviceProvider = null)\n {\n Throw.IfNull(transport);\n Throw.IfNull(serverOptions);\n\n return new McpServer(transport, serverOptions, loggerFactory, serviceProvider);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ClientCapabilities.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a client may support.\n/// \n/// \n/// \n/// Capabilities define the features and functionality that a client can handle when communicating with an MCP server.\n/// These are advertised to the server during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ClientCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the client supports.\n /// \n /// \n /// \n /// The dictionary allows clients to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Servers should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets the client's roots capability, which are entry points for resource navigation.\n /// \n /// \n /// \n /// When is non-, the client indicates that it can respond to \n /// server requests for listing root URIs. Root URIs serve as entry points for resource navigation in the protocol.\n /// \n /// \n /// The server can use to request the list of\n /// available roots from the client, which will trigger the client's .\n /// \n /// \n [JsonPropertyName(\"roots\")]\n public RootsCapability? Roots { get; set; }\n\n /// \n /// Gets or sets the client's sampling capability, which indicates whether the client \n /// supports issuing requests to an LLM on behalf of the server.\n /// \n [JsonPropertyName(\"sampling\")]\n public SamplingCapability? Sampling { get; set; }\n\n /// \n /// Gets or sets the client's elicitation capability, which indicates whether the client \n /// supports elicitation of additional information from the user on behalf of the server.\n /// \n [JsonPropertyName(\"elicitation\")]\n public ElicitationCapability? Elicitation { get; set; }\n\n /// Gets or sets notification handlers to register with the client.\n /// \n /// \n /// When constructed, the client will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The client will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the client to respond to server-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the client for the lifetime of the client.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing QuickstartWeatherServer.Tools;\nusing System.Net.Http.Headers;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools();\n\nbuilder.Logging.AddConsole(options =>\n{\n options.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nbuilder.Services.AddSingleton(_ =>\n{\n var client = new HttpClient { BaseAddress = new Uri(\"https://api.weather.gov\") };\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n return client;\n});\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseResponseStreamTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as \n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \n/// The response stream to write MCP JSON-RPC messages as SSE events to.\n/// \n/// The relative or absolute URI the client should use to post MCP JSON-RPC messages for this session.\n/// These messages should be passed to .\n/// Defaults to \"/message\".\n/// \n/// The identifier corresponding to the current MCP session.\npublic sealed class SseResponseStreamTransport(Stream sseResponseStream, string? messageEndpoint = \"/message\", string? sessionId = null) : ITransport\n{\n private readonly SseWriter _sseWriter = new(messageEndpoint);\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private bool _isConnected;\n\n /// \n /// Starts the transport and writes the JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task RunAsync(CancellationToken cancellationToken)\n {\n _isConnected = true;\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n /// \n public string? SessionId { get; } = sessionId;\n\n /// \n public async ValueTask DisposeAsync()\n {\n _isConnected = false;\n _incomingChannel.Writer.TryComplete();\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles incoming JSON-RPC messages received on the /message endpoint.\n /// \n /// The JSON-RPC message received from the client.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation to buffer the JSON-RPC message for processing.\n /// Thrown when there is an attempt to process a message before calling .\n /// \n /// \n /// This method is the entry point for processing client-to-server communication in the SSE transport model. \n /// While the SSE protocol itself is unidirectional (server to client), this method allows bidirectional \n /// communication by handling HTTP POST requests sent to the message endpoint.\n /// \n /// \n /// When a client sends a JSON-RPC message to the /message endpoint, the server calls this method to\n /// process the message and make it available to the MCP server via the channel.\n /// \n /// \n /// This method validates that the transport is connected before processing the message, ensuring proper\n /// sequencing of operations in the transport lifecycle.\n /// \n /// \n public async Task OnMessageReceivedAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n Throw.IfNull(message);\n\n if (!_isConnected)\n {\n throw new InvalidOperationException($\"Transport is not connected. Make sure to call {nameof(RunAsync)} first.\");\n }\n\n await _incomingChannel.Writer.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/NullableAttributes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n /// Specifies that null is allowed as an input even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class AllowNullAttribute : Attribute;\n\n /// Specifies that null is disallowed as an input even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class DisallowNullAttribute : Attribute;\n\n /// Specifies that an output may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class MaybeNullAttribute : Attribute;\n\n /// Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class NotNullAttribute : Attribute;\n\n /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class MaybeNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter may be null.\n /// \n public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class NotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter will not be null.\n /// \n public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that the output will be non-null if the named parameter is non-null.\n [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]\n internal sealed class NotNullIfNotNullAttribute : Attribute\n {\n /// Initializes the attribute with the associated parameter name.\n /// \n /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.\n /// \n public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;\n\n /// Gets the associated parameter name.\n public string ParameterName { get; }\n }\n\n /// Applied to a method that will never return under any circumstance.\n [AttributeUsage(AttributeTargets.Method, Inherited = false)]\n internal sealed class DoesNotReturnAttribute : Attribute;\n\n /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class DoesNotReturnIfAttribute : Attribute\n {\n /// Initializes the attribute with the specified parameter value.\n /// \n /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to\n /// the associated parameter matches this value.\n /// \n public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;\n\n /// Gets the condition parameter value.\n public bool ParameterValue { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullAttribute : Attribute\n {\n /// Initializes the attribute with a field or property member.\n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullAttribute(string member) => Members = [member];\n\n /// Initializes the attribute with the list of field and property members.\n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullAttribute(params string[] members) => Members = members;\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition and a field or property member.\n /// \n /// The return value condition. If the method returns this value, the associated field or property member will not be null.\n /// \n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, string member)\n {\n ReturnValue = returnValue;\n Members = [member];\n }\n\n /// Initializes the attribute with the specified return value condition and list of field and property members.\n /// \n /// The return value condition. If the method returns this value, the associated field and property members will not be null.\n /// \n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, params string[] members)\n {\n ReturnValue = returnValue;\n Members = members;\n }\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client capability that enables root resource discovery in the Model Context Protocol.\n/// \n/// \n/// \n/// When present in , it indicates that the client supports listing\n/// root URIs that serve as entry points for resource navigation.\n/// \n/// \n/// The roots capability establishes a mechanism for servers to discover and access the hierarchical \n/// structure of resources provided by a client. Root URIs represent top-level entry points from which\n/// servers can navigate to access specific resources.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsCapability\n{\n /// \n /// Gets or sets whether the client supports notifications for changes to the roots list.\n /// \n /// \n /// When set to , the client can notify servers when roots are added, \n /// removed, or modified, allowing servers to refresh their roots cache accordingly.\n /// This enables servers to stay synchronized with client-side changes to available roots.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client sends a request to retrieve available roots.\n /// The handler receives request parameters and should return a containing the collection of available roots.\n /// \n [JsonIgnore]\n public Func>? RootsHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpServerTransportOptions.cs", "using Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\n/// \n/// Configuration options for .\n/// which implements the Streaming HTTP transport for the Model Context Protocol.\n/// See the protocol specification for details on the Streamable HTTP transport. \n/// \npublic class HttpServerTransportOptions\n{\n /// \n /// Gets or sets an optional asynchronous callback to configure per-session \n /// with access to the of the request that initiated the session.\n /// \n public Func? ConfigureSessionOptions { get; set; }\n\n /// \n /// Gets or sets an optional asynchronous callback for running new MCP sessions manually.\n /// This is useful for running logic before a sessions starts and after it completes.\n /// \n public Func? RunSessionHandler { get; set; }\n\n /// \n /// Gets or sets whether the server should run in a stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process.\n /// \n /// \n /// If , the \"/sse\" endpoint will be disabled, and client information will be round-tripped as part\n /// of the \"MCP-Session-Id\" header instead of stored in memory. Unsolicited server-to-client messages and all server-to-client\n /// requests are also unsupported, because any responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// Defaults to .\n /// \n public bool Stateless { get; set; }\n\n /// \n /// Gets or sets whether the server should use a single execution context for the entire session.\n /// If , handlers like tools get called with the \n /// belonging to the corresponding HTTP request which can change throughout the MCP session.\n /// If , handlers will get called with the same \n /// used to call and .\n /// \n /// \n /// Enabling a per-session can be useful for setting variables\n /// that persist for the entire session, but it prevents you from using IHttpContextAccessor in handlers.\n /// Defaults to .\n /// \n public bool PerSessionExecutionContext { get; set; }\n\n /// \n /// Gets or sets the duration of time the server will wait between any active requests before timing out an MCP session.\n /// \n /// \n /// This is checked in background every 5 seconds. A client trying to resume a session will receive a 404 status code\n /// and should restart their session. A client can keep their session open by keeping a GET request open.\n /// Defaults to 2 hours.\n /// \n public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromHours(2);\n\n /// \n /// Gets or sets maximum number of idle sessions to track in memory. This is used to limit the number of sessions that can be idle at once.\n /// \n /// \n /// Past this limit, the server will log a critical error and terminate the oldest idle sessions even if they have not reached\n /// their until the idle session count is below this limit. Clients that keep their session open by\n /// keeping a GET request open will not count towards this limit.\n /// Defaults to 100,000 sessions.\n /// \n public int MaxIdleSessionCount { get; set; } = 100_000;\n\n /// \n /// Used for testing the .\n /// \n public TimeProvider TimeProvider { get; set; } = TimeProvider.System;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a request from the server,\n/// containing available roots.\n/// \n/// \n/// \n/// This result is returned when a server sends a request to discover \n/// available roots on the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListRootsResult : Result\n{\n /// \n /// Gets or sets the list of root URIs provided by the client.\n /// \n /// \n /// This collection contains all available root URIs and their associated metadata.\n /// Each root serves as an entry point for resource navigation in the Model Context Protocol.\n /// \n [JsonPropertyName(\"roots\")]\n public required IReadOnlyList Roots { get; init; }\n}\n"], ["/csharp-sdk/src/Common/CancellableStreamReader/TextReaderExtensions.cs", "namespace System.IO;\n\ninternal static class TextReaderExtensions\n{\n public static ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n {\n if (reader is CancellableStreamReader cancellableReader)\n {\n return cancellableReader.ReadLineAsync(cancellationToken)!;\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n return new ValueTask(reader.ReadLineAsync());\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Root.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a root URI and its metadata in the Model Context Protocol.\n/// \n/// \n/// Root URIs serve as entry points for resource navigation, typically representing\n/// top-level directories or container resources that can be accessed and traversed.\n/// Roots provide a hierarchical structure for organizing and accessing resources within the protocol.\n/// Each root has a URI that uniquely identifies it and optional metadata like a human-readable name.\n/// \npublic sealed class Root\n{\n /// \n /// Gets or sets the URI of the root.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for the root.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n\n /// \n /// Gets or sets additional metadata for the root.\n /// \n /// \n /// This is reserved by the protocol for future use.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonElement? Meta { get; init; }\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/TinyImageTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class TinyImageTool\n{\n [McpServerTool(Name = \"getTinyImage\"), Description(\"Get a tiny image from the server\")]\n public static IEnumerable GetTinyImage() => [\n new TextContent(\"This is a tiny image:\"),\n new DataContent(MCP_TINY_IMAGE),\n new TextContent(\"The image above is the MCP tiny image.\")\n ];\n\n internal const string MCP_TINY_IMAGE =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAKsGlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgOfe9JDQEiIgJfQmSCeAlBBaAAXpYCMkAUKJMRBU7MriClZURLCs6KqIgo0idizYFsWC3QVZBNR1sWDDlXeBQ9jdd9575805c+a7c+efmf+e/z9nLgCdKZDJMlF1gCxpjjwyyI8dn5DIJvUABRiY0kBdIMyWcSMiwgCTUft3+dgGyJC9YzuU69/f/1fREImzhQBIBMbJomxhFsbHMe0TyuQ5ALg9mN9kbo5siK9gzJRjDWL8ZIhTR7hviJOHGY8fjomO5GGsDUCmCQTyVACaKeZn5wpTsTw0f4ztpSKJFGPsGbyzsmaLMMbqgiUWI8N4KD8n+S95Uv+WM1mZUyBIVfLIXoaF7C/JlmUK5v+fn+N/S1amYrSGOaa0NHlwJGaxvpAHGbNDlSxNnhI+yhLRcPwwpymCY0ZZmM1LHGWRwD9UuTZzStgop0gC+co8OfzoURZnB0SNsnx2pLJWipzHHWWBfKyuIiNG6U8T85X589Ki40Y5VxI7ZZSzM6JCx2J4Sr9cEansXywN8hurG6jce1b2X/Yr4SvX5qRFByv3LhjrXyzljuXMjlf2JhL7B4zFxCjjZTl+ylqyzAhlvDgzSOnPzo1Srs3BDuTY2gjlN0wXhESMMoRBELAhBjIhB+QggECQgBTEOeJ5Q2cUeLNl8+WS1LQcNhe7ZWI2Xyq0m8B2tHd0Bhi6syNH4j1r+C4irGtjvhWVAF4nBgcHT475Qm4BHEkCoNaO+SxnAKh3A1w5JVTIc0d8Q9cJCEAFNWCCDhiACViCLTiCK3iCLwRACIRDNCTATBBCGmRhnc+FhbAMCqAI1sNmKIOdsBv2wyE4CvVwCs7DZbgOt+AePIZ26IJX0AcfYQBBEBJCRxiIDmKImCE2iCPCQbyRACQMiUQSkCQkFZEiCmQhsgIpQoqRMmQXUokcQU4g55GrSCvyEOlAepF3yFcUh9JQJqqPmqMTUQ7KRUPRaHQGmorOQfPQfHQtWopWoAfROvQ8eh29h7ajr9B+HOBUcCycEc4Wx8HxcOG4RFwKTo5bjCvEleAqcNW4Rlwz7g6uHfca9wVPxDPwbLwt3hMfjI/BC/Fz8Ivxq/Fl+P34OvxF/B18B74P/51AJ+gRbAgeBD4hnpBKmEsoIJQQ9hJqCZcI9whdhI9EIpFFtCC6EYOJCcR04gLiauJ2Yg3xHLGV2EnsJ5FIOiQbkhcpnCQg5ZAKSFtJB0lnSbdJXaTPZBWyIdmRHEhOJEvJy8kl5APkM+Tb5G7yAEWdYkbxoIRTRJT5lHWUPZRGyk1KF2WAqkG1oHpRo6np1GXUUmo19RL1CfW9ioqKsYq7ylQVicpSlVKVwypXVDpUvtA0adY0Hm06TUFbS9tHO0d7SHtPp9PN6b70RHoOfS29kn6B/oz+WZWhaqfKVxWpLlEtV61Tva36Ro2iZqbGVZuplqdWonZM7abaa3WKurk6T12gvli9XP2E+n31fg2GhoNGuEaWxmqNAxpXNXo0SZrmmgGaIs18zd2aFzQ7GTiGCYPHEDJWMPYwLjG6mESmBZPPTGcWMQ8xW5h9WppazlqxWvO0yrVOa7WzcCxzFp+VyVrHOspqY30dpz+OO048btW46nG3x33SHq/tqy3WLtSu0b6n/VWHrROgk6GzQade56kuXtdad6ruXN0dupd0X49njvccLxxfOP7o+Ed6qJ61XqTeAr3dejf0+vUN9IP0Zfpb9S/ovzZgGfgapBtsMjhj0GvIMPQ2lBhuMjxr+JKtxeayM9ml7IvsPiM9o2AjhdEuoxajAWML4xjj5cY1xk9NqCYckxSTTSZNJn2mhqaTTReaVpk+MqOYcczSzLaYNZt9MrcwjzNfaV5v3mOhbcG3yLOosnhiSbf0sZxjWWF514poxbHKsNpudcsatXaxTrMut75pg9q42khsttu0TiBMcJ8gnVAx4b4tzZZrm2tbZdthx7ILs1tuV2/3ZqLpxMSJGyY2T/xu72Kfab/H/rGDpkOIw3KHRod3jtaOQsdyx7tOdKdApyVODU5vnW2cxc47nB+4MFwmu6x0aXL509XNVe5a7drrZuqW5LbN7T6HyYngrOZccSe4+7kvcT/l/sXD1SPH46jHH562nhmeBzx7JllMEk/aM6nTy9hL4LXLq92b7Z3k/ZN3u4+Rj8Cnwue5r4mvyHevbzfXipvOPch942fvJ/er9fvE8+At4p3zx/kH+Rf6twRoBsQElAU8CzQOTA2sCuwLcglaEHQumBAcGrwh+D5fny/kV/L7QtxCFoVcDKWFRoWWhT4Psw6ThzVORieHTN44+ckUsynSKfXhEM4P3xj+NMIiYk7EyanEqRFTy6e+iHSIXBjZHMWImhV1IOpjtF/0uujHMZYxipimWLXY6bGVsZ/i/OOK49rjJ8Yvir+eoJsgSWhIJCXGJu5N7J8WMG3ztK7pLtMLprfNsJgxb8bVmbozM2eenqU2SzDrWBIhKS7pQNI3QbigQtCfzE/eltwn5Am3CF+JfEWbRL1iL3GxuDvFK6U4pSfVK3Vjam+aT1pJ2msJT1ImeZsenL4z/VNGeMa+jMHMuMyaLHJWUtYJqaY0Q3pxtsHsebNbZTayAln7HI85m+f0yUPle7OR7BnZDTlMbDi6obBU/KDoyPXOLc/9PDd27rF5GvOk827Mt56/an53XmDezwvwC4QLmhYaLVy2sGMRd9Guxcji5MVNS0yW5C/pWhq0dP8y6rKMZb8st19evPzDirgVjfn6+UvzO38I+qGqQLVAXnB/pefKnT/if5T82LLKadXWVd8LRYXXiuyLSoq+rRauvrbGYU3pmsG1KWtb1rmu27GeuF66vm2Dz4b9xRrFecWdGydvrNvE3lS46cPmWZuvljiX7NxC3aLY0l4aVtqw1XTr+q3fytLK7pX7ldds09u2atun7aLtt3f47qjeqb+zaOfXnyQ/PdgVtKuuwryiZDdxd+7uF3ti9zT/zPm5cq/u3qK9f+6T7mvfH7n/YqVbZeUBvQPrqtAqRVXvwekHbx3yP9RQbVu9q4ZVU3QYDisOvzySdKTtaOjRpmOcY9XHzY5vq2XUFtYhdfPr+urT6tsbEhpaT4ScaGr0bKw9aXdy3ymjU+WntU6vO0M9k39m8Gze2f5zsnOvz6ee72ya1fT4QvyFuxenXmy5FHrpyuXAyxeauc1nr3hdOXXV4+qJa5xr9dddr9fdcLlR+4vLL7Utri11N91uNtzyv9XYOqn1zG2f2+fv+N+5fJd/9/q9Kfda22LaHtyffr/9gehBz8PMh28f5T4aeLz0CeFJ4VP1pyXP9J5V/Gr1a027a/vpDv+OG8+jnj/uFHa++i37t29d+S/oL0q6Dbsrexx7TvUG9t56Oe1l1yvZq4HXBb9r/L7tjeWb43/4/nGjL76v66387eC71e913u/74PyhqT+i/9nHrI8Dnwo/63ze/4Xzpflr3NfugbnfSN9K/7T6s/F76Pcng1mDgzKBXDA8CuAwRVNSAN7tA6AnADCwGYI6bWSmHhZk5D9gmOA/8cjcPSyuANWYGRqNeOcADmNqvhRAzRdgaCyK9gXUyUmpo/Pv8Kw+JAbYv8K0HECi2x6tebQU/iEjc/xf+v6nBWXWv9l/AV0EC6JTIblRAAAAeGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAJAAAAABAAAAkAAAAAEAAqACAAQAAAABAAAAFKADAAQAAAABAAAAFAAAAAAXNii1AAAACXBIWXMAABYlAAAWJQFJUiTwAAAB82lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOllSZXNvbHV0aW9uPjE0NDwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+MTQ0PC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KReh49gAAAjRJREFUOBGFlD2vMUEUx2clvoNCcW8hCqFAo1dKhEQpvsF9KrWEBh/ALbQ0KkInBI3SWyGPCCJEQliXgsTLefaca/bBWjvJzs6cOf/fnDkzOQJIjWm06/XKBEGgD8c6nU5VIWgBtQDPZPWtJE8O63a7LBgMMo/Hw0ql0jPjcY4RvmqXy4XMjUYDUwLtdhtmsxnYbDbI5/O0djqdFFKmsEiGZ9jP9gem0yn0ej2Yz+fg9XpfycimAD7DttstQTDKfr8Po9GIIg6Hw1Cr1RTgB+A72GAwgMPhQLBMJgNSXsFqtUI2myUo18pA6QJogefsPrLBX4QdCVatViklw+EQRFGEj88P2O12pEUGATmsXq+TaLPZ0AXgMRF2vMEqlQoJTSYTpNNpApvNZliv1/+BHDaZTAi2Wq1A3Ig0xmMej7+RcZjdbodUKkWAaDQK+GHjHPnImB88JrZIJAKFQgH2+z2BOczhcMiwRCIBgUAA+NN5BP6mj2DYff35gk6nA61WCzBn2JxO5wPM7/fLz4vD0E+OECfn8xl/0Gw2KbLxeAyLxQIsFgt8p75pDSO7h/HbpUWpewCike9WLpfB7XaDy+WCYrFI/slk8i0MnRRAUt46hPMI4vE4+Hw+ec7t9/44VgWigEeby+UgFArJWjUYOqhWG6x50rpcSfR6PVUfNOgEVRlTX0HhrZBKz4MZjUYWi8VoA+lc9H/VaRZYjBKrtXR8tlwumcFgeMWRbZpA9ORQWfVm8A/FsrLaxebd5wAAAABJRU5ErkJggg==\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's capability to provide predefined prompt templates that clients can use.\n/// \n/// \n/// \n/// The prompts capability allows a server to expose a collection of predefined prompt templates that clients\n/// can discover and use. These prompts can be static (defined in the ) or\n/// dynamically generated through handlers.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the prompt list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when prompts are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their prompt cache. This capability enables clients to stay synchronized with server-side changes \n /// to available prompts.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests a list of available prompts from the server\n /// via a request. Results from this handler are returned\n /// along with any prompts defined in .\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt by name and provides arguments \n /// for the prompt if needed. The handler receives the request context containing the prompt name and any arguments, \n /// and should return a with the prompt messages and other details.\n /// \n /// \n /// This handler will be invoked if the requested prompt name is not found in the ,\n /// allowing for dynamic prompt generation or retrieval from external sources.\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets a collection of prompts that will be served by the server.\n /// \n /// \n /// \n /// The contains the predefined prompts that clients can request from the server.\n /// This collection works in conjunction with and \n /// when those are provided:\n /// \n /// \n /// - For requests: The server returns all prompts from this collection \n /// plus any additional prompts provided by the if it's set.\n /// \n /// \n /// - For requests: The server first checks this collection for the requested prompt.\n /// If not found, it will invoke the as a fallback if one is set.\n /// \n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? PromptCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/SemaphoreSlimExtensions.cs", "namespace ModelContextProtocol;\n\ninternal static class SynchronizationExtensions\n{\n /// \n /// Asynchronously acquires a lock on the semaphore and returns a disposable object that releases the lock when disposed.\n /// \n /// The semaphore to acquire a lock on.\n /// A cancellation token to observe while waiting for the semaphore.\n /// A disposable that releases the semaphore when disposed.\n /// \n /// This extension method provides a convenient pattern for using a semaphore in asynchronous code,\n /// similar to how the `lock` statement is used in synchronous code.\n /// \n /// The was canceled.\n public static async ValueTask LockAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)\n {\n await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);\n return new(semaphore);\n }\n\n /// \n /// A disposable struct that releases a semaphore when disposed.\n /// \n /// \n /// This struct is used with the extension method to provide\n /// a using-pattern for semaphore locking, similar to lock statements.\n /// \n public readonly struct Releaser(SemaphoreSlim semaphore) : IDisposable\n {\n /// \n /// Releases the semaphore.\n /// \n /// \n /// This method is called automatically when the goes out of scope\n /// in a using statement or expression.\n /// \n public void Dispose() => semaphore.Release();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/DefaultMcpServerBuilder.cs", "using ModelContextProtocol;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Default implementation of that enables fluent configuration\n/// of the Model Context Protocol (MCP) server. This builder is returned by the\n/// extension method and\n/// provides access to the service collection for registering additional MCP components.\n/// \ninternal sealed class DefaultMcpServerBuilder : IMcpServerBuilder\n{\n /// \n public IServiceCollection Services { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service collection to which MCP server services will be added. This collection\n /// is exposed through the property to allow additional configuration.\n /// Thrown when is null.\n public DefaultMcpServerBuilder(IServiceCollection services)\n {\n Throw.IfNull(services);\n\n Services = services;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolAnnotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional properties describing a to clients.\n/// \n/// \n/// All properties in are hints.\n/// They are not guaranteed to provide a faithful description of tool behavior (including descriptive properties like `title`).\n/// Clients should never make tool use decisions based on received from untrusted servers.\n/// \npublic sealed class ToolAnnotations\n{\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"destructiveHint\")]\n public bool? DestructiveHint { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"idempotentHint\")]\n public bool? IdempotentHint { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"openWorldHint\")]\n public bool? OpenWorldHint { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"readOnlyHint\")]\n public bool? ReadOnlyHint { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/StringSyntaxAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// Specifies the syntax used in a string.\n[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\ninternal sealed class StringSyntaxAttribute : Attribute\n{\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n public StringSyntaxAttribute(string syntax)\n {\n Syntax = syntax;\n Arguments = Array.Empty();\n }\n\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n /// Optional arguments associated with the specific syntax employed.\n public StringSyntaxAttribute(string syntax, params object?[] arguments)\n {\n Syntax = syntax;\n Arguments = arguments;\n }\n\n /// Gets the identifier of the syntax used.\n public string Syntax { get; }\n\n /// Optional arguments associated with the specific syntax employed.\n public object?[] Arguments { get; }\n\n /// The syntax identifier for strings containing composite formats for string formatting.\n public const string CompositeFormat = nameof(CompositeFormat);\n\n /// The syntax identifier for strings containing date format specifiers.\n public const string DateOnlyFormat = nameof(DateOnlyFormat);\n\n /// The syntax identifier for strings containing date and time format specifiers.\n public const string DateTimeFormat = nameof(DateTimeFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string EnumFormat = nameof(EnumFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string GuidFormat = nameof(GuidFormat);\n\n /// The syntax identifier for strings containing JavaScript Object Notation (JSON).\n public const string Json = nameof(Json);\n\n /// The syntax identifier for strings containing numeric format specifiers.\n public const string NumericFormat = nameof(NumericFormat);\n\n /// The syntax identifier for strings containing regular expressions.\n public const string Regex = nameof(Regex);\n\n /// The syntax identifier for strings containing time format specifiers.\n public const string TimeOnlyFormat = nameof(TimeOnlyFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string TimeSpanFormat = nameof(TimeSpanFormat);\n\n /// The syntax identifier for strings containing URIs.\n public const string Uri = nameof(Uri);\n\n /// The syntax identifier for strings containing XML.\n public const string Xml = nameof(Xml);\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CompilerFeatureRequiredAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Indicates that compiler support for a particular feature is required for the location where this attribute is applied.\n /// \n [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]\n internal sealed class CompilerFeatureRequiredAttribute : Attribute\n {\n public CompilerFeatureRequiredAttribute(string featureName)\n {\n FeatureName = featureName;\n }\n\n /// \n /// The name of the compiler feature.\n /// \n public string FeatureName { get; }\n\n /// \n /// If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand .\n /// \n public bool IsOptional { get; init; }\n\n /// \n /// The used for the required members C# feature.\n /// \n public const string RequiredMembers = nameof(RequiredMembers);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/TokenContainer.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a token response from the OAuth server.\n/// \ninternal sealed class TokenContainer\n{\n /// \n /// Gets or sets the access token.\n /// \n [JsonPropertyName(\"access_token\")]\n public string AccessToken { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the refresh token.\n /// \n [JsonPropertyName(\"refresh_token\")]\n public string? RefreshToken { get; set; }\n\n /// \n /// Gets or sets the number of seconds until the access token expires.\n /// \n [JsonPropertyName(\"expires_in\")]\n public int ExpiresIn { get; set; }\n\n /// \n /// Gets or sets the extended expiration time in seconds.\n /// \n [JsonPropertyName(\"ext_expires_in\")]\n public int ExtExpiresIn { get; set; }\n\n /// \n /// Gets or sets the token type (typically \"Bearer\").\n /// \n [JsonPropertyName(\"token_type\")]\n public string TokenType { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the scope of the access token.\n /// \n [JsonPropertyName(\"scope\")]\n public string Scope { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the timestamp when the token was obtained.\n /// \n [JsonIgnore]\n public DateTimeOffset ObtainedAt { get; set; }\n\n /// \n /// Gets the timestamp when the token expires, calculated from ObtainedAt and ExpiresIn.\n /// \n [JsonIgnore]\n public DateTimeOffset ExpiresAt => ObtainedAt.AddSeconds(ExpiresIn);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// request from a server to sample an LLM via the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageRequestParams : RequestParams\n{\n /// \n /// Gets or sets an indication as to which server contexts should be included in the prompt.\n /// \n /// \n /// The client may ignore this request.\n /// \n [JsonPropertyName(\"includeContext\")]\n public ContextInclusion? IncludeContext { get; init; }\n\n /// \n /// Gets or sets the maximum number of tokens to generate in the LLM response, as requested by the server.\n /// \n /// \n /// A token is generally a word or part of a word in the text. Setting this value helps control \n /// response length and computation time. The client may choose to sample fewer tokens than requested.\n /// \n [JsonPropertyName(\"maxTokens\")]\n public int? MaxTokens { get; init; }\n\n /// \n /// Gets or sets the messages requested by the server to be included in the prompt.\n /// \n [JsonPropertyName(\"messages\")]\n public required IReadOnlyList Messages { get; init; }\n\n /// \n /// Gets or sets optional metadata to pass through to the LLM provider.\n /// \n /// \n /// The format of this metadata is provider-specific and can include model-specific settings or\n /// configuration that isn't covered by standard parameters. This allows for passing custom parameters \n /// that are specific to certain AI models or providers.\n /// \n [JsonPropertyName(\"metadata\")]\n public JsonElement? Metadata { get; init; }\n\n /// \n /// Gets or sets the server's preferences for which model to select.\n /// \n /// \n /// \n /// The client may ignore these preferences.\n /// \n /// \n /// These preferences help the client make an appropriate model selection based on the server's priorities\n /// for cost, speed, intelligence, and specific model hints.\n /// \n /// \n /// When multiple dimensions are specified (cost, speed, intelligence), the client should balance these\n /// based on their relative values. If specific model hints are provided, the client should evaluate them\n /// in order and prioritize them over numeric priorities.\n /// \n /// \n [JsonPropertyName(\"modelPreferences\")]\n public ModelPreferences? ModelPreferences { get; init; }\n\n /// \n /// Gets or sets optional sequences of characters that signal the LLM to stop generating text when encountered.\n /// \n /// \n /// \n /// When the model generates any of these sequences during sampling, text generation stops immediately,\n /// even if the maximum token limit hasn't been reached. This is useful for controlling generation \n /// endings or preventing the model from continuing beyond certain points.\n /// \n /// \n /// Stop sequences are typically case-sensitive, and typically the LLM will only stop generation when a produced\n /// sequence exactly matches one of the provided sequences. Common uses include ending markers like \"END\", punctuation\n /// like \".\", or special delimiter sequences like \"###\".\n /// \n /// \n [JsonPropertyName(\"stopSequences\")]\n public IReadOnlyList? StopSequences { get; init; }\n\n /// \n /// Gets or sets an optional system prompt the server wants to use for sampling.\n /// \n /// \n /// The client may modify or omit this prompt.\n /// \n [JsonPropertyName(\"systemPrompt\")]\n public string? SystemPrompt { get; init; }\n\n /// \n /// Gets or sets the temperature to use for sampling, as requested by the server.\n /// \n [JsonPropertyName(\"temperature\")]\n public float? Temperature { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/IMcpEndpoint.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Represents a client or server Model Context Protocol (MCP) endpoint.\n/// \n/// \n/// \n/// The MCP endpoint provides the core communication functionality used by both clients and servers:\n/// \n/// Sending JSON-RPC requests and receiving responses.\n/// Sending notifications to the connected endpoint.\n/// Registering handlers for receiving notifications.\n/// \n/// \n/// \n/// serves as the base interface for both and \n/// interfaces, providing the common functionality needed for MCP protocol \n/// communication. Most applications will use these more specific interfaces rather than working with \n/// directly.\n/// \n/// \n/// All MCP endpoints should be properly disposed after use as they implement .\n/// \n/// \npublic interface IMcpEndpoint : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Sends a JSON-RPC request to the connected endpoint and waits for a response.\n /// \n /// The JSON-RPC request to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the endpoint's response.\n /// The transport is not connected, or another error occurs during request processing.\n /// An error occured during request processing.\n /// \n /// This method provides low-level access to send raw JSON-RPC requests. For most use cases,\n /// consider using the strongly-typed extension methods that provide a more convenient API.\n /// \n Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default);\n\n /// \n /// Sends a JSON-RPC message to the connected endpoint.\n /// \n /// \n /// The JSON-RPC message to send. This can be any type that implements JsonRpcMessage, such as\n /// JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, or JsonRpcError.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// is .\n /// \n /// \n /// This method provides low-level access to send any JSON-RPC message. For specific message types,\n /// consider using the higher-level methods such as or extension methods\n /// like ,\n /// which provide a simpler API.\n /// \n /// \n /// The method will serialize the message and transmit it using the underlying transport mechanism.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n\n /// Registers a handler to be invoked when a notification for the specified method is received.\n /// The notification method.\n /// The handler to be invoked.\n /// An that will remove the registered handler when disposed.\n IAsyncDisposable RegisterNotificationHandler(string method, Func handler);\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMembersAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that certain members on a specified are accessed dynamically,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which members are being accessed during the execution\n/// of a program.\n///\n/// This attribute is valid on members whose type is or .\n///\n/// When this attribute is applied to a location of type , the assumption is\n/// that the string represents a fully qualified type name.\n///\n/// When this attribute is applied to a class, interface, or struct, the members specified\n/// can be accessed dynamically on instances returned from calling\n/// on instances of that class, interface, or struct.\n///\n/// If the attribute is applied to a method it's treated as a special case and it implies\n/// the attribute should be applied to the \"this\" parameter of the method. As such the attribute\n/// should only be used on instance methods of types assignable to System.Type (or string, but no methods\n/// will use it there).\n/// \n[AttributeUsage(\n AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |\n AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |\n AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,\n Inherited = false)]\ninternal sealed class DynamicallyAccessedMembersAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified member types.\n /// \n /// The types of members dynamically accessed.\n public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)\n {\n MemberTypes = memberTypes;\n }\n\n /// \n /// Gets the which specifies the type\n /// of members dynamically accessed.\n /// \n public DynamicallyAccessedMemberTypes MemberTypes { get; }\n}\n#endif"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as prompts in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as prompts that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerPromptAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPromptAttribute()\n {\n }\n\n /// Gets the name of the prompt.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the prompt.\n public string? Title { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Completion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a completion object in the server's response to a request.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Completion\n{\n /// \n /// Gets or sets an array of completion values (auto-suggestions) for the requested input.\n /// \n /// \n /// This collection contains the actual text strings to be presented to users as completion suggestions.\n /// The array will be empty if no suggestions are available for the current input.\n /// Per the specification, this should not exceed 100 items.\n /// \n [JsonPropertyName(\"values\")]\n public IList Values { get; set; } = [];\n\n /// \n /// Gets or sets the total number of completion options available.\n /// \n /// \n /// This can exceed the number of values actually sent in the response.\n /// \n [JsonPropertyName(\"total\")]\n public int? Total { get; set; }\n\n /// \n /// Gets or sets an indicator as to whether there are additional completion options beyond \n /// those provided in the current response, even if the exact total is unknown.\n /// \n [JsonPropertyName(\"hasMore\")]\n public bool? HasMore { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available resources.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available resources on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resources.\n/// The server can provide the property to indicate there are more\n/// resources available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourcesResult : PaginatedResult\n{\n /// \n /// A list of resources that the server offers.\n /// \n [JsonPropertyName(\"resources\")]\n public IList Resources { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a from the server.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageResult : Result\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the name of the model that generated the message.\n /// \n /// \n /// \n /// This should contain the specific model identifier such as \"claude-3-5-sonnet-20241022\" or \"o3-mini\".\n /// \n /// \n /// This property allows the server to know which model was used to generate the response,\n /// enabling appropriate handling based on the model's capabilities and characteristics.\n /// \n /// \n [JsonPropertyName(\"model\")]\n public required string Model { get; init; }\n\n /// \n /// Gets or sets the reason why message generation (sampling) stopped, if known.\n /// \n /// \n /// Common values include:\n /// \n /// endTurnThe model naturally completed its response.\n /// maxTokensThe response was truncated due to reaching token limits.\n /// stopSequenceA specific stop sequence was encountered during generation.\n /// \n /// \n [JsonPropertyName(\"stopReason\")]\n public string? StopReason { get; init; }\n\n /// \n /// Gets or sets the role of the user who generated the message.\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationServerMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the metadata about an OAuth authorization server.\n/// \ninternal sealed class AuthorizationServerMetadata\n{\n /// \n /// The authorization endpoint URI.\n /// \n [JsonPropertyName(\"authorization_endpoint\")]\n public Uri AuthorizationEndpoint { get; set; } = null!;\n\n /// \n /// The token endpoint URI.\n /// \n [JsonPropertyName(\"token_endpoint\")]\n public Uri TokenEndpoint { get; set; } = null!;\n\n /// \n /// The registration endpoint URI.\n /// \n [JsonPropertyName(\"registration_endpoint\")]\n public Uri? RegistrationEndpoint { get; set; }\n\n /// \n /// The revocation endpoint URI.\n /// \n [JsonPropertyName(\"revocation_endpoint\")]\n public Uri? RevocationEndpoint { get; set; }\n\n /// \n /// The response types supported by the authorization server.\n /// \n [JsonPropertyName(\"response_types_supported\")]\n public List? ResponseTypesSupported { get; set; }\n\n /// \n /// The grant types supported by the authorization server.\n /// \n [JsonPropertyName(\"grant_types_supported\")]\n public List? GrantTypesSupported { get; set; }\n\n /// \n /// The token endpoint authentication methods supported by the authorization server.\n /// \n [JsonPropertyName(\"token_endpoint_auth_methods_supported\")]\n public List? TokenEndpointAuthMethodsSupported { get; set; }\n\n /// \n /// The code challenge methods supported by the authorization server.\n /// \n [JsonPropertyName(\"code_challenge_methods_supported\")]\n public List? CodeChallengeMethodsSupported { get; set; }\n\n /// \n /// The issuer URI of the authorization server.\n /// \n [JsonPropertyName(\"issuer\")]\n public Uri? Issuer { get; set; }\n\n /// \n /// The scopes supported by the authorization server.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List? ScopesSupported { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides configuration options for the MCP server.\n/// \npublic sealed class McpServerOptions\n{\n /// \n /// Gets or sets information about this server implementation, including its name and version.\n /// \n /// \n /// This information is sent to the client during initialization to identify the server.\n /// It's displayed in client logs and can be used for debugging and compatibility checks.\n /// \n public Implementation? ServerInfo { get; set; }\n\n /// \n /// Gets or sets server capabilities to advertise to the client.\n /// \n /// \n /// These determine which features will be available when a client connects.\n /// Capabilities can include \"tools\", \"prompts\", \"resources\", \"logging\", and other \n /// protocol-specific functionality.\n /// \n public ServerCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version supported by this server, using a date-based versioning scheme.\n /// \n /// \n /// The protocol version defines which features and message formats this server supports.\n /// This uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// If , the server will advertize to the client the version requested\n /// by the client if that version is known to be supported, and otherwise will advertize the latest\n /// version supported by the server.\n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout used for the client-server initialization handshake sequence.\n /// \n /// \n /// This timeout determines how long the server will wait for client responses during\n /// the initialization protocol handshake. If the client doesn't respond within this timeframe,\n /// the initialization process will be aborted.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n\n /// \n /// Gets or sets optional server instructions to send to clients.\n /// \n /// \n /// These instructions are sent to clients during the initialization handshake and provide\n /// guidance on how to effectively use the server's capabilities. They can include details\n /// about available tools, expected input formats, limitations, or other helpful information.\n /// Client applications typically use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n public string? ServerInstructions { get; set; }\n\n /// \n /// Gets or sets whether to create a new service provider scope for each handled request.\n /// \n /// \n /// The default is . When , each invocation of a request\n /// handler will be invoked within a new service scope.\n /// \n public bool ScopeRequests { get; set; } = true;\n\n /// \n /// Gets or sets preexisting knowledge about the client including its name and version to help support\n /// stateless Streamable HTTP servers that encode this knowledge in the mcp-session-id header.\n /// \n /// \n /// \n /// When not specified, this information is sourced from the client's initialize request.\n /// \n /// \n public Implementation? KnownClientInfo { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the tools capability configuration.\n/// See the schema for details.\n/// \npublic sealed class ToolsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the tool list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when tools are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their tool cache. This capability enables clients to stay synchronized with server-side \n /// changes to available tools.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// When used in conjunction with , both the tools from this handler\n /// and the tools from the collection will be combined to form the complete list of available tools.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the .\n /// The handler should implement logic to execute the requested tool and return appropriate results. \n /// It receives a containing information about the tool \n /// being called and its arguments, and should return a with the execution results.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets a collection of tools served by the server.\n /// \n /// \n /// Tools will specified via augment the and\n /// , if provided. ListTools requests will output information about every tool\n /// in and then also any tools output by , if it's\n /// non-. CallTool requests will first check for the tool\n /// being requested, and if the tool is not found in the , any specified \n /// will be invoked as a fallback.\n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? ToolCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcErrorDetail.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents detailed error information for JSON-RPC error responses.\n/// \n/// \n/// This class is used as part of the message to provide structured \n/// error information when a request cannot be fulfilled. The JSON-RPC 2.0 specification defines\n/// a standard format for error responses that includes a numeric code, a human-readable message,\n/// and optional additional data.\n/// \npublic sealed class JsonRpcErrorDetail\n{\n /// \n /// Gets an integer error code according to the JSON-RPC specification.\n /// \n [JsonPropertyName(\"code\")]\n public required int Code { get; init; }\n\n /// \n /// Gets a short description of the error.\n /// \n /// \n /// This is expected to be a brief, human-readable explanation of what went wrong.\n /// For standard error codes, it's recommended to use the descriptions defined \n /// in the JSON-RPC 2.0 specification.\n /// \n [JsonPropertyName(\"message\")]\n public required string Message { get; init; }\n\n /// \n /// Gets optional additional error data.\n /// \n /// \n /// This property can contain any additional information that might help the client\n /// understand or resolve the error. Common examples include validation errors,\n /// stack traces (in development environments), or contextual information about\n /// the error condition.\n /// \n [JsonPropertyName(\"data\")]\n public object? Data { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the client's response to an elicitation request.\n/// \npublic sealed class ElicitResult : Result\n{\n /// \n /// Gets or sets the user action in response to the elicitation.\n /// \n /// \n /// \n /// \n /// \"accept\"\n /// User submitted the form/confirmed the action\n /// \n /// \n /// \"decline\"\n /// User explicitly declined the action\n /// \n /// \n /// \"cancel\"\n /// User dismissed without making an explicit choice\n /// \n /// \n /// \n [JsonPropertyName(\"action\")]\n public string Action { get; set; } = \"cancel\";\n\n /// \n /// Gets or sets the submitted form data.\n /// \n /// \n /// \n /// This is typically omitted if the action is \"cancel\" or \"decline\".\n /// \n /// \n /// Values in the dictionary should be of types , ,\n /// , or .\n /// \n /// \n [JsonPropertyName(\"content\")]\n public IDictionary? Content { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CancelledNotificationParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification indicating that a request has been cancelled by the client,\n/// and that any associated processing should cease immediately.\n/// \n/// \n/// This class is typically used in conjunction with the \n/// method identifier. When a client sends this notification, the server should attempt to\n/// cancel any ongoing operations associated with the specified request ID.\n/// \npublic sealed class CancelledNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the ID of the request to cancel.\n /// \n /// \n /// This must match the ID of an in-flight request that the sender wishes to cancel.\n /// \n [JsonPropertyName(\"requestId\")]\n public RequestId RequestId { get; set; }\n\n /// \n /// Gets or sets an optional string describing the reason for the cancellation request.\n /// \n [JsonPropertyName(\"reason\")]\n public string? Reason { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request sent to the server during connection establishment.\n/// \n/// \n/// \n/// The is sent by the server in response to an \n/// message from the client. It contains information about the server, its capabilities, and the protocol version\n/// that will be used for the session.\n/// \n/// \n/// After receiving this response, the client should send an \n/// notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeResult : Result\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the server will use for this session.\n /// \n /// \n /// \n /// This is the protocol version the server has agreed to use, which should match the client's \n /// requested version. If there's a mismatch, the client should throw an exception to prevent \n /// communication issues due to incompatible protocol versions.\n /// \n /// \n /// The protocol uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the server's capabilities.\n /// \n /// \n /// This defines the features the server supports, such as \"tools\", \"prompts\", \"resources\", or \"logging\", \n /// and other protocol-specific functionality.\n /// \n [JsonPropertyName(\"capabilities\")]\n public required ServerCapabilities Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the server implementation, including its name and version.\n /// \n /// \n /// This information identifies the server during the initialization handshake.\n /// Clients may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"serverInfo\")]\n public required Implementation ServerInfo { get; init; }\n\n /// \n /// Gets or sets optional instructions for using the server and its features.\n /// \n /// \n /// \n /// These instructions provide guidance to clients on how to effectively use the server's capabilities.\n /// They can include details about available tools, expected input formats, limitations,\n /// or any other information that helps clients interact with the server properly.\n /// \n /// \n /// Client applications often use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n /// \n [JsonPropertyName(\"instructions\")]\n public string? Instructions { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationDefaults.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Default values used by MCP authentication.\n/// \npublic static class McpAuthenticationDefaults\n{\n /// \n /// The default value used for authentication scheme name.\n /// \n public const string AuthenticationScheme = \"McpAuth\";\n\n /// \n /// The default value used for authentication scheme display name.\n /// \n public const string DisplayName = \"MCP Authentication\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request sent by a client to a server during the protocol handshake.\n/// \n/// \n/// \n/// The is the first message sent in the Model Context Protocol\n/// communication flow. It establishes the connection between client and server, negotiates the protocol\n/// version, and declares the client's capabilities.\n/// \n/// \n/// After sending this request, the client should wait for an response\n/// before sending an notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the client wants to use.\n /// \n /// \n /// \n /// Protocol version is specified using a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// The client and server must agree on a protocol version to communicate successfully.\n /// \n /// \n /// During initialization, the server will check if it supports this requested version. If there's a \n /// mismatch, the server will reject the connection with a version mismatch error.\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the client's capabilities.\n /// \n /// \n /// Capabilities define the features the client supports, such as \"sampling\" or \"roots\".\n /// \n [JsonPropertyName(\"capabilities\")]\n public ClientCapabilities? Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the client implementation, including its name and version.\n /// \n /// \n /// This information is required during the initialization handshake to identify the client.\n /// Servers may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"clientInfo\")]\n public required Implementation ClientInfo { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolResult.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// \n/// Any errors that originate from the tool should be reported inside the result\n/// object, with set to true, rather than as a .\n/// \n/// \n/// However, any errors in finding the tool, an error indicating that the\n/// server does not support tool calls, or any other exceptional conditions,\n/// should be reported as an MCP error response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CallToolResult : Result\n{\n /// \n /// Gets or sets the response content from the tool call.\n /// \n [JsonPropertyName(\"content\")]\n public IList Content { get; set; } = [];\n\n /// \n /// Gets or sets an optional JSON object representing the structured result of the tool call.\n /// \n [JsonPropertyName(\"structuredContent\")]\n public JsonNode? StructuredContent { get; set; }\n\n /// \n /// Gets or sets an indication of whether the tool call was unsuccessful.\n /// \n /// \n /// When set to , it signifies that the tool execution failed.\n /// Tool errors are reported with this property set to and details in the \n /// property, rather than as protocol-level errors. This allows LLMs to see that an error occurred\n /// and potentially self-correct in subsequent requests.\n /// \n [JsonPropertyName(\"isError\")]\n public bool? IsError { get; set; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresDynamicCodeAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires the ability to generate new code at runtime,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when compiling ahead of time.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresDynamicCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of dynamic code.\n /// \n public RequiresDynamicCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of dynamic code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires dynamic code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ITransport.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Server;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a transport mechanism for MCP (Model Context Protocol) communication between clients and servers.\n/// \n/// \n/// \n/// The interface is the core abstraction for bidirectional communication.\n/// It provides methods for sending and receiving messages, abstracting away the underlying transport mechanism\n/// and allowing protocol implementations to be decoupled from communication details.\n/// \n/// \n/// Implementations of handle the serialization, transmission, and reception of\n/// messages over various channels like standard input/output streams and HTTP (Server-Sent Events).\n/// \n/// \n/// While is responsible for establishing a client's connection,\n/// represents an established session. Client implementations typically obtain an\n/// instance by calling .\n/// \n/// \npublic interface ITransport : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Gets a channel reader for receiving messages from the transport.\n /// \n /// \n /// \n /// The provides access to incoming JSON-RPC messages received by the transport.\n /// It returns a which allows consuming messages in a thread-safe manner.\n /// \n /// \n /// The reader will continue to provide messages as long as the transport is connected. When the transport\n /// is disconnected or disposed, the channel will be completed and no more messages will be available after\n /// any already transmitted messages are consumed.\n /// \n /// \n ChannelReader MessageReader { get; }\n\n /// \n /// Sends a JSON-RPC message through the transport.\n /// \n /// The JSON-RPC message to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// \n /// \n /// This method serializes and sends the provided JSON-RPC message through the transport connection.\n /// \n /// \n /// This is a core method used by higher-level abstractions in the MCP protocol implementation.\n /// Most client code should use the higher-level methods provided by ,\n /// , , or ,\n /// rather than accessing this method directly.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/UnconditionalSuppressMessageAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a\n/// single code artifact.\n/// \n/// \n/// is different than\n/// in that it doesn't have a\n/// . So it is always preserved in the compiled assembly.\n/// \n[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\ninternal sealed class UnconditionalSuppressMessageAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the \n /// class, specifying the category of the tool and the identifier for an analysis rule.\n /// \n /// The category for the attribute.\n /// The identifier of the analysis rule the attribute applies to.\n public UnconditionalSuppressMessageAttribute(string category, string checkId)\n {\n Category = category;\n CheckId = checkId;\n }\n\n /// \n /// Gets the category identifying the classification of the attribute.\n /// \n /// \n /// The property describes the tool or tool analysis category\n /// for which a message suppression attribute applies.\n /// \n public string Category { get; }\n\n /// \n /// Gets the identifier of the analysis tool rule to be suppressed.\n /// \n /// \n /// Concatenated together, the and \n /// properties form a unique check identifier.\n /// \n public string CheckId { get; }\n\n /// \n /// Gets or sets the scope of the code that is relevant for the attribute.\n /// \n /// \n /// The Scope property is an optional argument that specifies the metadata scope for which\n /// the attribute is relevant.\n /// \n public string? Scope { get; set; }\n\n /// \n /// Gets or sets a fully qualified path that represents the target of the attribute.\n /// \n /// \n /// The property is an optional argument identifying the analysis target\n /// of the attribute. An example value is \"System.IO.Stream.ctor():System.Void\".\n /// Because it is fully qualified, it can be long, particularly for targets such as parameters.\n /// The analysis tool user interface should be capable of automatically formatting the parameter.\n /// \n public string? Target { get; set; }\n\n /// \n /// Gets or sets an optional argument expanding on exclusion criteria.\n /// \n /// \n /// The property is an optional argument that specifies additional\n /// exclusion where the literal metadata target is not sufficiently precise. For example,\n /// the cannot be applied within a method,\n /// and it may be desirable to suppress a violation against a statement in the method that will\n /// give a rule violation, but not against all statements in the method.\n /// \n public string? MessageId { get; set; }\n\n /// \n /// Gets or sets the justification for suppressing the code analysis message.\n /// \n public string? Justification { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptResult.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// \n/// For integration with AI client libraries, can be converted to\n/// a collection of objects using the extension method.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class GetPromptResult : Result\n{\n /// \n /// Gets or sets an optional description for the prompt.\n /// \n /// \n /// \n /// This description provides contextual information about the prompt's purpose and use cases.\n /// It helps developers understand what the prompt is designed for and how it should be used.\n /// \n /// \n /// When returned from a server in response to a request,\n /// this description can be used by client applications to provide context about the prompt or to\n /// display in user interfaces.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets the prompt that the server offers.\n /// \n [JsonPropertyName(\"messages\")]\n public IList Messages { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Argument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument used in completion requests to provide context for auto-completion functionality.\n/// \n/// \n/// This class is used when requesting completion suggestions for a particular field or parameter.\n/// See the schema for details.\n/// \npublic sealed class Argument\n{\n /// \n /// Gets or sets the name of the argument being completed.\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the current partial text value for which completion suggestions are requested.\n /// \n /// \n /// This represents the text that has been entered so far and for which completion\n /// options should be generated.\n /// \n [JsonPropertyName(\"value\")]\n public string Value { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/TokenProgress.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides an tied to a specific progress token and that will issue\n/// progress notifications on the supplied endpoint.\n/// \ninternal sealed class TokenProgress(IMcpEndpoint endpoint, ProgressToken progressToken) : IProgress\n{\n /// \n public void Report(ProgressNotificationValue value)\n {\n _ = endpoint.NotifyProgressAsync(progressToken, value, CancellationToken.None);\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresUnreferencedCode.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires dynamic access to code that is not referenced\n/// statically, for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when removing unreferenced\n/// code from an application.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresUnreferencedCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of unreferenced code.\n /// \n public RequiresUnreferencedCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of unreferenced code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires unreferenced code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContextInclusion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Specifies the context inclusion options for a request in the Model Context Protocol (MCP).\n/// \n/// \n/// See the schema for details.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum ContextInclusion\n{\n /// \n /// Indicates that no context should be included.\n /// \n [JsonStringEnumMemberName(\"none\")]\n None,\n\n /// \n /// Indicates that context from the server that sent the request should be included.\n /// \n [JsonStringEnumMemberName(\"thisServer\")]\n ThisServer,\n\n /// \n /// Indicates that context from all servers that the client is connected to should be included.\n /// \n [JsonStringEnumMemberName(\"allServers\")]\n AllServers\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcError.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an error response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Error responses are sent when a request cannot be fulfilled or encounters an error during processing.\n/// Like successful responses, error messages include the same ID as the original request, allowing the\n/// sender to match errors with their corresponding requests.\n/// \n/// \n/// Each error response contains a structured error detail object with a numeric code, descriptive message,\n/// and optional additional data to provide more context about the error.\n/// \n/// \npublic sealed class JsonRpcError : JsonRpcMessageWithId\n{\n /// \n /// Gets detailed error information for the failed request, containing an error code, \n /// message, and optional additional data\n /// \n [JsonPropertyName(\"error\")]\n public required JsonRpcErrorDetail Error { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/IO/TextWriterExtensions.cs", "#if !NET\nnamespace System.IO;\n\ninternal static class TextWriterExtensions\n{\n public static async Task FlushAsync(this TextWriter writer, CancellationToken cancellationToken)\n {\n cancellationToken.ThrowIfCancellationRequested();\n await writer.FlushAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol/IMcpServerBuilder.cs", "using ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides a builder for configuring instances.\n/// \n/// \n/// \n/// The interface provides a fluent API for configuring Model Context Protocol (MCP) servers\n/// when using dependency injection. It exposes methods for registering tools, prompts, custom request handlers,\n/// and server transports, allowing for comprehensive server configuration through a chain of method calls.\n/// \n/// \n/// The builder is obtained from the extension\n/// method and provides access to the underlying service collection via the property.\n/// \n/// \npublic interface IMcpServerBuilder\n{\n /// \n /// Gets the associated service collection.\n /// \n IServiceCollection Services { get; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelPreferences.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's preferences for model selection, requested of the client during sampling.\n/// \n/// \n/// \n/// Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n/// rarely straightforward. Different models excel in different areas—some are\n/// faster but less capable, others are more capable but more expensive, and so\n/// on. This class allows servers to express their priorities across multiple\n/// dimensions to help clients make an appropriate selection for their use case.\n/// \n/// \n/// These preferences are always advisory. The client may ignore them. It is also\n/// up to the client to decide how to interpret these preferences and how to\n/// balance them against other considerations.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelPreferences\n{\n /// \n /// Gets or sets how much to prioritize cost when selecting a model.\n /// \n /// \n /// A value of 0 means cost is not important, while a value of 1 means cost is the most important factor.\n /// \n [JsonPropertyName(\"costPriority\")]\n public float? CostPriority { get; init; }\n\n /// \n /// Gets or sets optional hints to use for model selection.\n /// \n [JsonPropertyName(\"hints\")]\n public IReadOnlyList? Hints { get; init; }\n\n /// \n /// Gets or sets how much to prioritize sampling speed (latency) when selecting a model.\n /// \n /// \n /// A value of 0 means speed is not important, while a value of 1 means speed is the most important factor.\n /// \n [JsonPropertyName(\"speedPriority\")]\n public float? SpeedPriority { get; init; }\n\n /// \n /// Gets or sets how much to prioritize intelligence and capabilities when selecting a model.\n /// \n /// \n /// A value of 0 means intelligence is not important, while a value of 1 means intelligence is the most important factor.\n /// \n [JsonPropertyName(\"intelligencePriority\")]\n public float? IntelligencePriority { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessageWithId.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC message used in the Model Context Protocol (MCP) and that includes an ID.\n/// \n/// \n/// In the JSON-RPC protocol, messages with an ID require a response from the receiver.\n/// This includes request messages (which expect a matching response) and response messages\n/// (which include the ID of the original request they're responding to).\n/// The ID is used to correlate requests with their responses, allowing asynchronous\n/// communication where multiple requests can be sent without waiting for responses.\n/// \npublic abstract class JsonRpcMessageWithId : JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessageWithId()\n {\n }\n\n /// \n /// Gets the message identifier.\n /// \n /// \n /// Each ID is expected to be unique within the context of a given session.\n /// \n [JsonPropertyName(\"id\")]\n public RequestId Id { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServer.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) server that connects to and communicates with an MCP client.\n/// \npublic interface IMcpServer : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the client.\n /// \n /// \n /// \n /// These capabilities are established during the initialization handshake and indicate\n /// which features the client supports, such as sampling, roots, and other\n /// protocol-specific functionality.\n /// \n /// \n /// Server implementations can check these capabilities to determine which features\n /// are available when interacting with the client.\n /// \n /// \n ClientCapabilities? ClientCapabilities { get; }\n\n /// \n /// Gets the version and implementation information of the connected client.\n /// \n /// \n /// \n /// This property contains identification information about the client that has connected to this server,\n /// including its name and version. This information is provided by the client during initialization.\n /// \n /// \n /// Server implementations can use this information for logging, tracking client versions, \n /// or implementing client-specific behaviors.\n /// \n /// \n Implementation? ClientInfo { get; }\n\n /// \n /// Gets the options used to construct this server.\n /// \n /// \n /// These options define the server's capabilities, protocol version, and other configuration\n /// settings that were used to initialize the server.\n /// \n McpServerOptions ServerOptions { get; }\n\n /// \n /// Gets the service provider for the server.\n /// \n IServiceProvider? Services { get; }\n\n /// Gets the last logging level set by the client, or if it's never been set.\n LoggingLevel? LoggingLevel { get; }\n\n /// \n /// Runs the server, listening for and handling client requests.\n /// \n Task RunAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingCapability.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Client;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to generate text or other content using an AI model.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to sampling requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to generate content\n/// using an AI model. The client must set a to process these requests.\n/// \n/// \npublic sealed class SamplingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to generate content\n /// using an AI model. The client must set this property for the sampling capability to work.\n /// \n /// \n /// The handler receives message parameters, a progress reporter for updates, and a \n /// cancellation token. It should return a containing the \n /// generated content.\n /// \n /// \n /// You can create a handler using the extension\n /// method with any implementation of .\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SamplingHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptArgument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument that a prompt can accept for templating and customization.\n/// \n/// \n/// \n/// The class defines metadata for arguments that can be provided\n/// to a prompt. These arguments are used to customize or parameterize prompts when they are \n/// retrieved using requests.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptArgument : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the argument's purpose and expected values.\n /// \n /// \n /// This description helps developers understand what information should be provided\n /// for this argument and how it will affect the generated prompt.\n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets an indication as to whether this argument must be provided when requesting the prompt.\n /// \n /// \n /// When set to , the client must include this argument when making a request.\n /// If a required argument is missing, the server should respond with an error.\n /// \n [JsonPropertyName(\"required\")]\n public bool? Required { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Collections/Generic/CollectionExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Collections.Generic;\n\ninternal static class CollectionExtensions\n{\n public static TValue? GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key)\n {\n return dictionary.GetValueOrDefault(key, default!);\n }\n\n public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key, TValue defaultValue)\n {\n Throw.IfNull(dictionary);\n\n return dictionary.TryGetValue(key, out TValue? value) ? value : defaultValue;\n }\n\n public static Dictionary ToDictionary(this IEnumerable> source) =>\n source.ToDictionary(kv => kv.Key, kv => kv.Value);\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Net/Http/HttpClientExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Net.Http;\n\ninternal static class HttpClientExtensions\n{\n public static async Task ReadAsStreamAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStreamAsync();\n }\n\n public static async Task ReadAsStringAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStringAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationRedirectDelegate.cs", "\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a method that handles the OAuth authorization URL and returns the authorization code.\n/// \n/// The authorization URL that the user needs to visit.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// A task that represents the asynchronous operation. The task result contains the authorization code if successful, or null if the operation failed or was cancelled.\n/// \n/// \n/// This delegate provides SDK consumers with full control over how the OAuth authorization flow is handled.\n/// Implementers can choose to:\n/// \n/// \n/// Start a local HTTP server and open a browser (default behavior)\n/// Display the authorization URL to the user for manual handling\n/// Integrate with a custom UI or authentication flow\n/// Use a different redirect mechanism altogether\n/// \n/// \n/// The implementation should handle user interaction to visit the authorization URL and extract\n/// the authorization code from the callback. The authorization code is typically provided as\n/// a query parameter in the redirect URI callback.\n/// \n/// \npublic delegate Task AuthorizationRedirectDelegate(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken);"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/EmptyResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an empty result object for operations that need to indicate successful completion \n/// but don't need to return any specific data.\n/// \npublic sealed class EmptyResult : Result\n{\n [JsonIgnore]\n internal static EmptyResult Instance { get; } = new();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpErrorCode.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents standard JSON-RPC error codes as defined in the MCP specification.\n/// \npublic enum McpErrorCode\n{\n /// \n /// Indicates that the JSON received could not be parsed.\n /// \n /// \n /// This error occurs when the input contains malformed JSON or incorrect syntax.\n /// \n ParseError = -32700,\n\n /// \n /// Indicates that the JSON payload does not conform to the expected Request object structure.\n /// \n /// \n /// The request is considered invalid if it lacks required fields or fails to follow the JSON-RPC protocol.\n /// \n InvalidRequest = -32600,\n\n /// \n /// Indicates that the requested method does not exist or is not available on the server.\n /// \n /// \n /// This error is returned when the method name specified in the request cannot be found.\n /// \n MethodNotFound = -32601,\n\n /// \n /// Indicates that one or more parameters provided in the request are invalid.\n /// \n /// \n /// This error is returned when the parameters do not match the expected method signature or constraints.\n /// This includes cases where required parameters are missing or not understood, such as when a name for\n /// a tool or prompt is not recognized.\n /// \n InvalidParams = -32602,\n\n /// \n /// Indicates that an internal error occurred while processing the request.\n /// \n /// \n /// This error is used when the endpoint encounters an unexpected condition that prevents it from fulfilling the request.\n /// \n InternalError = -32603,\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/NopProgress.cs", "namespace ModelContextProtocol;\n\n/// Provides an that's a nop.\ninternal sealed class NullProgress : IProgress\n{\n /// \n /// Gets the singleton instance of the class that performs no operations when progress is reported.\n /// \n /// \n /// Use this property when you need to provide an implementation \n /// but don't need to track or report actual progress.\n /// \n public static NullProgress Instance { get; } = new();\n\n /// \n public void Report(ProgressNotificationValue value)\n {\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithToolsFromAssembly, it enables automatic registration of tools without explicitly listing each tool\n/// class. The attribute is not necessary when a reference to the type is provided directly to a method like WithTools.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// tools must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerToolTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithPromptsFromAssembly, it enables automatic registration of prompts without explicitly listing each prompt class.\n/// The attribute is not necessary when a reference to the type is provided directly to a method like WithPrompts.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// prompts must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerPromptTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration request for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationRequest\n{\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public required string[] RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the human-readable name of the client.\n /// \n [JsonPropertyName(\"client_name\")]\n public string? ClientName { get; init; }\n\n /// \n /// Gets or sets the URL of the client's home page.\n /// \n [JsonPropertyName(\"client_uri\")]\n public string? ClientUri { get; init; }\n\n /// \n /// Gets or sets the scope values that the client will use.\n /// \n [JsonPropertyName(\"scope\")]\n public string? Scope { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available tools.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available tools on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many tools.\n/// The server can provide the property to indicate there are more\n/// tools available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListToolsResult : PaginatedResult\n{\n /// \n /// The server's response to a tools/list request from the client.\n /// \n [JsonPropertyName(\"tools\")]\n public IList Tools { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides configuration options for creating instances.\n/// \n/// \n/// These options are typically passed to when creating a client.\n/// They define client capabilities, protocol version, and other client-specific settings.\n/// \npublic sealed class McpClientOptions\n{\n /// \n /// Gets or sets information about this client implementation, including its name and version.\n /// \n /// \n /// \n /// This information is sent to the server during initialization to identify the client.\n /// It's often displayed in server logs and can be used for debugging and compatibility checks.\n /// \n /// \n /// When not specified, information sourced from the current process will be used.\n /// \n /// \n public Implementation? ClientInfo { get; set; }\n\n /// \n /// Gets or sets the client capabilities to advertise to the server.\n /// \n public ClientCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version to request from the server, using a date-based versioning scheme.\n /// \n /// \n /// \n /// The protocol version is a key part of the initialization handshake. The client and server must \n /// agree on a compatible protocol version to communicate successfully.\n /// \n /// \n /// If non-, this version will be sent to the server, and the handshake\n /// will fail if the version in the server's response does not match this version.\n /// If , the client will request the latest version supported by the server\n /// but will allow any supported version that the server advertizes in its response.\n /// \n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout for the client-server initialization handshake sequence.\n /// \n /// \n /// \n /// This timeout determines how long the client will wait for the server to respond during\n /// the initialization protocol handshake. If the server doesn't respond within this timeframe,\n /// an exception will be thrown.\n /// \n /// \n /// Setting an appropriate timeout prevents the client from hanging indefinitely when\n /// connecting to unresponsive servers.\n /// \n /// The default value is 60 seconds.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices;\n\n[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]\ninternal sealed class CallerArgumentExpressionAttribute : Attribute\n{\n public CallerArgumentExpressionAttribute(string parameterName)\n {\n ParameterName = parameterName;\n }\n\n public string ParameterName { get; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Prompt.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a prompt that the server offers.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Prompt : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets an optional description of what this prompt provides.\n /// \n /// \n /// \n /// This description helps developers understand the purpose and use cases for the prompt.\n /// It should explain what the prompt is designed to accomplish and any important context.\n /// \n /// \n /// The description is typically used in documentation, UI displays, and for providing context\n /// to client applications that may need to choose between multiple available prompts.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a list of arguments that this prompt accepts for templating and customization.\n /// \n /// \n /// \n /// This list defines the arguments that can be provided when requesting the prompt.\n /// Each argument specifies metadata like name, description, and whether it's required.\n /// \n /// \n /// When a client makes a request, it can provide values for these arguments\n /// which will be substituted into the prompt template or otherwise used to render the prompt.\n /// \n /// \n [JsonPropertyName(\"arguments\")]\n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/CancellationTokenSourceExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class CancellationTokenSourceExtensions\n{\n public static Task CancelAsync(this CancellationTokenSource cancellationTokenSource)\n {\n Throw.IfNull(cancellationTokenSource);\n\n cancellationTokenSource.Cancel();\n return Task.CompletedTask;\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParamsMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides metadata related to the request that provides additional protocol-level information.\n/// \n/// \n/// This class contains properties that are used by the Model Context Protocol\n/// for features like progress tracking and other protocol-specific capabilities.\n/// \npublic sealed class RequestParamsMetadata\n{\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n /// \n /// The receiver is not obligated to provide these notifications.\n /// \n [JsonPropertyName(\"progressToken\")]\n public ProgressToken? ProgressToken { get; set; } = default!;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// The server will respond with a containing the result of the tool invocation.\n/// See the schema for details.\n/// \npublic sealed class CallToolRequestParams : RequestParams\n{\n /// Gets or sets the name of the tool to invoke.\n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets optional arguments to pass to the tool when invoking it on the server.\n /// \n /// \n /// This dictionary contains the parameter values to be passed to the tool. Each key-value pair represents \n /// a parameter name and its corresponding argument value.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for paginated requests.\n/// \n/// \n/// See the schema for details\n/// \npublic abstract class PaginatedRequestParams : RequestParams\n{\n /// Prevent external derivations.\n private protected PaginatedRequestParams()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the current pagination position.\n /// \n /// \n /// If provided, the server should return results starting after this cursor.\n /// This value should be obtained from the \n /// property of a previous request's response.\n /// \n [JsonPropertyName(\"cursor\")]\n public string? Cursor { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelHint.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides hints to use for model selection.\n/// \n/// \n/// \n/// When multiple hints are specified in , they are evaluated in order,\n/// with the first match taking precedence. Clients should prioritize these hints over numeric priorities.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelHint\n{\n /// \n /// Gets or sets a hint for a model name.\n /// \n /// \n /// The specified string can be a partial or full model name. Clients may also \n /// map hints to equivalent models from different providers. Clients make the final model\n /// selection based on these preferences and their available models.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a prompt provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting prompt.\n/// See the schema for details.\n/// \npublic sealed class GetPromptRequestParams : RequestParams\n{\n /// \n /// Gets or sets the name of the prompt.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets arguments to use for templating the prompt when retrieving it from the server.\n /// \n /// \n /// Typically, these arguments are used to replace placeholders in prompt templates. The keys in this dictionary\n /// should match the names defined in the prompt's list. However, the server may\n /// choose to use these arguments in any way it deems appropriate to generate the prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from \n/// a client to ask a server for auto-completion suggestions.\n/// \n/// \n/// \n/// is used in the Model Context Protocol completion workflow\n/// to provide intelligent suggestions for partial inputs related to resources, prompts, or other referenceable entities.\n/// The completion mechanism in MCP allows clients to request suggestions based on partial inputs.\n/// The server will respond with a containing matching values.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteRequestParams : RequestParams\n{\n /// \n /// Gets or sets the reference's information.\n /// \n [JsonPropertyName(\"ref\")]\n public required Reference Ref { get; init; }\n\n /// \n /// Gets or sets the argument information for the completion request, specifying what is being completed\n /// and the current partial input.\n /// \n [JsonPropertyName(\"argument\")]\n public required Argument Argument { get; init; }\n\n /// \n /// Gets or sets additional, optional context for completions.\n /// \n [JsonPropertyName(\"context\")]\n public CompleteContext? Context { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationResponse.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration response for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationResponse\n{\n /// \n /// Gets or sets the client identifier.\n /// \n [JsonPropertyName(\"client_id\")]\n public required string ClientId { get; init; }\n\n /// \n /// Gets or sets the client secret.\n /// \n [JsonPropertyName(\"client_secret\")]\n public string? ClientSecret { get; init; }\n\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public string[]? RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the client ID issued timestamp.\n /// \n [JsonPropertyName(\"client_id_issued_at\")]\n public long? ClientIdIssuedAt { get; init; }\n\n /// \n /// Gets or sets the client secret expiration time.\n /// \n [JsonPropertyName(\"client_secret_expires_at\")]\n public long? ClientSecretExpiresAt { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available prompts.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available prompts on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many prompts.\n/// The server can provide the property to indicate there are more\n/// prompts available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListPromptsResult : PaginatedResult\n{\n /// \n /// A list of prompts or prompt templates that the server offers.\n /// \n [JsonPropertyName(\"prompts\")]\n public IList Prompts { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingMessageNotificationParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a log message is generated.\n/// \n/// \n/// \n/// Logging notifications allow servers to communicate diagnostic information to clients with varying severity levels.\n/// Clients can filter these messages based on the and properties.\n/// \n/// \n/// If no request has been sent from the client, the server may decide which\n/// messages to send automatically.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class LoggingMessageNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the severity of this log message.\n /// \n [JsonPropertyName(\"level\")]\n public LoggingLevel Level { get; init; }\n\n /// \n /// Gets or sets an optional name of the logger issuing this message.\n /// \n /// \n /// \n /// typically represents a category or component in the server's logging system.\n /// The logger name is useful for filtering and routing log messages in client applications.\n /// \n /// \n /// When implementing custom servers, choose clear, hierarchical logger names to help\n /// clients understand the source of log messages.\n /// \n /// \n [JsonPropertyName(\"logger\")]\n public string? Logger { get; init; }\n\n /// \n /// Gets or sets the data to be logged, such as a string message.\n /// \n [JsonPropertyName(\"data\")]\n public JsonElement? Data { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcNotification.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification message in the JSON-RPC protocol.\n/// \n/// \n/// Notifications are messages that do not require a response and are not matched with a response message.\n/// They are useful for one-way communication, such as log notifications and progress updates.\n/// Unlike requests, notifications do not include an ID field, since there will be no response to match with it.\n/// \npublic sealed class JsonRpcNotification : JsonRpcMessage\n{\n /// \n /// Gets or sets the name of the notification method.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Gets or sets optional parameters for the notification.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ServerCapabilities.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a server may support.\n/// \n/// \n/// \n/// Server capabilities define the features and functionality available when clients connect.\n/// These capabilities are advertised to clients during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ServerCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the server supports.\n /// \n /// \n /// \n /// The dictionary allows servers to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Clients should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets a server's logging capability, supporting sending log messages to the client.\n /// \n [JsonPropertyName(\"logging\")]\n public LoggingCapability? Logging { get; set; }\n\n /// \n /// Gets or sets a server's prompts capability for serving predefined prompt templates that clients can discover and use.\n /// \n [JsonPropertyName(\"prompts\")]\n public PromptsCapability? Prompts { get; set; }\n\n /// \n /// Gets or sets a server's resources capability for serving predefined resources that clients can discover and use.\n /// \n [JsonPropertyName(\"resources\")]\n public ResourcesCapability? Resources { get; set; }\n\n /// \n /// Gets or sets a server's tools capability for listing tools that a client is able to invoke.\n /// \n [JsonPropertyName(\"tools\")]\n public ToolsCapability? Tools { get; set; }\n\n /// \n /// Gets or sets a server's completions capability for supporting argument auto-completion suggestions.\n /// \n [JsonPropertyName(\"completions\")]\n public CompletionsCapability? Completions { get; set; }\n\n /// Gets or sets notification handlers to register with the server.\n /// \n /// \n /// When constructed, the server will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The server will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the server to respond to client-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the server for the lifetime of the server.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/IBaseMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// Provides a base interface for metadata with name (identifier) and title (display name) properties.\npublic interface IBaseMetadata\n{\n /// \n /// Gets or sets the unique identifier for this item.\n /// \n [JsonPropertyName(\"name\")]\n string Name { get; set; }\n\n /// \n /// Gets or sets a title.\n /// \n /// \n /// This is intended for UI and end-user contexts. It is optimized to be human-readable and easily understood,\n /// even by those unfamiliar with domain-specific terminology.\n /// If not provided, may be used for display (except for tools, where , if present, \n /// should be given precedence over using ).\n /// \n [JsonPropertyName(\"title\")]\n string? Title { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcResponse.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A successful response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Response messages are sent in reply to a request message and contain the result of the method execution.\n/// Each response includes the same ID as the original request, allowing the sender to match responses\n/// with their corresponding requests.\n/// \n/// \n/// This class represents a successful response with a result. For error responses, see .\n/// \n/// \npublic sealed class JsonRpcResponse : JsonRpcMessageWithId\n{\n /// \n /// Gets the result of the method invocation.\n /// \n /// \n /// This property contains the result data returned by the server in response to the JSON-RPC method request.\n /// \n [JsonPropertyName(\"result\")]\n public required JsonNode? Result { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Implementation.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides the name and version of an MCP implementation.\n/// \n/// \n/// \n/// The class is used to identify MCP clients and servers during the initialization handshake.\n/// It provides version and name information that can be used for compatibility checks, logging, and debugging.\n/// \n/// \n/// Both clients and servers provide this information during connection establishment.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class Implementation : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the version of the implementation.\n /// \n /// \n /// The version is used during client-server handshake to identify implementation versions,\n /// which can be important for troubleshooting compatibility issues or when reporting bugs.\n /// \n [JsonPropertyName(\"version\")]\n public required string Version { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resources available from the server.\n/// \n/// \n/// The server responds with a containing the available resources.\n/// See the schema for details.\n/// \npublic sealed class ListResourcesRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a server to request\n/// a list of roots available from the client.\n/// \n/// \n/// The client responds with a containing the client's roots.\n/// See the schema for details.\n/// \npublic sealed class ListRootsRequestParams : RequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional context information for completion requests.\n/// \n/// \n/// This context provides information that helps the server generate more relevant \n/// completion suggestions, such as previously resolved variables in a template.\n/// \npublic sealed class CompleteContext\n{\n /// \n /// Gets or sets previously-resolved variables in a URI template or prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IClientTransport.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a transport mechanism for Model Context Protocol (MCP) client-to-server communication.\n/// \n/// \n/// \n/// The interface abstracts the communication layer between MCP clients\n/// and servers, allowing different transport protocols to be used interchangeably.\n/// \n/// \n/// When creating an , is typically used, and is\n/// provided with the based on expected server configuration.\n/// \n/// \npublic interface IClientTransport\n{\n /// \n /// Gets a transport identifier, used for logging purposes.\n /// \n string Name { get; }\n\n /// \n /// Asynchronously establishes a transport session with an MCP server and returns a transport for the duplex message stream.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// Returns an interface for the duplex message stream.\n /// \n /// \n /// This method is responsible for initializing the connection to the server using the specific transport \n /// mechanism implemented by the derived class. The returned interface \n /// provides methods to send and receive messages over the established connection.\n /// \n /// \n /// The lifetime of the returned instance is typically managed by the \n /// that uses this transport. When the client is disposed, it will dispose\n /// the transport session as well.\n /// \n /// \n /// This method is used by to initialize the connection.\n /// \n /// \n /// The transport connection could not be established.\n Task ConnectAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the logging capability configuration for a Model Context Protocol server.\n/// \n/// \n/// This capability allows clients to set the logging level and receive log messages from the server.\n/// See the schema for details.\n/// \npublic sealed class LoggingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for set logging level requests from clients.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SetLevelRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to enable or adjust logging.\n/// \n/// \n/// This request allows clients to configure the level of logging information they want to receive from the server.\n/// The server will send notifications for log events at the specified level and all higher (more severe) levels.\n/// \npublic sealed class SetLevelRequestParams : RequestParams\n{\n /// \n /// Gets or sets the level of logging that the client wants to receive from the server. \n /// \n [JsonPropertyName(\"level\")]\n public required LoggingLevel Level { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionId.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed class StatelessSessionId\n{\n [JsonPropertyName(\"clientInfo\")]\n public Implementation? ClientInfo { get; init; }\n\n [JsonPropertyName(\"userIdClaim\")]\n public UserIdClaim? UserIdClaim { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingLevel.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Indicates the severity of a log message.\n/// \n/// \n/// These map to syslog message severities, as specified in RFC-5424.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum LoggingLevel\n{\n /// Detailed debug information, typically only valuable to developers.\n [JsonStringEnumMemberName(\"debug\")]\n Debug,\n\n /// Normal operational messages that require no action.\n [JsonStringEnumMemberName(\"info\")]\n Info,\n\n /// Normal but significant events that might deserve attention.\n [JsonStringEnumMemberName(\"notice\")]\n Notice,\n\n /// Warning conditions that don't represent an error but indicate potential issues.\n [JsonStringEnumMemberName(\"warning\")]\n Warning,\n\n /// Error conditions that should be addressed but don't require immediate action.\n [JsonStringEnumMemberName(\"error\")]\n Error,\n\n /// Critical conditions that require immediate attention.\n [JsonStringEnumMemberName(\"critical\")]\n Critical,\n\n /// Action must be taken immediately to address the condition.\n [JsonStringEnumMemberName(\"alert\")]\n Alert,\n\n /// System is unusable and requires immediate attention.\n [JsonStringEnumMemberName(\"emergency\")]\n Emergency\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for notification parameters.\n/// \npublic abstract class NotificationParams\n{\n /// Prevent external derivations.\n private protected NotificationParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/RequiredMemberAttribute.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Specifies that a type has required members or that a member is required.\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\n [EditorBrowsable(EditorBrowsableState.Never)]\n internal sealed class RequiredMemberAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IMcpClient.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) client that connects to and communicates with an MCP server.\n/// \npublic interface IMcpClient : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the connected server.\n /// \n /// The client is not connected.\n ServerCapabilities ServerCapabilities { get; }\n\n /// \n /// Gets the implementation information of the connected server.\n /// \n /// \n /// \n /// This property provides identification details about the connected server, including its name and version.\n /// It is populated during the initialization handshake and is available after a successful connection.\n /// \n /// \n /// This information can be useful for logging, debugging, compatibility checks, and displaying server\n /// information to users.\n /// \n /// \n /// The client is not connected.\n Implementation ServerInfo { get; }\n\n /// \n /// Gets any instructions describing how to use the connected server and its features.\n /// \n /// \n /// \n /// This property contains instructions provided by the server during initialization that explain\n /// how to effectively use its capabilities. These instructions can include details about available\n /// tools, expected input formats, limitations, or any other helpful information.\n /// \n /// \n /// This can be used by clients to improve an LLM's understanding of available tools, prompts, and resources. \n /// It can be thought of like a \"hint\" to the model and may be added to a system prompt.\n /// \n /// \n string? ServerInstructions { get; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/IsExternalInit.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Reserved to be used by the compiler for tracking metadata.\n /// This class should not be used by developers in source code.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n internal static class IsExternalInit;\n}\n#else\n// The compiler emits a reference to the internal copy of this type in the non-.NET builds,\n// so we must include a forward to be compatible.\n[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExternalInit))]\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Result.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads.\n/// \npublic abstract class Result\n{\n /// Prevent external derivations.\n private protected Result()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServerPrimitive.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Represents an MCP server primitive, like a tool or a prompt.\n/// \npublic interface IMcpServerPrimitive\n{\n /// Gets the unique identifier of the primitive.\n string Id { get; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMemberTypes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Specifies the types of members that are dynamically accessed.\n///\n/// This enumeration has a attribute that allows a\n/// bitwise combination of its member values.\n/// \n[Flags]\ninternal enum DynamicallyAccessedMemberTypes\n{\n /// \n /// Specifies no members.\n /// \n None = 0,\n\n /// \n /// Specifies the default, parameterless public constructor.\n /// \n PublicParameterlessConstructor = 0x0001,\n\n /// \n /// Specifies all public constructors.\n /// \n PublicConstructors = 0x0002 | PublicParameterlessConstructor,\n\n /// \n /// Specifies all non-public constructors.\n /// \n NonPublicConstructors = 0x0004,\n\n /// \n /// Specifies all public methods.\n /// \n PublicMethods = 0x0008,\n\n /// \n /// Specifies all non-public methods.\n /// \n NonPublicMethods = 0x0010,\n\n /// \n /// Specifies all public fields.\n /// \n PublicFields = 0x0020,\n\n /// \n /// Specifies all non-public fields.\n /// \n NonPublicFields = 0x0040,\n\n /// \n /// Specifies all public nested types.\n /// \n PublicNestedTypes = 0x0080,\n\n /// \n /// Specifies all non-public nested types.\n /// \n NonPublicNestedTypes = 0x0100,\n\n /// \n /// Specifies all public properties.\n /// \n PublicProperties = 0x0200,\n\n /// \n /// Specifies all non-public properties.\n /// \n NonPublicProperties = 0x0400,\n\n /// \n /// Specifies all public events.\n /// \n PublicEvents = 0x0800,\n\n /// \n /// Specifies all non-public events.\n /// \n NonPublicEvents = 0x1000,\n\n /// \n /// Specifies all interfaces implemented by the type.\n /// \n Interfaces = 0x2000,\n\n /// \n /// Specifies all non-public constructors, including those inherited from base classes.\n /// \n NonPublicConstructorsWithInherited = NonPublicConstructors | 0x4000,\n\n /// \n /// Specifies all non-public methods, including those inherited from base classes.\n /// \n NonPublicMethodsWithInherited = NonPublicMethods | 0x8000,\n\n /// \n /// Specifies all non-public fields, including those inherited from base classes.\n /// \n NonPublicFieldsWithInherited = NonPublicFields | 0x10000,\n\n /// \n /// Specifies all non-public nested types, including those inherited from base classes.\n /// \n NonPublicNestedTypesWithInherited = NonPublicNestedTypes | 0x20000,\n\n /// \n /// Specifies all non-public properties, including those inherited from base classes.\n /// \n NonPublicPropertiesWithInherited = NonPublicProperties | 0x40000,\n\n /// \n /// Specifies all non-public events, including those inherited from base classes.\n /// \n NonPublicEventsWithInherited = NonPublicEvents | 0x80000,\n\n /// \n /// Specifies all public constructors, including those inherited from base classes.\n /// \n PublicConstructorsWithInherited = PublicConstructors | 0x100000,\n\n /// \n /// Specifies all public nested types, including those inherited from base classes.\n /// \n PublicNestedTypesWithInherited = PublicNestedTypes | 0x200000,\n\n /// \n /// Specifies all constructors, including those inherited from base classes.\n /// \n AllConstructors = PublicConstructorsWithInherited | NonPublicConstructorsWithInherited,\n\n /// \n /// Specifies all methods, including those inherited from base classes.\n /// \n AllMethods = PublicMethods | NonPublicMethodsWithInherited,\n\n /// \n /// Specifies all fields, including those inherited from base classes.\n /// \n AllFields = PublicFields | NonPublicFieldsWithInherited,\n\n /// \n /// Specifies all nested types, including those inherited from base classes.\n /// \n AllNestedTypes = PublicNestedTypesWithInherited | NonPublicNestedTypesWithInherited,\n\n /// \n /// Specifies all properties, including those inherited from base classes.\n /// \n AllProperties = PublicProperties | NonPublicPropertiesWithInherited,\n\n /// \n /// Specifies all events, including those inherited from base classes.\n /// \n AllEvents = PublicEvents | NonPublicEventsWithInherited,\n\n /// \n /// Specifies all members.\n /// \n All = ~None\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitationCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to provide server-requested additional information during interactions.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to elicitation requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to provide additional information\n/// during interactions. The client must set a to process these requests.\n/// \n/// \npublic sealed class ElicitationCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to provide additional\n /// information during interactions. The client must set this property for the elicitation capability to work.\n /// \n /// \n /// The handler receives message parameters and a cancellation token.\n /// It should return a containing the response to the elicitation request.\n /// \n /// \n [JsonIgnore]\n public Func>? ElicitationHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of resources it can read from has changed. \n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/ForceYielding.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading;\n\n/// \n/// await default(ForceYielding) to provide the same behavior as\n/// await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding).\n/// \ninternal readonly struct ForceYielding : INotifyCompletion, ICriticalNotifyCompletion\n{\n public ForceYielding GetAwaiter() => this;\n\n public bool IsCompleted => false;\n public void OnCompleted(Action continuation) => ThreadPool.QueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void UnsafeOnCompleted(Action continuation) => ThreadPool.UnsafeQueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void GetResult() { }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads that support cursor-based pagination.\n/// \n/// \n/// \n/// Pagination allows API responses to be broken into smaller, manageable chunks when\n/// there are potentially many results to return or when dynamically-computed results\n/// may incur measurable latency.\n/// \n/// \n/// Classes that inherit from implement cursor-based pagination,\n/// where the property serves as an opaque token pointing to the next \n/// set of results.\n/// \n/// \npublic abstract class PaginatedResult : Result\n{\n private protected PaginatedResult()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the pagination position after the last returned result.\n /// \n /// \n /// When a paginated result has more data available, the \n /// property will contain a non- token that can be used in subsequent requests\n /// to fetch the next page. When there are no more results to return, the property\n /// will be .\n /// \n public string? NextCursor { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Role.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the type of role in the Model Context Protocol conversation.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum Role\n{\n /// \n /// Corresponds to a human user in the conversation.\n /// \n [JsonStringEnumMemberName(\"user\")]\n User,\n\n /// \n /// Corresponds to the AI assistant in the conversation.\n /// \n [JsonStringEnumMemberName(\"assistant\")]\n Assistant\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/SetsRequiredMembersAttribute.cs", "#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]\n internal sealed class SetsRequiredMembersAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/ProgressNotificationValue.cs", "namespace ModelContextProtocol;\n\n/// Provides a progress value that can be sent using .\npublic sealed class ProgressNotificationValue\n{\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// \n /// This value typically represents either a percentage (0-100) or the number of items processed so far (when used with the property).\n /// \n /// \n /// When reporting progress, this value should increase monotonically as the operation proceeds.\n /// Values are typically between 0 and 100 when representing percentages, or can be any positive number\n /// when representing completed items in combination with the property.\n /// \n /// \n public required float Progress { get; init; }\n\n /// Gets or sets the total number of items to process (or total progress required), if known.\n public float? Total { get; init; }\n\n /// Gets or sets an optional message describing the current progress.\n public string? Message { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of tools available from the server.\n/// \n/// \n/// The server responds with a containing the available tools.\n/// See the schema for details.\n/// \npublic sealed class ListToolsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of prompts available from the server.\n/// \n/// \n/// The server responds with a containing the available prompts.\n/// See the schema for details.\n/// \npublic sealed class ListPromptsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PingResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request in the Model Context Protocol.\n/// \n/// \n/// \n/// The is returned in response to a request, \n/// which is used to verify that the connection between client and server is still alive and responsive. \n/// Since this is a simple connectivity check, the result is an empty object containing no data.\n/// \n/// \n/// Ping requests can be initiated by either the client or the server to check if the other party\n/// is still responsive.\n/// \n/// \npublic sealed class PingResult : Result;"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// sent from the client to the server after initialization has finished.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class InitializedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the client to the server, informing it that the list of roots has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of tools it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ToolListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptListChangedNotification .cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of prompts it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionIdJsonContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\n[JsonSerializable(typeof(StatelessSessionId))]\ninternal sealed partial class StatelessSessionIdJsonContext : JsonSerializerContext;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/HttpTransportMode.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Specifies the transport mode for HTTP client connections.\n/// \npublic enum HttpTransportMode\n{\n /// \n /// Automatically detect the appropriate transport by trying Streamable HTTP first, then falling back to SSE if that fails.\n /// This is the recommended mode for maximum compatibility.\n /// \n AutoDetect,\n\n /// \n /// Use only the Streamable HTTP transport.\n /// \n StreamableHttp,\n\n /// \n /// Use only the HTTP with SSE transport.\n /// \n Sse\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/UserIdClaim.cs", "namespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed record UserIdClaim(string Type, string Value, string Issuer);\n"]], "task_instance_info": {"created_time": "2025-08-20 18:39:06", "created_task_model": "DeepSeek-R1", "class_skeleton": "[McpServerResourceType]\npublic\nclass\nSimpleResourceType\n{\n[McpServerResource(UriTemplate = \"test://direct/text/resource\", Name = \"Direct Text Resource\", MimeType = \"text/plain\")] [Description(\"A direct text resource\")] public static string DirectTextResource () => \"This is a direct resource\" {}\n[McpServerResource(UriTemplate = \"test://template/resource/{id}\", Name = \"Template Resource\")] [Description(\"A template resource with a numeric ID\")] public static ResourceContents TemplateResource (RequestContext requestContext, int id) {}\n}", "code_description": "This code segment functions to: Define server-side resource handlers that retrieve and format data based on URI patterns, including static text responses and dynamic resource lookups using identifier validation. It implements content-type discrimination between textual and binary data representations while enforcing request parameter constraints through index boundary checks."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test://direct/text/resource\", Name = \"Direct Text Resource\", MimeType = \"text/plain\")]\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n\n [McpServerResource(UriTemplate = \"test://template/resource/{id}\", Name = \"Template Resource\")]\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id) \n => new ResourceContents { Content = $\"Template resource ID: {id}\", MimeType = \"text/plain\" };\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-39-24"}, "editdistance_info": {"edit_distance": 47.7273, "calculate_time": "2025-08-20 18:39:24", "true_code_clean": "[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test:\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n [McpServerResource(UriTemplate = \"test:\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id)\n {\n int index = id - 1;\n if ((uint)index >= ResourceGenerator.Resources.Count)\n {\n throw new NotSupportedException($\"Unknown resource: {requestContext.Params?.Uri}\");\n }\n var resource = ResourceGenerator.Resources[index];\n return resource.MimeType == \"text/plain\" ?\n new TextResourceContents\n {\n Text = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n } :\n new BlobResourceContents\n {\n Blob = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n };\n }\n}", "predict_code_clean": "[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test:\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n [McpServerResource(UriTemplate = \"test:\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id) \n => new ResourceContents { Content = $\"Template resource ID: {id}\", MimeType = \"text/plain\" };\n}"}} {"repo_name": "csharp-sdk", "file_name": "/csharp-sdk/src/Common/CancellableStreamReader/TextReaderExtensions.cs", "inference_info": {"prefix_code": "namespace System.IO;\n\n", "suffix_code": "", "middle_code": "internal static class TextReaderExtensions\n{\n public static ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n {\n if (reader is CancellableStreamReader cancellableReader)\n {\n return cancellableReader.ReadLineAsync(cancellationToken)!;\n }\n cancellationToken.ThrowIfCancellationRequested();\n return new ValueTask(reader.ReadLineAsync());\n }\n}", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/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.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/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/Common/Polyfills/System/Threading/Channels/ChannelExtensions.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading.Channels;\n\ninternal static class ChannelExtensions\n{\n public static async IAsyncEnumerable ReadAllAsync(this ChannelReader reader, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))\n {\n while (reader.TryRead(out var item))\n {\n yield return item;\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Tasks/TaskExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class TaskExtensions\n{\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n await WaitAsync((Task)task, timeout, cancellationToken).ConfigureAwait(false);\n return task.Result;\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(task);\n\n if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan)\n {\n throw new ArgumentOutOfRangeException(nameof(timeout));\n }\n\n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n cts.CancelAfter(timeout);\n\n var cancellationTask = new TaskCompletionSource();\n using var _ = cts.Token.Register(tcs => ((TaskCompletionSource)tcs!).TrySetResult(true), cancellationTask);\n await Task.WhenAny(task, cancellationTask.Task).ConfigureAwait(false);\n \n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n throw new TimeoutException();\n }\n }\n\n await task.ConfigureAwait(false);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Net.ServerSentEvents;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Handles processing the request/response body pairs for the Streamable HTTP transport.\n/// This is typically used via .\n/// \ninternal sealed class StreamableHttpPostTransport(StreamableHttpServerTransport parentTransport, IDuplexPipe httpBodies) : ITransport\n{\n private readonly SseWriter _sseWriter = new();\n private RequestId _pendingRequest;\n\n public ChannelReader MessageReader => throw new NotSupportedException(\"JsonRpcMessage.RelatedTransport should only be used for sending messages.\");\n\n string? ITransport.SessionId => parentTransport.SessionId;\n\n /// \n /// True, if data was written to the respond body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async ValueTask RunAsync(CancellationToken cancellationToken)\n {\n var message = await JsonSerializer.DeserializeAsync(httpBodies.Input.AsStream(),\n McpJsonUtilities.JsonContext.Default.JsonRpcMessage, cancellationToken).ConfigureAwait(false);\n await OnMessageReceivedAsync(message, cancellationToken).ConfigureAwait(false);\n\n if (_pendingRequest.Id is null)\n {\n return false;\n }\n\n _sseWriter.MessageFilter = StopOnFinalResponseFilter;\n await _sseWriter.WriteAllAsync(httpBodies.Output.AsStream(), cancellationToken).ConfigureAwait(false);\n return true;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (parentTransport.Stateless && message is JsonRpcRequest)\n {\n throw new InvalidOperationException(\"Server to client requests are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n private async IAsyncEnumerable> StopOnFinalResponseFilter(IAsyncEnumerable> messages, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n await foreach (var message in messages.WithCancellation(cancellationToken))\n {\n yield return message;\n\n if (message.Data is JsonRpcResponse or JsonRpcError && ((JsonRpcMessageWithId)message.Data).Id == _pendingRequest)\n {\n // Complete the SSE response stream now that all pending requests have been processed.\n break;\n }\n }\n }\n\n private async ValueTask OnMessageReceivedAsync(JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (message is null)\n {\n throw new InvalidOperationException(\"Received invalid null message.\");\n }\n\n if (message is JsonRpcRequest request)\n {\n _pendingRequest = request.Id;\n\n // Invoke the initialize request callback if applicable.\n if (parentTransport.OnInitRequestReceived is { } onInitRequest && request.Method == RequestMethods.Initialize)\n {\n var initializeRequest = JsonSerializer.Deserialize(request.Params, McpJsonUtilities.JsonContext.Default.InitializeRequestParams);\n await onInitRequest(initializeRequest).ConfigureAwait(false);\n }\n }\n\n message.RelatedTransport = this;\n\n if (parentTransport.FlowExecutionContextFromRequests)\n {\n message.ExecutionContext = ExecutionContext.Capture();\n }\n\n await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseWriter.cs", "using ModelContextProtocol.Protocol;\nusing System.Buffers;\nusing System.Net.ServerSentEvents;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class SseWriter(string? messageEndpoint = null, BoundedChannelOptions? channelOptions = null) : IAsyncDisposable\n{\n private readonly Channel> _messages = Channel.CreateBounded>(channelOptions ?? new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private Utf8JsonWriter? _jsonWriter;\n private Task? _writeTask;\n private CancellationToken? _writeCancellationToken;\n\n private readonly SemaphoreSlim _disposeLock = new(1, 1);\n private bool _disposed;\n\n public Func>, CancellationToken, IAsyncEnumerable>>? MessageFilter { get; set; }\n\n public Task WriteAllAsync(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n // When messageEndpoint is set, the very first SSE event isn't really an IJsonRpcMessage, but there's no API to write a single\n // item of a different type, so we fib and special-case the \"endpoint\" event type in the formatter.\n if (messageEndpoint is not null && !_messages.Writer.TryWrite(new SseItem(null, \"endpoint\")))\n {\n throw new InvalidOperationException(\"You must call RunAsync before calling SendMessageAsync.\");\n }\n\n _writeCancellationToken = cancellationToken;\n\n var messages = _messages.Reader.ReadAllAsync(cancellationToken);\n if (MessageFilter is not null)\n {\n messages = MessageFilter(messages, cancellationToken);\n }\n\n _writeTask = SseFormatter.WriteAsync(messages, sseResponseStream, WriteJsonRpcMessageToBuffer, cancellationToken);\n return _writeTask;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(message);\n\n using var _ = await _disposeLock.LockAsync(cancellationToken).ConfigureAwait(false);\n\n if (_disposed)\n {\n // Don't throw an ODE, because this is disposed internally when the transport disconnects due to an abort\n // or sending all the responses for the a give given Streamable HTTP POST request, so the user might not be at fault.\n // There's precedence for no-oping here similar to writing to the response body of an aborted request in ASP.NET Core.\n return;\n }\n\n // Emit redundant \"event: message\" lines for better compatibility with other SDKs.\n await _messages.Writer.WriteAsync(new SseItem(message, SseParser.EventTypeDefault), cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);\n\n if (_disposed)\n {\n return;\n }\n\n _messages.Writer.Complete();\n try\n {\n if (_writeTask is not null)\n {\n await _writeTask.ConfigureAwait(false);\n }\n }\n catch (OperationCanceledException) when (_writeCancellationToken?.IsCancellationRequested == true)\n {\n // Ignore exceptions caused by intentional cancellation during shutdown.\n }\n finally\n {\n _jsonWriter?.Dispose();\n _disposed = true;\n }\n }\n\n private void WriteJsonRpcMessageToBuffer(SseItem item, IBufferWriter writer)\n {\n if (item.EventType == \"endpoint\" && messageEndpoint is not null)\n {\n writer.Write(Encoding.UTF8.GetBytes(messageEndpoint));\n return;\n }\n\n JsonSerializer.Serialize(GetUtf8JsonWriter(writer), item.Data, McpJsonUtilities.JsonContext.Default.JsonRpcMessage!);\n }\n\n private Utf8JsonWriter GetUtf8JsonWriter(IBufferWriter writer)\n {\n if (_jsonWriter is null)\n {\n _jsonWriter = new Utf8JsonWriter(writer);\n }\n else\n {\n _jsonWriter.Reset(writer);\n }\n\n return _jsonWriter;\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Net/Http/HttpClientExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Net.Http;\n\ninternal static class HttpClientExtensions\n{\n public static async Task ReadAsStreamAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStreamAsync();\n }\n\n public static async Task ReadAsStringAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStringAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/IO/StreamExtensions.cs", "using ModelContextProtocol;\nusing System.Buffers;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n#if !NET\nnamespace System.IO;\n\ninternal static class StreamExtensions\n{\n public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return WriteAsyncCore(stream, buffer, cancellationToken);\n\n static async ValueTask WriteAsyncCore(Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n buffer.Span.CopyTo(array);\n await stream.WriteAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n\n public static ValueTask ReadAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.ReadAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return ReadAsyncCore(stream, buffer, cancellationToken);\n static async ValueTask ReadAsyncCore(Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n int bytesRead = await stream.ReadAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n array.AsSpan(0, bytesRead).CopyTo(buffer.Span);\n return bytesRead;\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/IO/TextWriterExtensions.cs", "#if !NET\nnamespace System.IO;\n\ninternal static class TextWriterExtensions\n{\n public static async Task FlushAsync(this TextWriter writer, CancellationToken cancellationToken)\n {\n cancellationToken.ThrowIfCancellationRequested();\n await writer.FlushAsync();\n }\n}\n#endif"], ["/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/Server/StreamableHttpServerTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as\n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \npublic sealed class StreamableHttpServerTransport : ITransport\n{\n // For JsonRpcMessages without a RelatedTransport, we don't want to block just because the client didn't make a GET request to handle unsolicited messages.\n private readonly SseWriter _sseWriter = new(channelOptions: new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n FullMode = BoundedChannelFullMode.DropOldest,\n });\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n private readonly CancellationTokenSource _disposeCts = new();\n\n private int _getRequestStarted;\n\n /// \n public string? SessionId { get; set; }\n\n /// \n /// Configures whether the transport should be in stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process. Unsolicited server-to-client messages are not supported in this mode,\n /// so calling results in an .\n /// Server-to-client requests are also unsupported, because the responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// \n public bool Stateless { get; init; }\n\n /// \n /// Gets a value indicating whether the execution context should flow from the calls to \n /// to the corresponding emitted by the .\n /// \n /// \n /// Defaults to .\n /// \n public bool FlowExecutionContextFromRequests { get; init; }\n\n /// \n /// Gets or sets a callback to be invoked before handling the initialize request.\n /// \n public Func? OnInitRequestReceived { get; set; }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n internal ChannelWriter MessageWriter => _incomingChannel.Writer;\n\n /// \n /// Handles an optional SSE GET request a client using the Streamable HTTP transport might make by\n /// writing any unsolicited JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The response stream to write MCP JSON-RPC messages as SSE events to.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task HandleGetRequest(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"GET requests are not supported in stateless mode.\");\n }\n\n if (Interlocked.Exchange(ref _getRequestStarted, 1) == 1)\n {\n throw new InvalidOperationException(\"Session resumption is not yet supported. Please start a new session.\");\n }\n\n // We do not need to reference _disposeCts like in HandlePostRequest, because the session ending completes the _sseWriter gracefully.\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles a Streamable HTTP POST request processing both the request body and response body ensuring that\n /// and other correlated messages are sent back to the client directly in response\n /// to the that initiated the message.\n /// \n /// The duplex pipe facilitates the reading and writing of HTTP request and response data.\n /// This token allows for the operation to be canceled if needed.\n /// \n /// True, if data was written to the response body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async Task HandlePostRequest(IDuplexPipe httpBodies, CancellationToken cancellationToken)\n {\n using var postCts = CancellationTokenSource.CreateLinkedTokenSource(_disposeCts.Token, cancellationToken);\n await using var postTransport = new StreamableHttpPostTransport(this, httpBodies);\n return await postTransport.RunAsync(postCts.Token).ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"Unsolicited server to client messages are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n }\n finally\n {\n try\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n finally\n {\n _disposeCts.Dispose();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StdioServerTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implemented via \"stdio\" (standard input/output).\n/// \npublic sealed class StdioServerTransport : StreamServerTransport\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The server options.\n /// Optional logger factory used for logging employed by the transport.\n /// is or contains a null name.\n public StdioServerTransport(McpServerOptions serverOptions, ILoggerFactory? loggerFactory = null)\n : this(GetServerName(serverOptions), loggerFactory: loggerFactory)\n {\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the server.\n /// Optional logger factory used for logging employed by the transport.\n /// is .\n public StdioServerTransport(string serverName, ILoggerFactory? loggerFactory = null)\n : base(new CancellableStdinStream(Console.OpenStandardInput()),\n new BufferedStream(Console.OpenStandardOutput()),\n serverName ?? throw new ArgumentNullException(nameof(serverName)),\n loggerFactory)\n {\n }\n\n private static string GetServerName(McpServerOptions serverOptions)\n {\n Throw.IfNull(serverOptions);\n\n return serverOptions.ServerInfo?.Name ?? McpServer.DefaultImplementation.Name;\n }\n\n // Neither WindowsConsoleStream nor UnixConsoleStream respect CancellationTokens or cancel any I/O on Dispose.\n // WindowsConsoleStream will return an EOS on Ctrl-C, but that is not the only reason the shutdownToken may fire.\n private sealed class CancellableStdinStream(Stream stdinStream) : Stream\n {\n public override bool CanRead => true;\n public override bool CanSeek => false;\n public override bool CanWrite => false;\n\n public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n => stdinStream.ReadAsync(buffer, offset, count, cancellationToken).WaitAsync(cancellationToken);\n\n#if NET\n public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)\n {\n ValueTask vt = stdinStream.ReadAsync(buffer, cancellationToken);\n return vt.IsCompletedSuccessfully ? vt : new(vt.AsTask().WaitAsync(cancellationToken));\n }\n#endif\n\n // The McpServer shouldn't call flush on the stdin Stream, but it doesn't need to throw just in case.\n public override void Flush() { }\n\n public override long Length => throw new NotSupportedException();\n\n public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }\n\n public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();\n\n public override void SetLength(long value) => throw new NotSupportedException();\n public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();\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.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 posts.\n internal static UserIdClaim? GetUserIdClaim(ClaimsPrincipal user)\n {\n if (user?.Identity?.IsAuthenticated != true)\n {\n return null;\n }\n\n var claim = user.FindFirst(ClaimTypes.NameIdentifier) ?? user.FindFirst(\"sub\") ?? user.FindFirst(ClaimTypes.Upn);\n\n if (claim is { } idClaim)\n {\n return new(idClaim.Type, idClaim.Value, idClaim.Issuer);\n }\n\n return null;\n }\n\n private static JsonTypeInfo GetRequiredJsonTypeInfo() => (JsonTypeInfo)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));\n\n private static bool MatchesApplicationJsonMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"application/json\");\n\n private static bool MatchesTextEventStreamMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"text/event-stream\");\n\n private sealed class HttpDuplexPipe(HttpContext context) : IDuplexPipe\n {\n public PipeReader Input => context.Request.BodyReader;\n public PipeWriter Output => context.Response.BodyWriter;\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.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/ModelContextProtocol.Core/Server/McpServerExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides extension methods for interacting with an instance.\n/// \npublic static class McpServerExtensions\n{\n /// \n /// Requests to sample an LLM via the client using the specified request parameters.\n /// \n /// The server instance initiating the request.\n /// The parameters for the sampling request.\n /// The to monitor for cancellation requests.\n /// A task containing the sampling result from the client.\n /// is .\n /// The client does not support sampling.\n /// \n /// This method requires the client to support sampling capabilities.\n /// It allows detailed control over sampling parameters including messages, system prompt, temperature, \n /// and token limits.\n /// \n public static ValueTask SampleAsync(\n this IMcpServer server, CreateMessageRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.SamplingCreateMessage,\n request,\n McpJsonUtilities.JsonContext.Default.CreateMessageRequestParams,\n McpJsonUtilities.JsonContext.Default.CreateMessageResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests to sample an LLM via the client using the provided chat messages and options.\n /// \n /// The server initiating the request.\n /// The messages to send as part of the request.\n /// The options to use for the request, including model parameters and constraints.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the chat response from the model.\n /// is .\n /// is .\n /// The client does not support sampling.\n /// \n /// This method converts the provided chat messages into a format suitable for the sampling API,\n /// handling different content types such as text, images, and audio.\n /// \n public static async Task SampleAsync(\n this IMcpServer server,\n IEnumerable messages, ChatOptions? options = default, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n Throw.IfNull(messages);\n\n StringBuilder? systemPrompt = null;\n\n if (options?.Instructions is { } instructions)\n {\n (systemPrompt ??= new()).Append(instructions);\n }\n\n List samplingMessages = [];\n foreach (var message in messages)\n {\n if (message.Role == ChatRole.System)\n {\n if (systemPrompt is null)\n {\n systemPrompt = new();\n }\n else\n {\n systemPrompt.AppendLine();\n }\n\n systemPrompt.Append(message.Text);\n continue;\n }\n\n if (message.Role == ChatRole.User || message.Role == ChatRole.Assistant)\n {\n Role role = message.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n foreach (var content in message.Contents)\n {\n switch (content)\n {\n case TextContent textContent:\n samplingMessages.Add(new()\n {\n Role = role,\n Content = new TextContentBlock { Text = textContent.Text },\n });\n break;\n\n case DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") || dataContent.HasTopLevelMediaType(\"audio\"):\n samplingMessages.Add(new()\n {\n Role = role,\n Content = dataContent.HasTopLevelMediaType(\"image\") ?\n new ImageContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n } :\n new AudioContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n },\n });\n break;\n }\n }\n }\n }\n\n ModelPreferences? modelPreferences = null;\n if (options?.ModelId is { } modelId)\n {\n modelPreferences = new() { Hints = [new() { Name = modelId }] };\n }\n\n var result = await server.SampleAsync(new()\n {\n Messages = samplingMessages,\n MaxTokens = options?.MaxOutputTokens,\n StopSequences = options?.StopSequences?.ToArray(),\n SystemPrompt = systemPrompt?.ToString(),\n Temperature = options?.Temperature,\n ModelPreferences = modelPreferences,\n }, cancellationToken).ConfigureAwait(false);\n\n AIContent? responseContent = result.Content.ToAIContent();\n\n return new(new ChatMessage(result.Role is Role.User ? ChatRole.User : ChatRole.Assistant, responseContent is not null ? [responseContent] : []))\n {\n ModelId = result.Model,\n FinishReason = result.StopReason switch\n {\n \"maxTokens\" => ChatFinishReason.Length,\n \"endTurn\" or \"stopSequence\" or _ => ChatFinishReason.Stop,\n }\n };\n }\n\n /// \n /// Creates an wrapper that can be used to send sampling requests to the client.\n /// \n /// The server to be wrapped as an .\n /// The that can be used to issue sampling requests to the client.\n /// is .\n /// The client does not support sampling.\n public static IChatClient AsSamplingChatClient(this IMcpServer server)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return new SamplingChatClient(server);\n }\n\n /// Gets an on which logged messages will be sent as notifications to the client.\n /// The server to wrap as an .\n /// An that can be used to log to the client..\n public static ILoggerProvider AsClientLoggerProvider(this IMcpServer server)\n {\n Throw.IfNull(server);\n\n return new ClientLoggerProvider(server);\n }\n\n /// \n /// Requests the client to list the roots it exposes.\n /// \n /// The server initiating the request.\n /// The parameters for the list roots request.\n /// The to monitor for cancellation requests.\n /// A task containing the list of roots exposed by the client.\n /// is .\n /// The client does not support roots.\n /// \n /// This method requires the client to support the roots capability.\n /// Root resources allow clients to expose a hierarchical structure of resources that can be\n /// navigated and accessed by the server. These resources might include file systems, databases,\n /// or other structured data sources that the client makes available through the protocol.\n /// \n public static ValueTask RequestRootsAsync(\n this IMcpServer server, ListRootsRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfRootsUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.RootsList,\n request,\n McpJsonUtilities.JsonContext.Default.ListRootsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListRootsResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests additional information from the user via the client, allowing the server to elicit structured data.\n /// \n /// The server initiating the request.\n /// The parameters for the elicitation request.\n /// The to monitor for cancellation requests.\n /// A task containing the elicitation result.\n /// is .\n /// The client does not support elicitation.\n /// \n /// This method requires the client to support the elicitation capability.\n /// \n public static ValueTask ElicitAsync(\n this IMcpServer server, ElicitRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfElicitationUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.ElicitationCreate,\n request,\n McpJsonUtilities.JsonContext.Default.ElicitRequestParams,\n McpJsonUtilities.JsonContext.Default.ElicitResult,\n cancellationToken: cancellationToken);\n }\n\n private static void ThrowIfSamplingUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Sampling is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Sampling is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support sampling.\");\n }\n }\n\n private static void ThrowIfRootsUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Roots is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Roots are not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support roots.\");\n }\n }\n\n private static void ThrowIfElicitationUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Elicitation is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Elicitation is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support elicitation requests.\");\n }\n }\n\n /// Provides an implementation that's implemented via client sampling.\n private sealed class SamplingChatClient(IMcpServer server) : IChatClient\n {\n /// \n public Task GetResponseAsync(IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) =>\n server.SampleAsync(messages, options, cancellationToken);\n\n /// \n async IAsyncEnumerable IChatClient.GetStreamingResponseAsync(\n IEnumerable messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n var response = await GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);\n foreach (var update in response.ToChatResponseUpdates())\n {\n yield return update;\n }\n }\n\n /// \n object? IChatClient.GetService(Type serviceType, object? serviceKey)\n {\n Throw.IfNull(serviceType);\n\n return\n serviceKey is not null ? null :\n serviceType.IsInstanceOfType(this) ? this :\n serviceType.IsInstanceOfType(server) ? server :\n null;\n }\n\n /// \n void IDisposable.Dispose() { } // nop\n }\n\n /// \n /// Provides an implementation for creating loggers\n /// that send logging message notifications to the client for logged messages.\n /// \n private sealed class ClientLoggerProvider(IMcpServer server) : ILoggerProvider\n {\n /// \n public ILogger CreateLogger(string categoryName)\n {\n Throw.IfNull(categoryName);\n\n return new ClientLogger(server, categoryName);\n }\n\n /// \n void IDisposable.Dispose() { }\n\n private sealed class ClientLogger(IMcpServer server, string categoryName) : ILogger\n {\n /// \n public IDisposable? BeginScope(TState state) where TState : notnull =>\n null;\n\n /// \n public bool IsEnabled(LogLevel logLevel) =>\n server?.LoggingLevel is { } loggingLevel &&\n McpServer.ToLoggingLevel(logLevel) >= loggingLevel;\n\n /// \n public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)\n {\n if (!IsEnabled(logLevel))\n {\n return;\n }\n\n Throw.IfNull(formatter);\n\n Log(logLevel, formatter(state, exception));\n\n void Log(LogLevel logLevel, string message)\n {\n _ = server.SendNotificationAsync(NotificationMethods.LoggingMessageNotification, new LoggingMessageNotificationParams\n {\n Level = McpServer.ToLoggingLevel(logLevel),\n Data = JsonSerializer.SerializeToElement(message, McpJsonUtilities.JsonContext.Default.String),\n Logger = categoryName,\n });\n }\n }\n }\n }\n}\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/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/Server/AIFunctionMcpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed partial class AIFunctionMcpServerTool : McpServerTool\n{\n private readonly ILogger _logger;\n private readonly bool _structuredOutputRequiresWrapping;\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n \n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n object? target,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerToolCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options)\n {\n Throw.IfNull(function);\n\n Tool tool = new()\n {\n Name = options?.Name ?? function.Name,\n Description = options?.Description ?? function.Description,\n InputSchema = function.JsonSchema,\n OutputSchema = CreateOutputSchema(function, options, out bool structuredOutputRequiresWrapping),\n };\n\n if (options is not null)\n {\n if (options.Title is not null ||\n options.Idempotent is not null ||\n options.Destructive is not null ||\n options.OpenWorld is not null ||\n options.ReadOnly is not null)\n {\n tool.Title = options.Title;\n\n tool.Annotations = new()\n {\n Title = options.Title,\n IdempotentHint = options.Idempotent,\n DestructiveHint = options.Destructive,\n OpenWorldHint = options.OpenWorld,\n ReadOnlyHint = options.ReadOnly,\n };\n }\n }\n\n return new AIFunctionMcpServerTool(function, tool, options?.Services, structuredOutputRequiresWrapping);\n }\n\n private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpServerToolCreateOptions? options)\n {\n McpServerToolCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } toolAttr)\n {\n newOptions.Name ??= toolAttr.Name;\n newOptions.Title ??= toolAttr.Title;\n\n if (toolAttr._destructive is bool destructive)\n {\n newOptions.Destructive ??= destructive;\n }\n\n if (toolAttr._idempotent is bool idempotent)\n {\n newOptions.Idempotent ??= idempotent;\n }\n\n if (toolAttr._openWorld is bool openWorld)\n {\n newOptions.OpenWorld ??= openWorld;\n }\n\n if (toolAttr._readOnly is bool readOnly)\n {\n newOptions.ReadOnly ??= readOnly;\n }\n\n newOptions.UseStructuredContent = toolAttr.UseStructuredContent;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this tool.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerTool(AIFunction function, Tool tool, IServiceProvider? serviceProvider, bool structuredOutputRequiresWrapping)\n {\n AIFunction = function;\n ProtocolTool = tool;\n _logger = serviceProvider?.GetService()?.CreateLogger() ?? (ILogger)NullLogger.Instance;\n _structuredOutputRequiresWrapping = structuredOutputRequiresWrapping;\n }\n\n /// \n public override Tool ProtocolTool { get; }\n\n /// \n public override async ValueTask InvokeAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result;\n try\n {\n result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e) when (e is not OperationCanceledException)\n {\n ToolCallError(request.Params?.Name ?? string.Empty, e);\n\n string errorMessage = e is McpException ?\n $\"An error occurred invoking '{request.Params?.Name}': {e.Message}\" :\n $\"An error occurred invoking '{request.Params?.Name}'.\";\n\n return new()\n {\n IsError = true,\n Content = [new TextContentBlock { Text = errorMessage }],\n };\n }\n\n JsonNode? structuredContent = CreateStructuredResponse(result);\n return result switch\n {\n AIContent aiContent => new()\n {\n Content = [aiContent.ToContent()],\n StructuredContent = structuredContent,\n IsError = aiContent is ErrorContent\n },\n\n null => new()\n {\n Content = [],\n StructuredContent = structuredContent,\n },\n \n string text => new()\n {\n Content = [new TextContentBlock { Text = text }],\n StructuredContent = structuredContent,\n },\n \n ContentBlock content => new()\n {\n Content = [content],\n StructuredContent = structuredContent,\n },\n \n IEnumerable texts => new()\n {\n Content = [.. texts.Select(x => new TextContentBlock { Text = x ?? string.Empty })],\n StructuredContent = structuredContent,\n },\n \n IEnumerable contentItems => ConvertAIContentEnumerableToCallToolResult(contentItems, structuredContent),\n \n IEnumerable contents => new()\n {\n Content = [.. contents],\n StructuredContent = structuredContent,\n },\n \n CallToolResult callToolResponse => callToolResponse,\n\n _ => new()\n {\n Content = [new TextContentBlock { Text = JsonSerializer.Serialize(result, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))) }],\n StructuredContent = structuredContent,\n },\n };\n }\n\n /// Creates a name to use based on the supplied method and naming policy.\n internal static string DeriveName(MethodInfo method, JsonNamingPolicy? policy = null)\n {\n string name = method.Name;\n\n // Remove any \"Async\" suffix if the method is an async method and if the method name isn't just \"Async\".\n const string AsyncSuffix = \"Async\";\n if (IsAsyncMethod(method) &&\n name.EndsWith(AsyncSuffix, StringComparison.Ordinal) &&\n name.Length > AsyncSuffix.Length)\n {\n name = name.Substring(0, name.Length - AsyncSuffix.Length);\n }\n\n // Replace anything other than ASCII letters or digits with underscores, trim off any leading or trailing underscores.\n name = NonAsciiLetterDigitsRegex().Replace(name, \"_\").Trim('_');\n\n // If after all our transformations the name is empty, just use the original method name.\n if (name.Length == 0)\n {\n name = method.Name;\n }\n\n // Case the name based on the provided naming policy.\n return (policy ?? JsonNamingPolicy.SnakeCaseLower).ConvertName(name) ?? name;\n\n static bool IsAsyncMethod(MethodInfo method)\n {\n Type t = method.ReturnType;\n\n if (t == typeof(Task) || t == typeof(ValueTask))\n {\n return true;\n }\n\n if (t.IsGenericType)\n {\n t = t.GetGenericTypeDefinition();\n if (t == typeof(Task<>) || t == typeof(ValueTask<>) || t == typeof(IAsyncEnumerable<>))\n {\n return true;\n }\n }\n\n return false;\n }\n }\n\n /// Regex that flags runs of characters other than ASCII digits or letters.\n#if NET\n [GeneratedRegex(\"[^0-9A-Za-z]+\")]\n private static partial Regex NonAsciiLetterDigitsRegex();\n#else\n private static Regex NonAsciiLetterDigitsRegex() => _nonAsciiLetterDigits;\n private static readonly Regex _nonAsciiLetterDigits = new(\"[^0-9A-Za-z]+\", RegexOptions.Compiled);\n#endif\n\n private static JsonElement? CreateOutputSchema(AIFunction function, McpServerToolCreateOptions? toolCreateOptions, out bool structuredOutputRequiresWrapping)\n {\n structuredOutputRequiresWrapping = false;\n\n if (toolCreateOptions?.UseStructuredContent is not true)\n {\n return null;\n }\n\n if (function.ReturnJsonSchema is not JsonElement outputSchema)\n {\n return null;\n }\n\n if (outputSchema.ValueKind is not JsonValueKind.Object ||\n !outputSchema.TryGetProperty(\"type\", out JsonElement typeProperty) ||\n typeProperty.ValueKind is not JsonValueKind.String ||\n typeProperty.GetString() is not \"object\")\n {\n // If the output schema is not an object, need to modify to be a valid MCP output schema.\n JsonNode? schemaNode = JsonSerializer.SerializeToNode(outputSchema, McpJsonUtilities.JsonContext.Default.JsonElement);\n\n if (schemaNode is JsonObject objSchema &&\n objSchema.TryGetPropertyValue(\"type\", out JsonNode? typeNode) &&\n typeNode is JsonArray { Count: 2 } typeArray && typeArray.Any(type => (string?)type is \"object\") && typeArray.Any(type => (string?)type is \"null\"))\n {\n // For schemas that are of type [\"object\", \"null\"], replace with just \"object\" to be conformant.\n objSchema[\"type\"] = \"object\";\n }\n else\n {\n // For anything else, wrap the schema in an envelope with a \"result\" property.\n schemaNode = new JsonObject\n {\n [\"type\"] = \"object\",\n [\"properties\"] = new JsonObject\n {\n [\"result\"] = schemaNode\n },\n [\"required\"] = new JsonArray { (JsonNode)\"result\" }\n };\n\n structuredOutputRequiresWrapping = true;\n }\n\n outputSchema = JsonSerializer.Deserialize(schemaNode, McpJsonUtilities.JsonContext.Default.JsonElement);\n }\n\n return outputSchema;\n }\n\n private JsonNode? CreateStructuredResponse(object? aiFunctionResult)\n {\n if (ProtocolTool.OutputSchema is null)\n {\n // Only provide structured responses if the tool has an output schema defined.\n return null;\n }\n\n JsonNode? nodeResult = aiFunctionResult switch\n {\n JsonNode node => node,\n JsonElement jsonElement => JsonSerializer.SerializeToNode(jsonElement, McpJsonUtilities.JsonContext.Default.JsonElement),\n _ => JsonSerializer.SerializeToNode(aiFunctionResult, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))),\n };\n\n if (_structuredOutputRequiresWrapping)\n {\n return new JsonObject\n {\n [\"result\"] = nodeResult\n };\n }\n\n return nodeResult;\n }\n\n private static CallToolResult ConvertAIContentEnumerableToCallToolResult(IEnumerable contentItems, JsonNode? structuredContent)\n {\n List contentList = [];\n bool allErrorContent = true;\n bool hasAny = false;\n\n foreach (var item in contentItems)\n {\n contentList.Add(item.ToContent());\n hasAny = true;\n\n if (allErrorContent && item is not ErrorContent)\n {\n allErrorContent = false;\n }\n }\n\n return new()\n {\n Content = contentList,\n StructuredContent = structuredContent,\n IsError = allErrorContent && hasAny\n };\n }\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"\\\"{ToolName}\\\" threw an unhandled exception.\")]\n private partial void ToolCallError(string toolName, Exception exception);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerResource : McpServerResource\n{\n private readonly Regex? _uriParser;\n private readonly string[] _templateVariableNames = [];\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n object? target,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerResourceCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n // These parameters are the ones and only ones to include in the schema. The schema\n // won't be consumed by anyone other than this instance, which will use it to determine\n // which properties should show up in the URI template.\n if (pi.Name is not null && GetConverter(pi.ParameterType) is { } converter)\n {\n return new()\n {\n ExcludeFromSchema = false,\n BindParameter = (pi, args) =>\n {\n if (args.TryGetValue(pi.Name!, out var value))\n {\n return\n value is null || pi.ParameterType.IsInstanceOfType(value) ? value :\n value is string stringValue ? converter(stringValue) :\n throw new ArgumentException($\"Parameter '{pi.Name}' is of type '{pi.ParameterType}', but value '{value}' is of type '{value.GetType()}'.\");\n }\n\n return\n pi.HasDefaultValue ? pi.DefaultValue :\n throw new ArgumentException($\"Missing a value for the required parameter '{pi.Name}'.\");\n },\n };\n }\n\n return default;\n },\n };\n\n private static readonly ConcurrentDictionary> s_convertersCache = [];\n\n private static Func? GetConverter(Type type)\n {\n Type key = type;\n\n if (s_convertersCache.TryGetValue(key, out var converter))\n {\n return converter;\n }\n\n if (Nullable.GetUnderlyingType(type) is { } underlyingType)\n {\n // We will have already screened out null values by the time the converter is used,\n // so we can parse just the underlying type.\n type = underlyingType;\n }\n\n if (type == typeof(string) || type == typeof(object)) converter = static s => s;\n if (type == typeof(bool)) converter = static s => bool.Parse(s);\n if (type == typeof(char)) converter = static s => char.Parse(s);\n if (type == typeof(byte)) converter = static s => byte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(sbyte)) converter = static s => sbyte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ushort)) converter = static s => ushort.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(short)) converter = static s => short.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(uint)) converter = static s => uint.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(int)) converter = static s => int.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ulong)) converter = static s => ulong.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(long)) converter = static s => long.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(float)) converter = static s => float.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(double)) converter = static s => double.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(decimal)) converter = static s => decimal.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeSpan)) converter = static s => TimeSpan.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTime)) converter = static s => DateTime.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTimeOffset)) converter = static s => DateTimeOffset.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Uri)) converter = static s => new Uri(s, UriKind.RelativeOrAbsolute);\n if (type == typeof(Guid)) converter = static s => Guid.Parse(s);\n if (type == typeof(Version)) converter = static s => Version.Parse(s);\n#if NET\n if (type == typeof(Half)) converter = static s => Half.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Int128)) converter = static s => Int128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UInt128)) converter = static s => UInt128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(IntPtr)) converter = static s => IntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UIntPtr)) converter = static s => UIntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateOnly)) converter = static s => DateOnly.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeOnly)) converter = static s => TimeOnly.Parse(s, CultureInfo.InvariantCulture);\n#endif\n if (type.IsEnum) converter = s => Enum.Parse(type, s);\n\n if (type.GetCustomAttribute() is TypeConverterAttribute tca &&\n Type.GetType(tca.ConverterTypeName, throwOnError: false) is { } converterType &&\n Activator.CreateInstance(converterType) is TypeConverter typeConverter &&\n typeConverter.CanConvertFrom(typeof(string)))\n {\n converter = s => typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, s);\n }\n\n if (converter is not null)\n {\n s_convertersCache.TryAdd(key, converter);\n }\n\n return converter;\n }\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerResource Create(AIFunction function, McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(function);\n\n string name = options?.Name ?? function.Name;\n\n ResourceTemplate resource = new()\n {\n UriTemplate = options?.UriTemplate ?? DeriveUriTemplate(name, function),\n Name = name,\n Title = options?.Title,\n Description = options?.Description,\n MimeType = options?.MimeType ?? \"application/octet-stream\",\n };\n\n return new AIFunctionMcpServerResource(function, resource);\n }\n\n private static McpServerResourceCreateOptions DeriveOptions(MemberInfo member, McpServerResourceCreateOptions? options)\n {\n McpServerResourceCreateOptions newOptions = options?.Clone() ?? new();\n\n if (member.GetCustomAttribute() is { } resourceAttr)\n {\n newOptions.UriTemplate ??= resourceAttr.UriTemplate;\n newOptions.Name ??= resourceAttr.Name;\n newOptions.Title ??= resourceAttr.Title;\n newOptions.MimeType ??= resourceAttr.MimeType;\n }\n\n if (member.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Derives a name to be used as a resource name.\n private static string DeriveUriTemplate(string name, AIFunction function)\n {\n StringBuilder template = new();\n\n template.Append(\"resource://mcp/\").Append(Uri.EscapeDataString(name));\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n string separator = \"{?\";\n foreach (var prop in properties.EnumerateObject())\n {\n template.Append(separator).Append(prop.Name);\n separator = \",\";\n }\n\n if (separator == \",\")\n {\n template.Append('}');\n }\n }\n\n return template.ToString();\n }\n\n /// Gets the wrapped by this resource.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerResource(AIFunction function, ResourceTemplate resourceTemplate)\n {\n AIFunction = function;\n ProtocolResourceTemplate = resourceTemplate;\n ProtocolResource = resourceTemplate.AsResource();\n\n if (ProtocolResource is null)\n {\n _uriParser = UriTemplate.CreateParser(resourceTemplate.UriTemplate);\n _templateVariableNames = _uriParser.GetGroupNames().Where(n => n != \"0\").ToArray();\n }\n }\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// \n public override Resource? ProtocolResource { get; }\n\n /// \n public override async ValueTask ReadAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n Throw.IfNull(request.Params);\n Throw.IfNull(request.Params.Uri);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check to see if this URI template matches the request URI. If it doesn't, return null.\n // For templates, use the Regex to parse. For static resources, we can just compare the URIs.\n Match? match = null;\n if (_uriParser is not null)\n {\n match = _uriParser.Match(request.Params.Uri);\n if (!match.Success)\n {\n return null;\n }\n }\n else if (!UriTemplate.UriTemplateComparer.Instance.Equals(request.Params.Uri, ProtocolResource!.Uri))\n {\n return null;\n }\n\n // Build up the arguments for the AIFunction call, including all of the name/value pairs from the URI.\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n // For templates, populate the arguments from the URI template.\n if (match is not null)\n {\n foreach (string varName in _templateVariableNames)\n {\n if (match.Groups[varName] is { Success: true } value)\n {\n arguments[varName] = Uri.UnescapeDataString(value.Value);\n }\n }\n }\n\n // Invoke the function.\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n // And process the result.\n return result switch\n {\n ReadResourceResult readResourceResult => readResourceResult,\n\n ResourceContents content => new()\n {\n Contents = [content],\n },\n\n TextContent tc => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = tc.Text }],\n },\n\n DataContent dc => new()\n {\n Contents = [new BlobResourceContents { Uri = request.Params!.Uri, MimeType = dc.MediaType, Blob = dc.Base64Data.ToString() }],\n },\n\n string text => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = text }],\n },\n\n IEnumerable contents => new()\n {\n Contents = contents.ToList(),\n },\n\n IEnumerable aiContents => new()\n {\n Contents = aiContents.Select(\n ac => ac switch\n {\n TextContent tc => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = tc.Text\n },\n\n DataContent dc => new BlobResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = dc.MediaType,\n Blob = dc.Base64Data.ToString()\n },\n\n _ => throw new InvalidOperationException($\"Unsupported AIContent type '{ac.GetType()}' returned from resource function.\"),\n }).ToList(),\n },\n\n IEnumerable strings => new()\n {\n Contents = strings.Select(text => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = text\n }).ToList(),\n },\n\n null => throw new InvalidOperationException(\"Null result returned from resource function.\"),\n\n _ => throw new InvalidOperationException($\"Unsupported result type '{result.GetType()}' returned from resource function.\"),\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceContents.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class representing contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// serves as the base class for different types of resources that can be \n/// exchanged through the Model Context Protocol. Resources are identified by URIs and can contain\n/// different types of data.\n/// \n/// \n/// This class is abstract and has two concrete implementations:\n/// \n/// - For text-based resources\n/// - For binary data resources\n/// \n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class ResourceContents\n{\n /// Prevent external derivations.\n private protected ResourceContents()\n {\n }\n\n /// \n /// Gets or sets the URI of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n public string Uri { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the MIME type of the resource content.\n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ResourceContents? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? uri = null;\n string? mimeType = null;\n string? blob = null;\n string? text = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"blob\":\n blob = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n if (blob is not null)\n {\n return new BlobResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Blob = blob,\n Meta = meta,\n };\n }\n\n if (text is not null)\n {\n return new TextResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Text = text,\n Meta = meta,\n };\n }\n\n return null;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ResourceContents value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n writer.WriteString(\"uri\", value.Uri);\n writer.WriteString(\"mimeType\", value.MimeType);\n \n Debug.Assert(value is BlobResourceContents or TextResourceContents);\n if (value is BlobResourceContents blobResource)\n {\n writer.WriteString(\"blob\", blobResource.Blob);\n }\n else if (value is TextResourceContents textResource)\n {\n writer.WriteString(\"text\", textResource.Text);\n }\n\n if (value.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, value.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerPrompt : McpServerPrompt\n{\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n object? target,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerPromptCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(function);\n\n List args = [];\n HashSet? requiredProps = function.JsonSchema.TryGetProperty(\"required\", out JsonElement required)\n ? new(required.EnumerateArray().Select(p => p.GetString()!), StringComparer.Ordinal)\n : null;\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n foreach (var param in properties.EnumerateObject())\n {\n args.Add(new()\n {\n Name = param.Name,\n Description = param.Value.TryGetProperty(\"description\", out JsonElement description) ? description.GetString() : null,\n Required = requiredProps?.Contains(param.Name) ?? false,\n });\n }\n }\n\n Prompt prompt = new()\n {\n Name = options?.Name ?? function.Name,\n Title = options?.Title,\n Description = options?.Description ?? function.Description,\n Arguments = args,\n };\n\n return new AIFunctionMcpServerPrompt(function, prompt);\n }\n\n private static McpServerPromptCreateOptions DeriveOptions(MethodInfo method, McpServerPromptCreateOptions? options)\n {\n McpServerPromptCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } promptAttr)\n {\n newOptions.Name ??= promptAttr.Name;\n newOptions.Title ??= promptAttr.Title;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this prompt.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerPrompt(AIFunction function, Prompt prompt)\n {\n AIFunction = function;\n ProtocolPrompt = prompt;\n }\n\n /// \n public override Prompt ProtocolPrompt { get; }\n\n /// \n public override async ValueTask GetAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n return result switch\n {\n GetPromptResult getPromptResult => getPromptResult,\n\n string text => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [new() { Role = Role.User, Content = new TextContentBlock { Text = text } }],\n },\n\n PromptMessage promptMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [promptMessage],\n },\n\n IEnumerable promptMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. promptMessages],\n },\n\n ChatMessage chatMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessage.ToPromptMessages()],\n },\n\n IEnumerable chatMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessages.SelectMany(chatMessage => chatMessage.ToPromptMessages())],\n },\n\n null => throw new InvalidOperationException(\"Null result returned from prompt function.\"),\n\n _ => throw new InvalidOperationException($\"Unknown result type '{result.GetType()}' returned from prompt function.\"),\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class contains extension methods that simplify common operations with an MCP client,\n/// such as pinging a server, listing and working with tools, prompts, and resources, and\n/// managing subscriptions to resources.\n/// \n/// \npublic static class McpClientExtensions\n{\n /// \n /// Sends a ping request to verify server connectivity.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A task that completes when the ping is successful.\n /// \n /// \n /// This method is used to check if the MCP server is online and responding to requests.\n /// It can be useful for health checking, ensuring the connection is established, or verifying \n /// that the client has proper authorization to communicate with the server.\n /// \n /// \n /// The ping operation is lightweight and does not require any parameters. A successful completion\n /// of the task indicates that the server is operational and accessible.\n /// \n /// \n /// is .\n /// Thrown when the server cannot be reached or returns an error response.\n public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.Ping,\n parameters: null,\n McpJsonUtilities.JsonContext.Default.Object!,\n McpJsonUtilities.JsonContext.Default.Object,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Retrieves a list of available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available tools as instances.\n /// \n /// \n /// This method fetches all available tools from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of tools and that responds with paginated responses, consider using \n /// instead, as it streams tools as they arrive rather than loading them all at once.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// \n /// \n /// // Get all tools available on the server\n /// var tools = await mcpClient.ListToolsAsync();\n /// \n /// // Use tools with an AI client\n /// ChatOptions chatOptions = new()\n /// {\n /// Tools = [.. tools]\n /// };\n /// \n /// await foreach (var update in chatClient.GetStreamingResponseAsync(userMessage, chatOptions))\n /// {\n /// Console.Write(update);\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n List? tools = null;\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n tools ??= new List(toolResults.Tools.Count);\n foreach (var tool in toolResults.Tools)\n {\n tools.Add(new McpClientTool(client, tool, serializerOptions));\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n\n return tools;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available tools as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve tools from the server, which allows processing tools\n /// as they arrive rather than waiting for all tools to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with tools split across multiple responses.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available tools.\n /// \n /// \n /// \n /// \n /// // Enumerate all tools available on the server\n /// await foreach (var tool in client.EnumerateToolsAsync())\n /// {\n /// Console.WriteLine($\"Tool: {tool.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var tool in toolResults.Tools)\n {\n yield return new McpClientTool(client, tool, serializerOptions);\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available prompts as instances.\n /// \n /// \n /// This method fetches all available prompts from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of prompts and that responds with paginated responses, consider using \n /// instead, as it streams prompts as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListPromptsAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? prompts = null;\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n prompts ??= new List(promptResults.Prompts.Count);\n foreach (var prompt in promptResults.Prompts)\n {\n prompts.Add(new McpClientPrompt(client, prompt));\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n\n return prompts;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available prompts as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve prompts from the server, which allows processing prompts\n /// as they arrive rather than waiting for all prompts to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with prompts split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available prompts.\n /// \n /// \n /// \n /// \n /// // Enumerate all prompts available on the server\n /// await foreach (var prompt in client.EnumeratePromptsAsync())\n /// {\n /// Console.WriteLine($\"Prompt: {prompt.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumeratePromptsAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var prompt in promptResults.Prompts)\n {\n yield return new(client, prompt);\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a specific prompt from the MCP server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the prompt to retrieve.\n /// Optional arguments for the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to create the specified prompt with the provided arguments.\n /// The server will process the arguments and return a prompt containing messages or other content.\n /// \n /// \n /// Arguments are serialized into JSON and passed to the server, where they may be used to customize the \n /// prompt's behavior or content. Each prompt may have different argument requirements.\n /// \n /// \n /// The returned contains a collection of objects,\n /// which can be converted to objects using the method.\n /// \n /// \n /// Thrown when the prompt does not exist, when required arguments are missing, or when the server encounters an error processing the prompt.\n /// is .\n public static ValueTask GetPromptAsync(\n this IMcpClient client,\n string name,\n IReadOnlyDictionary? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(name);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n return client.SendRequestAsync(\n RequestMethods.PromptsGet,\n new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },\n McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,\n McpJsonUtilities.JsonContext.Default.GetPromptResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Retrieves a list of available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resource templates as instances.\n /// \n /// \n /// This method fetches all available resource templates from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resource templates and that responds with paginated responses, consider using \n /// instead, as it streams templates as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListResourceTemplatesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resourceTemplates = null;\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resourceTemplates ??= new List(templateResults.ResourceTemplates.Count);\n foreach (var template in templateResults.ResourceTemplates)\n {\n resourceTemplates.Add(new McpClientResourceTemplate(client, template));\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n\n return resourceTemplates;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resource templates as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resource templates from the server, which allows processing templates\n /// as they arrive rather than waiting for all templates to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with templates split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resource templates.\n /// \n /// \n /// \n /// \n /// // Enumerate all resource templates available on the server\n /// await foreach (var template in client.EnumerateResourceTemplatesAsync())\n /// {\n /// Console.WriteLine($\"Template: {template.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourceTemplatesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var templateResult in templateResults.ResourceTemplates)\n {\n yield return new McpClientResourceTemplate(client, templateResult);\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resources as instances.\n /// \n /// \n /// This method fetches all available resources from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resources and that responds with paginated responses, consider using \n /// instead, as it streams resources as they arrive rather than loading them all at once.\n /// \n /// \n /// \n /// \n /// // Get all resources available on the server\n /// var resources = await client.ListResourcesAsync();\n /// \n /// // Display information about each resource\n /// foreach (var resource in resources)\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListResourcesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resources = null;\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resources ??= new List(resourceResults.Resources.Count);\n foreach (var resource in resourceResults.Resources)\n {\n resources.Add(new McpClientResource(client, resource));\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n\n return resources;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resources as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resources from the server, which allows processing resources\n /// as they arrive rather than waiting for all resources to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with resources split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resources.\n /// \n /// \n /// \n /// \n /// // Enumerate all resources available on the server\n /// await foreach (var resource in client.EnumerateResourcesAsync())\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourcesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var resource in resourceResults.Resources)\n {\n yield return new McpClientResource(client, resource);\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return ReadResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri template of the resource.\n /// Arguments to use to format .\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uriTemplate, IReadOnlyDictionary arguments, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uriTemplate);\n Throw.IfNull(arguments);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = UriTemplate.FormatUri(uriTemplate, arguments) },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests completion suggestions for a prompt argument or resource reference.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The reference object specifying the type and optional URI or name.\n /// The name of the argument for which completions are requested.\n /// The current value of the argument, used to filter relevant completions.\n /// The to monitor for cancellation requests. The default is .\n /// A containing completion suggestions.\n /// \n /// \n /// This method allows clients to request auto-completion suggestions for arguments in a prompt template\n /// or for resource references.\n /// \n /// \n /// When working with prompt references, the server will return suggestions for the specified argument\n /// that match or begin with the current argument value. This is useful for implementing intelligent\n /// auto-completion in user interfaces.\n /// \n /// \n /// When working with resource references, the server will return suggestions relevant to the specified \n /// resource URI.\n /// \n /// \n /// is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n /// The server returned an error response.\n public static ValueTask CompleteAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(reference);\n Throw.IfNullOrWhiteSpace(argumentName);\n\n return client.SendRequestAsync(\n RequestMethods.CompletionComplete,\n new()\n {\n Ref = reference,\n Argument = new Argument { Name = argumentName, Value = argumentValue }\n },\n McpJsonUtilities.JsonContext.Default.CompleteRequestParams,\n McpJsonUtilities.JsonContext.Default.CompleteResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesSubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n public static Task SubscribeToResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return SubscribeToResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesUnsubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return UnsubscribeFromResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Invokes a tool on the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the tool to call on the server..\n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// is .\n /// is .\n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// // Call a simple echo tool with a string argument\n /// var result = await client.CallToolAsync(\n /// \"echo\",\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public static ValueTask CallToolAsync(\n this IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(toolName);\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n if (progress is not null)\n {\n return SendRequestWithProgressAsync(client, toolName, arguments, progress, serializerOptions, cancellationToken);\n }\n\n return client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken);\n\n static async ValueTask SendRequestWithProgressAsync(\n IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments,\n IProgress progress,\n JsonSerializerOptions serializerOptions,\n CancellationToken cancellationToken)\n {\n ProgressToken progressToken = new(Guid.NewGuid().ToString(\"N\"));\n\n await using var _ = client.RegisterNotificationHandler(NotificationMethods.ProgressNotification,\n (notification, cancellationToken) =>\n {\n if (JsonSerializer.Deserialize(notification.Params, McpJsonUtilities.JsonContext.Default.ProgressNotificationParams) is { } pn &&\n pn.ProgressToken == progressToken)\n {\n progress.Report(pn.Progress);\n }\n\n return default;\n }).ConfigureAwait(false);\n\n return await client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n ProgressToken = progressToken,\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n }\n\n /// \n /// Converts the contents of a into a pair of\n /// and instances to use\n /// as inputs into a operation.\n /// \n /// \n /// The created pair of messages and options.\n /// is .\n internal static (IList Messages, ChatOptions? Options) ToChatClientArguments(\n this CreateMessageRequestParams requestParams)\n {\n Throw.IfNull(requestParams);\n\n ChatOptions? options = null;\n\n if (requestParams.MaxTokens is int maxTokens)\n {\n (options ??= new()).MaxOutputTokens = maxTokens;\n }\n\n if (requestParams.Temperature is float temperature)\n {\n (options ??= new()).Temperature = temperature;\n }\n\n if (requestParams.StopSequences is { } stopSequences)\n {\n (options ??= new()).StopSequences = stopSequences.ToArray();\n }\n\n List messages =\n (from sm in requestParams.Messages\n let aiContent = sm.Content.ToAIContent()\n where aiContent is not null\n select new ChatMessage(sm.Role == Role.Assistant ? ChatRole.Assistant : ChatRole.User, [aiContent]))\n .ToList();\n\n return (messages, options);\n }\n\n /// Converts the contents of a into a .\n /// The whose contents should be extracted.\n /// The created .\n /// is .\n internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chatResponse)\n {\n Throw.IfNull(chatResponse);\n\n // The ChatResponse can include multiple messages, of varying modalities, but CreateMessageResult supports\n // only either a single blob of text or a single image. Heuristically, we'll use an image if there is one\n // in any of the response messages, or we'll use all the text from them concatenated, otherwise.\n\n ChatMessage? lastMessage = chatResponse.Messages.LastOrDefault();\n\n ContentBlock? content = null;\n if (lastMessage is not null)\n {\n foreach (var lmc in lastMessage.Contents)\n {\n if (lmc is DataContent dc && (dc.HasTopLevelMediaType(\"image\") || dc.HasTopLevelMediaType(\"audio\")))\n {\n content = dc.ToContent();\n }\n }\n }\n\n return new()\n {\n Content = content ?? new TextContentBlock { Text = lastMessage?.Text ?? string.Empty },\n Model = chatResponse.ModelId ?? \"unknown\",\n Role = lastMessage?.Role == ChatRole.User ? Role.User : Role.Assistant,\n StopReason = chatResponse.FinishReason == ChatFinishReason.Length ? \"maxTokens\" : \"endTurn\",\n };\n }\n\n /// \n /// Creates a sampling handler for use with that will\n /// satisfy sampling requests using the specified .\n /// \n /// The with which to satisfy sampling requests.\n /// The created handler delegate that can be assigned to .\n /// \n /// \n /// This method creates a function that converts MCP message requests into chat client calls, enabling\n /// an MCP client to generate text or other content using an actual AI model via the provided chat client.\n /// \n /// \n /// The handler can process text messages, image messages, and resource messages as defined in the\n /// Model Context Protocol.\n /// \n /// \n /// is .\n public static Func, CancellationToken, ValueTask> CreateSamplingHandler(\n this IChatClient chatClient)\n {\n Throw.IfNull(chatClient);\n\n return async (requestParams, progress, cancellationToken) =>\n {\n Throw.IfNull(requestParams);\n\n var (messages, options) = requestParams.ToChatClientArguments();\n var progressToken = requestParams.ProgressToken;\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false))\n {\n updates.Add(update);\n\n if (progressToken is not null)\n {\n progress.Report(new()\n {\n Progress = updates.Count,\n });\n }\n }\n\n return updates.ToChatResponse().ToCreateMessageResult();\n };\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// , , and \n /// level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LoggingLevel level, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.LoggingSetLevel,\n new() { Level = level },\n McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// and level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LogLevel level, CancellationToken cancellationToken = default) =>\n SetLoggingLevel(client, McpServer.ToLoggingLevel(level), cancellationToken);\n\n /// Convers a dictionary with values to a dictionary with values.\n private static Dictionary? ToArgumentsDictionary(\n IReadOnlyDictionary? arguments, JsonSerializerOptions options)\n {\n var typeInfo = options.GetTypeInfo();\n\n Dictionary? result = null;\n if (arguments is not null)\n {\n result = new(arguments.Count);\n foreach (var kvp in arguments)\n {\n result.Add(kvp.Key, kvp.Value is JsonElement je ? je : JsonSerializer.SerializeToElement(kvp.Value, typeInfo));\n }\n }\n\n return result;\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/Client/StdioClientSessionTransport.cs", "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 protected override async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)\n {\n // Only clean up once.\n if (Interlocked.Exchange(ref _cleanedUp, 1) != 0)\n {\n return;\n }\n\n // We've not yet forcefully terminated the server. If it's already shut down, something went wrong,\n // so create an exception with details about that.\n error ??= await GetUnexpectedExitExceptionAsync(cancellationToken).ConfigureAwait(false);\n\n // Now terminate the server process.\n try\n {\n StdioClientTransport.DisposeProcess(_process, processRunning: true, _options.ShutdownTimeout, Name);\n }\n catch (Exception ex)\n {\n LogTransportShutdownFailed(Name, ex);\n }\n\n // And handle cleanup in the base type.\n await base.CleanupAsync(error, cancellationToken);\n }\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"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpSession.cs", "using ModelContextProtocol.AspNetCore.Stateless;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Security.Claims;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed class HttpMcpSession(\n string sessionId,\n TTransport transport,\n UserIdClaim? userId,\n TimeProvider timeProvider) : IAsyncDisposable\n where TTransport : ITransport\n{\n private int _referenceCount;\n private int _getRequestStarted;\n private CancellationTokenSource _disposeCts = new();\n\n public string Id { get; } = sessionId;\n public TTransport Transport { get; } = transport;\n public UserIdClaim? UserIdClaim { get; } = userId;\n\n public CancellationToken SessionClosed => _disposeCts.Token;\n\n public bool IsActive => !SessionClosed.IsCancellationRequested && _referenceCount > 0;\n public long LastActivityTicks { get; private set; } = timeProvider.GetTimestamp();\n\n private TimeProvider TimeProvider => timeProvider;\n\n public IMcpServer? Server { get; set; }\n public Task? ServerRunTask { get; set; }\n\n public IDisposable AcquireReference()\n {\n Interlocked.Increment(ref _referenceCount);\n return new UnreferenceDisposable(this);\n }\n\n public bool TryStartGetRequest() => Interlocked.Exchange(ref _getRequestStarted, 1) == 0;\n\n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n\n if (ServerRunTask is not null)\n {\n await ServerRunTask;\n }\n }\n catch (OperationCanceledException)\n {\n }\n finally\n {\n try\n {\n if (Server is not null)\n {\n await Server.DisposeAsync();\n }\n }\n finally\n {\n await Transport.DisposeAsync();\n _disposeCts.Dispose();\n }\n }\n }\n\n public bool HasSameUserId(ClaimsPrincipal user)\n => UserIdClaim == StreamableHttpHandler.GetUserIdClaim(user);\n\n private sealed class UnreferenceDisposable(HttpMcpSession session) : IDisposable\n {\n public void Dispose()\n {\n if (Interlocked.Decrement(ref session._referenceCount) == 0)\n {\n session.LastActivityTicks = session.TimeProvider.GetTimestamp();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseResponseStreamTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as \n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \n/// The response stream to write MCP JSON-RPC messages as SSE events to.\n/// \n/// The relative or absolute URI the client should use to post MCP JSON-RPC messages for this session.\n/// These messages should be passed to .\n/// Defaults to \"/message\".\n/// \n/// The identifier corresponding to the current MCP session.\npublic sealed class SseResponseStreamTransport(Stream sseResponseStream, string? messageEndpoint = \"/message\", string? sessionId = null) : ITransport\n{\n private readonly SseWriter _sseWriter = new(messageEndpoint);\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private bool _isConnected;\n\n /// \n /// Starts the transport and writes the JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task RunAsync(CancellationToken cancellationToken)\n {\n _isConnected = true;\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n /// \n public string? SessionId { get; } = sessionId;\n\n /// \n public async ValueTask DisposeAsync()\n {\n _isConnected = false;\n _incomingChannel.Writer.TryComplete();\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles incoming JSON-RPC messages received on the /message endpoint.\n /// \n /// The JSON-RPC message received from the client.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation to buffer the JSON-RPC message for processing.\n /// Thrown when there is an attempt to process a message before calling .\n /// \n /// \n /// This method is the entry point for processing client-to-server communication in the SSE transport model. \n /// While the SSE protocol itself is unidirectional (server to client), this method allows bidirectional \n /// communication by handling HTTP POST requests sent to the message endpoint.\n /// \n /// \n /// When a client sends a JSON-RPC message to the /message endpoint, the server calls this method to\n /// process the message and make it available to the MCP server via the channel.\n /// \n /// \n /// This method validates that the transport is connected before processing the message, ensuring proper\n /// sequencing of operations in the transport lifecycle.\n /// \n /// \n public async Task OnMessageReceivedAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n Throw.IfNull(message);\n\n if (!_isConnected)\n {\n throw new InvalidOperationException($\"Transport is not connected. Make sure to call {nameof(RunAsync)} first.\");\n }\n\n await _incomingChannel.Writer.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Reference.cs", "using ModelContextProtocol.Client;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a reference to a resource or prompt in the Model Context Protocol.\n/// \n/// \n/// \n/// References are commonly used with to request completion suggestions for arguments,\n/// and with other methods that need to reference resources or prompts.\n/// \n/// \n/// See the schema for details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class Reference\n{\n /// Prevent external derivations.\n private protected Reference() \n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This can be \"ref/resource\" or \"ref/prompt\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override Reference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? name = null;\n string? title = null;\n string? uri = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n default:\n break;\n }\n }\n\n // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n\n switch (type)\n {\n case \"ref/prompt\":\n if (name is null)\n {\n throw new JsonException(\"Prompt references must have a 'name' property.\");\n }\n\n return new PromptReference { Name = name, Title = title };\n\n case \"ref/resource\":\n if (uri is null)\n {\n throw new JsonException(\"Resource references must have a 'uri' property.\");\n }\n\n return new ResourceTemplateReference { Uri = uri };\n\n default:\n throw new JsonException($\"Unknown content type: '{type}'\");\n }\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, Reference value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case PromptReference pr:\n writer.WriteString(\"name\", pr.Name);\n if (pr.Title is not null)\n {\n writer.WriteString(\"title\", pr.Title);\n }\n break;\n\n case ResourceTemplateReference rtr:\n writer.WriteString(\"uri\", rtr.Uri);\n break;\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// \n/// Represents a reference to a prompt, identified by its name.\n/// \npublic sealed class PromptReference : Reference, IBaseMetadata\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public PromptReference() => Type = \"ref/prompt\";\n\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Name}\\\"\";\n}\n\n/// \n/// Represents a reference to a resource or resource template definition.\n/// \npublic sealed class ResourceTemplateReference : Reference\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public ResourceTemplateReference() => Type = \"ref/resource\";\n\n /// \n /// Gets or sets the URI or URI template of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public required string? Uri { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Uri}\\\"\";\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.AspNetCore/IdleTrackingBackgroundService.cs", "using System.Runtime.InteropServices;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed partial class IdleTrackingBackgroundService(\n StreamableHttpHandler handler,\n IOptions options,\n IHostApplicationLifetime appLifetime,\n ILogger logger) : BackgroundService\n{\n // The compiler will complain about the parameter being unused otherwise despite the source generator.\n private readonly ILogger _logger = logger;\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n // Still run loop given infinite IdleTimeout to enforce the MaxIdleSessionCount and assist graceful shutdown.\n if (options.Value.IdleTimeout != Timeout.InfiniteTimeSpan)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.IdleTimeout, TimeSpan.Zero);\n }\n\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.MaxIdleSessionCount, 0);\n\n try\n {\n var timeProvider = options.Value.TimeProvider;\n using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);\n\n var idleTimeoutTicks = options.Value.IdleTimeout.Ticks;\n var maxIdleSessionCount = options.Value.MaxIdleSessionCount;\n\n // Create two lists that will be reused between runs.\n // This assumes that the number of idle sessions is not breached frequently.\n // If the idle sessions often breach the maximum, a priority queue could be considered.\n var idleSessionsTimestamps = new List();\n var idleSessionSessionIds = new List();\n\n while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))\n {\n var idleActivityCutoff = idleTimeoutTicks switch\n {\n < 0 => long.MinValue,\n var ticks => timeProvider.GetTimestamp() - ticks,\n };\n\n foreach (var (_, session) in handler.Sessions)\n {\n if (session.IsActive || session.SessionClosed.IsCancellationRequested)\n {\n // There's a request currently active or the session is already being closed.\n continue;\n }\n\n if (session.LastActivityTicks < idleActivityCutoff)\n {\n RemoveAndCloseSession(session.Id);\n continue;\n }\n\n // Add the timestamp and the session\n idleSessionsTimestamps.Add(session.LastActivityTicks);\n idleSessionSessionIds.Add(session.Id);\n\n // Emit critical log at most once every 5 seconds the idle count it exceeded,\n // since the IdleTimeout will no longer be respected.\n if (idleSessionsTimestamps.Count == maxIdleSessionCount + 1)\n {\n LogMaxSessionIdleCountExceeded(maxIdleSessionCount);\n }\n }\n\n if (idleSessionsTimestamps.Count > maxIdleSessionCount)\n {\n var timestamps = CollectionsMarshal.AsSpan(idleSessionsTimestamps);\n\n // Sort only if the maximum is breached and sort solely by the timestamp. Sort both collections.\n timestamps.Sort(CollectionsMarshal.AsSpan(idleSessionSessionIds));\n\n var sessionsToPrune = CollectionsMarshal.AsSpan(idleSessionSessionIds)[..^maxIdleSessionCount];\n foreach (var id in sessionsToPrune)\n {\n RemoveAndCloseSession(id);\n }\n }\n\n idleSessionsTimestamps.Clear();\n idleSessionSessionIds.Clear();\n }\n }\n catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)\n {\n }\n finally\n {\n try\n {\n List disposeSessionTasks = [];\n\n foreach (var (sessionKey, _) in handler.Sessions)\n {\n if (handler.Sessions.TryRemove(sessionKey, out var session))\n {\n disposeSessionTasks.Add(DisposeSessionAsync(session));\n }\n }\n\n await Task.WhenAll(disposeSessionTasks);\n }\n finally\n {\n if (!stoppingToken.IsCancellationRequested)\n {\n // Something went terribly wrong. A very unexpected exception must be bubbling up, but let's ensure we also stop the application,\n // so that it hopefully gets looked at and restarted. This shouldn't really be reachable.\n appLifetime.StopApplication();\n IdleTrackingBackgroundServiceStoppedUnexpectedly();\n }\n }\n }\n }\n\n private void RemoveAndCloseSession(string sessionId)\n {\n if (!handler.Sessions.TryRemove(sessionId, out var session))\n {\n return;\n }\n\n LogSessionIdle(session.Id);\n // Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown.\n _ = DisposeSessionAsync(session);\n }\n\n private async Task DisposeSessionAsync(HttpMcpSession session)\n {\n try\n {\n await session.DisposeAsync();\n }\n catch (Exception ex)\n {\n LogSessionDisposeError(session.Id, ex);\n }\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Closing idle session {sessionId}.\")]\n private partial void LogSessionIdle(string sessionId);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"Error disposing session {sessionId}.\")]\n private partial void LogSessionDisposeError(string sessionId, Exception ex);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"Exceeded maximum of {maxIdleSessionCount} idle sessions. Now closing sessions active more recently than configured IdleTimeout.\")]\n private partial void LogMaxSessionIdleCountExceeded(int maxIdleSessionCount);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"The IdleTrackingBackgroundService has stopped unexpectedly.\")]\n private partial void IdleTrackingBackgroundServiceStoppedUnexpectedly();\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/Common/Polyfills/System/Threading/CancellationTokenSourceExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class CancellationTokenSourceExtensions\n{\n public static Task CancelAsync(this CancellationTokenSource cancellationTokenSource)\n {\n Throw.IfNull(cancellationTokenSource);\n\n cancellationTokenSource.Cancel();\n return Task.CompletedTask;\n }\n}\n#endif"], ["/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.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/NotificationHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol;\n\n/// Provides thread-safe storage for notification handlers.\ninternal sealed class NotificationHandlers\n{\n /// A dictionary of linked lists of registrations, indexed by the notification method.\n private readonly Dictionary _handlers = [];\n\n /// Gets the object to be used for all synchronization.\n private object SyncObj => _handlers;\n\n /// \n /// Registers a collection of notification handlers at once.\n /// \n /// \n /// A collection of notification method names paired with their corresponding handler functions.\n /// Each key in the collection is a notification method name, and each value is a handler function\n /// that will be invoked when a notification with that method name is received.\n /// \n /// \n /// \n /// This method is typically used during client or server initialization to register\n /// all notification handlers provided in capabilities.\n /// \n /// \n /// Registrations completed with this method are permanent and non-removable.\n /// This differs from handlers registered with which can be temporary.\n /// \n /// \n /// When multiple handlers are registered for the same method, all handlers will be invoked\n /// in reverse order of registration (newest first) when a notification is received.\n /// \n /// \n /// The registered handlers will be invoked by when a notification\n /// with the corresponding method name is received.\n /// \n /// \n public void RegisterRange(IEnumerable>> handlers)\n {\n foreach (var entry in handlers)\n {\n _ = Register(entry.Key, entry.Value, temporary: false);\n }\n }\n\n /// \n /// Adds a notification handler as part of configuring the endpoint.\n /// \n /// The notification method for which the handler is being registered.\n /// The handler being registered.\n /// \n /// if the registration can be removed later; if it cannot.\n /// If , the registration will be permanent: calling \n /// on the returned instance will not unregister the handler.\n /// \n /// \n /// An that when disposed will unregister the handler if is .\n /// \n /// \n /// Multiple handlers can be registered for the same method. When a notification for that method is received,\n /// all registered handlers will be invoked in reverse order of registration (newest first).\n /// \n public IAsyncDisposable Register(\n string method, Func handler, bool temporary = true)\n {\n // Create the new registration instance.\n Registration reg = new(this, method, handler, temporary);\n\n // Store the registration into the dictionary. If there's not currently a registration for the method,\n // then this registration instance just becomes the single value. If there is currently a registration,\n // then this new registration becomes the new head of the linked list, and the old head becomes the next\n // item in the list.\n lock (SyncObj)\n {\n if (_handlers.TryGetValue(method, out var existingHandlerHead))\n {\n reg.Next = existingHandlerHead;\n existingHandlerHead.Prev = reg;\n }\n\n _handlers[method] = reg;\n }\n\n // Return the new registration. It must be disposed of when no longer used, or it will end up being\n // leaked into the list. This is the same as with CancellationToken.Register.\n return reg;\n }\n\n /// \n /// Invokes all registered handlers for the specified notification method.\n /// \n /// The notification method name to invoke handlers for.\n /// The notification object to pass to each handler.\n /// A token that can be used to cancel the operation.\n /// \n /// Handlers are invoked in reverse order of registration (newest first).\n /// If any handler throws an exception, all handlers will still be invoked, and an \n /// containing all exceptions will be thrown after all handlers have been invoked.\n /// \n public async Task InvokeHandlers(string method, JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // If there are no handlers registered for this method, we're done.\n Registration? reg;\n lock (SyncObj)\n {\n if (!_handlers.TryGetValue(method, out reg))\n {\n return;\n }\n }\n\n // Invoke each handler in the list. We guarantee that we'll try to invoke\n // any handlers that were in the list when the list was fetched from the dictionary,\n // which is why DisposeAsync doesn't modify the Prev/Next of the registration being\n // disposed; if those were nulled out, we'd be unable to walk around it in the list\n // if we happened to be on that item when it was disposed.\n List? exceptions = null;\n while (reg is not null)\n {\n try\n {\n await reg.InvokeAsync(notification, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e)\n {\n (exceptions ??= []).Add(e);\n }\n\n lock (SyncObj)\n {\n reg = reg.Next;\n }\n }\n\n if (exceptions is not null)\n {\n throw new AggregateException(exceptions);\n }\n }\n\n /// Provides storage for a handler registration.\n private sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable) : IAsyncDisposable\n {\n /// Used to prevent deadlocks during disposal.\n /// \n /// The task returned from does not complete until all invocations of the handler\n /// have completed and no more will be performed, so that the consumer can then trust that any resources accessed\n /// by that handler are no longer in use and may be cleaned up. If were to be invoked\n /// and its task awaited from within the invocation of the handler, however, that would result in deadlock, since\n /// the task wouldn't complete until the invocation completed, and the invocation wouldn't complete until the task\n /// completed. To circument that, we track via an in-flight invocations. If\n /// detects it's being invoked from within an invocation, it will avoid waiting. For\n /// simplicity, we don't require that it's the same handler.\n /// \n private static readonly AsyncLocal s_invokingAncestor = new();\n\n /// The parent to which this registration belongs.\n private readonly NotificationHandlers _handlers = handlers;\n\n /// The method with which this registration is associated.\n private readonly string _method = method;\n \n /// The handler this registration represents.\n private readonly Func _handler = handler;\n\n /// true if this instance is temporary; false if it's permanent\n private readonly bool _temporary = unregisterable;\n\n /// Provides a task that can await to know when all in-flight invocations have completed.\n /// \n /// This will only be initialized if sees in-flight invocations, in which case it'll initialize\n /// this and then await its task. The task will be completed when the last\n /// in-flight notification completes.\n /// \n private TaskCompletionSource? _disposeTcs;\n \n /// The number of remaining references to this registration.\n /// \n /// The ref count starts life at 1 to represent the whole registration; that ref count will be subtracted when\n /// the instance is disposed. Every invocation then temporarily increases the ref count before invocation and\n /// decrements it after. When is called, it decrements the ref count. In the common\n /// case, that'll bring the count down to 0, in which case the instance will never be subsequently invoked.\n /// If, however, after that decrement the count is still positive, then there are in-flight invocations; the last\n /// one of those to complete will end up decrementing the ref count to 0.\n /// \n private int _refCount = 1;\n\n /// Tracks whether has ever been invoked.\n /// \n /// It's rare but possible is called multiple times. Only the first\n /// should decrement the initial ref count, but they all must wait until all invocations have quiesced.\n /// \n private bool _disposedCalled = false;\n\n /// The next registration in the linked list.\n public Registration? Next;\n /// \n /// The previous registration in the linked list of handlers for a specific notification method.\n /// Used to maintain the bidirectional linked list when handlers are added or removed.\n /// \n public Registration? Prev;\n\n /// Removes the registration.\n public async ValueTask DisposeAsync()\n {\n if (!_temporary)\n {\n return;\n }\n\n lock (_handlers.SyncObj)\n {\n // If DisposeAsync was previously called, we don't want to do all of the work again\n // to remove the registration from the list, and we must not do the work again to\n // decrement the ref count and possibly initialize the _disposeTcs.\n if (!_disposedCalled)\n {\n _disposedCalled = true;\n\n // If this handler is the head of the list for this method, we need to update\n // the dictionary, either to point to a different head, or if this is the only\n // item in the list, to remove the entry from the dictionary entirely.\n if (_handlers._handlers.TryGetValue(_method, out var handlers) && handlers == this)\n {\n if (Next is not null)\n {\n _handlers._handlers[_method] = Next;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n\n // Remove the registration from the linked list by routing the nodes around it\n // to point past this one. Importantly, we do not modify this node's Next or Prev.\n // We want to ensure that an enumeration through all of the registrations can still\n // progress through this one.\n if (Prev is not null)\n {\n Prev.Next = Next;\n }\n if (Next is not null)\n {\n Next.Prev = Prev;\n }\n\n // Decrement the ref count. In the common case, there's no in-flight invocation for\n // this handler. However, in the uncommon case that there is, we need to wait for\n // that invocation to complete. To do that, initialize the _disposeTcs. It's created\n // with RunContinuationsAsynchronously so that completing it doesn't run the continuation\n // under any held locks.\n if (--_refCount != 0)\n {\n Debug.Assert(_disposeTcs is null);\n _disposeTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);\n }\n }\n }\n\n // Ensure that DisposeAsync doesn't complete until all in-flight invocations have completed,\n // unless our call chain includes one of those in-flight invocations, in which case waiting\n // would deadlock.\n if (_disposeTcs is not null && s_invokingAncestor.Value == 0)\n {\n await _disposeTcs.Task.ConfigureAwait(false);\n }\n }\n\n /// Invoke the handler associated with the registration.\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // For permanent registrations, skip all the tracking overhead and just invoke the handler.\n if (!_temporary)\n {\n return _handler(notification, cancellationToken);\n }\n\n // For temporary registrations, track the invocation and coordinate with disposal.\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n\n /// Invoke the handler associated with the temporary registration.\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // Check whether we need to handle this registration. If DisposeAsync has been called,\n // then even if there are in-flight invocations for it, we avoid adding more.\n // If DisposeAsync has not been called, then we need to increment the ref count to\n // signal that there's another in-flight invocation.\n lock (_handlers.SyncObj)\n {\n Debug.Assert(_refCount != 0 || _disposedCalled, $\"Expected {nameof(_disposedCalled)} == true when {nameof(_refCount)} == 0\");\n if (_disposedCalled)\n {\n return;\n }\n\n Debug.Assert(_refCount > 0);\n _refCount++;\n }\n\n // Ensure that if DisposeAsync is called from within the handler, it won't deadlock by waiting\n // for the in-flight invocation to complete.\n s_invokingAncestor.Value++;\n\n try\n {\n // Invoke the handler.\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n // Undo the in-flight tracking.\n s_invokingAncestor.Value--;\n\n // Now decrement the ref count we previously incremented. If that brings the ref count to 0,\n // DisposeAsync must have been called while this was in-flight, which also means it's now\n // waiting on _disposeTcs; unblock it.\n lock (_handlers.SyncObj)\n {\n _refCount--;\n if (_refCount == 0)\n {\n Debug.Assert(_disposedCalled);\n Debug.Assert(_disposeTcs is not null);\n bool completed = _disposeTcs!.TrySetResult(true);\n Debug.Assert(completed);\n }\n }\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/SemaphoreSlimExtensions.cs", "namespace ModelContextProtocol;\n\ninternal static class SynchronizationExtensions\n{\n /// \n /// Asynchronously acquires a lock on the semaphore and returns a disposable object that releases the lock when disposed.\n /// \n /// The semaphore to acquire a lock on.\n /// A cancellation token to observe while waiting for the semaphore.\n /// A disposable that releases the semaphore when disposed.\n /// \n /// This extension method provides a convenient pattern for using a semaphore in asynchronous code,\n /// similar to how the `lock` statement is used in synchronous code.\n /// \n /// The was canceled.\n public static async ValueTask LockAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)\n {\n await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);\n return new(semaphore);\n }\n\n /// \n /// A disposable struct that releases a semaphore when disposed.\n /// \n /// \n /// This struct is used with the extension method to provide\n /// a using-pattern for semaphore locking, similar to lock statements.\n /// \n public readonly struct Releaser(SemaphoreSlim semaphore) : IDisposable\n {\n /// \n /// Releases the semaphore.\n /// \n /// \n /// This method is called automatically when the goes out of scope\n /// in a using statement or expression.\n /// \n public void Dispose() => semaphore.Release();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitRequestParams.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued from the server to elicit additional information from the user via the client.\n/// \npublic sealed class ElicitRequestParams\n{\n /// \n /// Gets or sets the message to present to the user.\n /// \n [JsonPropertyName(\"message\")]\n public string Message { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the requested schema.\n /// \n /// \n /// May be one of , , , or .\n /// \n [JsonPropertyName(\"requestedSchema\")]\n [field: MaybeNull]\n public RequestSchema RequestedSchema\n {\n get => field ??= new RequestSchema();\n set => field = value;\n }\n\n /// Represents a request schema used in an elicitation request.\n public class RequestSchema\n {\n /// Gets the type of the schema.\n /// This is always \"object\".\n [JsonPropertyName(\"type\")]\n public string Type => \"object\";\n\n /// Gets or sets the properties of the schema.\n [JsonPropertyName(\"properties\")]\n [field: MaybeNull]\n public IDictionary Properties\n {\n get => field ??= new Dictionary();\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets the required properties of the schema.\n [JsonPropertyName(\"required\")]\n public IList? Required { get; set; }\n }\n\n /// \n /// Represents restricted subset of JSON Schema: \n /// , , , or .\n /// \n [JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n public abstract class PrimitiveSchemaDefinition\n {\n /// Prevent external derivations.\n protected private PrimitiveSchemaDefinition()\n {\n }\n\n /// Gets the type of the schema.\n [JsonPropertyName(\"type\")]\n public abstract string Type { get; set; }\n\n /// Gets or sets a title for the schema.\n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// Gets or sets a description for the schema.\n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override PrimitiveSchemaDefinition? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? title = null;\n string? description = null;\n int? minLength = null;\n int? maxLength = null;\n string? format = null;\n double? minimum = null;\n double? maximum = null;\n bool? defaultBool = null;\n IList? enumValues = null;\n IList? enumNames = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"title\":\n title = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"minLength\":\n minLength = reader.GetInt32();\n break;\n\n case \"maxLength\":\n maxLength = reader.GetInt32();\n break;\n\n case \"format\":\n format = reader.GetString();\n break;\n\n case \"minimum\":\n minimum = reader.GetDouble();\n break;\n\n case \"maximum\":\n maximum = reader.GetDouble();\n break;\n\n case \"default\":\n defaultBool = reader.GetBoolean();\n break;\n\n case \"enum\":\n enumValues = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n case \"enumNames\":\n enumNames = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n default:\n break;\n }\n }\n\n if (type is null)\n {\n throw new JsonException(\"The 'type' property is required.\");\n }\n\n PrimitiveSchemaDefinition? psd = null;\n switch (type)\n {\n case \"string\":\n if (enumValues is not null)\n {\n psd = new EnumSchema\n {\n Enum = enumValues,\n EnumNames = enumNames\n };\n }\n else\n {\n psd = new StringSchema\n {\n MinLength = minLength,\n MaxLength = maxLength,\n Format = format,\n };\n }\n break;\n\n case \"integer\":\n case \"number\":\n psd = new NumberSchema\n {\n Minimum = minimum,\n Maximum = maximum,\n };\n break;\n\n case \"boolean\":\n psd = new BooleanSchema\n {\n Default = defaultBool,\n };\n break;\n }\n\n if (psd is not null)\n {\n psd.Type = type;\n psd.Title = title;\n psd.Description = description;\n }\n\n return psd;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, PrimitiveSchemaDefinition value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n if (value.Title is not null)\n {\n writer.WriteString(\"title\", value.Title);\n }\n if (value.Description is not null)\n {\n writer.WriteString(\"description\", value.Description);\n }\n\n switch (value)\n {\n case StringSchema stringSchema:\n if (stringSchema.MinLength.HasValue)\n {\n writer.WriteNumber(\"minLength\", stringSchema.MinLength.Value);\n }\n if (stringSchema.MaxLength.HasValue)\n {\n writer.WriteNumber(\"maxLength\", stringSchema.MaxLength.Value);\n }\n if (stringSchema.Format is not null)\n {\n writer.WriteString(\"format\", stringSchema.Format);\n }\n break;\n\n case NumberSchema numberSchema:\n if (numberSchema.Minimum.HasValue)\n {\n writer.WriteNumber(\"minimum\", numberSchema.Minimum.Value);\n }\n if (numberSchema.Maximum.HasValue)\n {\n writer.WriteNumber(\"maximum\", numberSchema.Maximum.Value);\n }\n break;\n\n case BooleanSchema booleanSchema:\n if (booleanSchema.Default.HasValue)\n {\n writer.WriteBoolean(\"default\", booleanSchema.Default.Value);\n }\n break;\n\n case EnumSchema enumSchema:\n if (enumSchema.Enum is not null)\n {\n writer.WritePropertyName(\"enum\");\n JsonSerializer.Serialize(writer, enumSchema.Enum, McpJsonUtilities.JsonContext.Default.IListString);\n }\n if (enumSchema.EnumNames is not null)\n {\n writer.WritePropertyName(\"enumNames\");\n JsonSerializer.Serialize(writer, enumSchema.EnumNames, McpJsonUtilities.JsonContext.Default.IListString);\n }\n break;\n\n default:\n throw new JsonException($\"Unexpected schema type: {value.GetType().Name}\");\n }\n\n writer.WriteEndObject();\n }\n }\n }\n\n /// Represents a schema for a string type.\n public sealed class StringSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the minimum length for the string.\n [JsonPropertyName(\"minLength\")]\n public int? MinLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Minimum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the maximum length for the string.\n [JsonPropertyName(\"maxLength\")]\n public int? MaxLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Maximum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets a specific format for the string (\"email\", \"uri\", \"date\", or \"date-time\").\n [JsonPropertyName(\"format\")]\n public string? Format\n {\n get => field;\n set\n {\n if (value is not (null or \"email\" or \"uri\" or \"date\" or \"date-time\"))\n {\n throw new ArgumentException(\"Format must be 'email', 'uri', 'date', or 'date-time'.\", nameof(value));\n }\n\n field = value;\n }\n }\n }\n\n /// Represents a schema for a number or integer type.\n public sealed class NumberSchema : PrimitiveSchemaDefinition\n {\n /// \n [field: MaybeNull]\n public override string Type\n {\n get => field ??= \"number\";\n set\n {\n if (value is not (\"number\" or \"integer\"))\n {\n throw new ArgumentException(\"Type must be 'number' or 'integer'.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the minimum allowed value.\n [JsonPropertyName(\"minimum\")]\n public double? Minimum { get; set; }\n\n /// Gets or sets the maximum allowed value.\n [JsonPropertyName(\"maximum\")]\n public double? Maximum { get; set; }\n }\n\n /// Represents a schema for a Boolean type.\n public sealed class BooleanSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"boolean\";\n set\n {\n if (value is not \"boolean\")\n {\n throw new ArgumentException(\"Type must be 'boolean'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the default value for the Boolean.\n [JsonPropertyName(\"default\")]\n public bool? Default { get; set; }\n }\n\n /// Represents a schema for an enum type.\n public sealed class EnumSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the list of allowed string values for the enum.\n [JsonPropertyName(\"enum\")]\n [field: MaybeNull]\n public IList Enum\n {\n get => field ??= [];\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets optional display names corresponding to the enum values.\n [JsonPropertyName(\"enumNames\")]\n public IList? EnumNames { get; set; }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ProgressNotificationParams.cs", "using Microsoft.Extensions.Logging.Abstractions;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an out-of-band notification used to inform the receiver of a progress update for a long-running request.\n/// \n/// \n/// See the schema for more details.\n/// \n[JsonConverter(typeof(Converter))]\npublic sealed class ProgressNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the progress token which was given in the initial request, used to associate this notification with \n /// the corresponding request.\n /// \n /// \n /// \n /// This token acts as a correlation identifier that links progress updates to their corresponding request.\n /// \n /// \n /// When an endpoint initiates a request with a in its metadata, \n /// the receiver can send progress notifications using this same token. This allows both sides to \n /// correlate the notifications with the original request.\n /// \n /// \n public required ProgressToken ProgressToken { get; init; }\n\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// This should increase for each notification issued as part of the same request, even if the total is unknown.\n /// \n public required ProgressNotificationValue Progress { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressNotificationParams? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n ProgressToken? progressToken = null;\n float? progress = null;\n float? total = null;\n string? message = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType == JsonTokenType.PropertyName)\n {\n var propertyName = reader.GetString();\n reader.Read();\n switch (propertyName)\n {\n case \"progressToken\":\n progressToken = (ProgressToken)JsonSerializer.Deserialize(ref reader, options.GetTypeInfo(typeof(ProgressToken)))!;\n break;\n\n case \"progress\":\n progress = reader.GetSingle();\n break;\n\n case \"total\":\n total = reader.GetSingle();\n break;\n\n case \"message\":\n message = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n }\n }\n }\n\n if (progress is null)\n {\n throw new JsonException(\"Missing required property 'progress'.\");\n }\n\n if (progressToken is null)\n {\n throw new JsonException(\"Missing required property 'progressToken'.\");\n }\n\n return new ProgressNotificationParams\n {\n ProgressToken = progressToken.GetValueOrDefault(),\n Progress = new ProgressNotificationValue\n {\n Progress = progress.GetValueOrDefault(),\n Total = total,\n Message = message,\n },\n Meta = meta,\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressNotificationParams value, JsonSerializerOptions options)\n {\n writer.WriteStartObject();\n\n writer.WritePropertyName(\"progressToken\");\n JsonSerializer.Serialize(writer, value.ProgressToken, options.GetTypeInfo(typeof(ProgressToken)));\n\n writer.WriteNumber(\"progress\", value.Progress.Progress);\n\n if (value.Progress.Total is { } total)\n {\n writer.WriteNumber(\"total\", total);\n }\n\n if (value.Progress.Message is { } message)\n {\n writer.WriteString(\"message\", message);\n }\n\n if (value.Meta is { } meta)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthenticatingMcpHttpClient.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Net.Http.Headers;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// A delegating handler that adds authentication tokens to requests and handles 401 responses.\n/// \ninternal sealed class AuthenticatingMcpHttpClient(HttpClient httpClient, ClientOAuthProvider credentialProvider) : McpHttpClient(httpClient)\n{\n // Select first supported scheme as the default\n private string _currentScheme = credentialProvider.SupportedSchemes.FirstOrDefault() ??\n throw new ArgumentException(\"Authorization provider must support at least one authentication scheme.\", nameof(credentialProvider));\n\n /// \n /// Sends an HTTP request with authentication handling.\n /// \n internal override async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (request.Headers.Authorization == null)\n {\n await AddAuthorizationHeaderAsync(request, _currentScheme, cancellationToken).ConfigureAwait(false);\n }\n\n var response = await base.SendAsync(request, message, cancellationToken).ConfigureAwait(false);\n\n if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)\n {\n return await HandleUnauthorizedResponseAsync(request, message, response, cancellationToken).ConfigureAwait(false);\n }\n\n return response;\n }\n\n /// \n /// Handles a 401 Unauthorized response by attempting to authenticate and retry the request.\n /// \n private async Task HandleUnauthorizedResponseAsync(\n HttpRequestMessage originalRequest,\n JsonRpcMessage? originalJsonRpcMessage,\n HttpResponseMessage response,\n CancellationToken cancellationToken)\n {\n // Gather the schemes the server wants us to use from WWW-Authenticate headers\n var serverSchemes = ExtractServerSupportedSchemes(response);\n\n if (!serverSchemes.Contains(_currentScheme))\n {\n // Find the first server scheme that's in our supported set\n var bestSchemeMatch = serverSchemes.Intersect(credentialProvider.SupportedSchemes, StringComparer.OrdinalIgnoreCase).FirstOrDefault();\n\n if (bestSchemeMatch is not null)\n {\n _currentScheme = bestSchemeMatch;\n }\n else if (serverSchemes.Count > 0)\n {\n // If no match was found, either throw an exception or use default\n throw new McpException(\n $\"The server does not support any of the provided authentication schemes.\" +\n $\"Server supports: [{string.Join(\", \", serverSchemes)}], \" +\n $\"Provider supports: [{string.Join(\", \", credentialProvider.SupportedSchemes)}].\");\n }\n }\n\n // Try to handle the 401 response with the selected scheme\n await credentialProvider.HandleUnauthorizedResponseAsync(_currentScheme, response, cancellationToken).ConfigureAwait(false);\n\n using var retryRequest = new HttpRequestMessage(originalRequest.Method, originalRequest.RequestUri);\n\n // Copy headers except Authorization which we'll set separately\n foreach (var header in originalRequest.Headers)\n {\n if (!header.Key.Equals(\"Authorization\", StringComparison.OrdinalIgnoreCase))\n {\n retryRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);\n }\n }\n\n await AddAuthorizationHeaderAsync(retryRequest, _currentScheme, cancellationToken).ConfigureAwait(false);\n return await base.SendAsync(retryRequest, originalJsonRpcMessage, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Extracts the authentication schemes that the server supports from the WWW-Authenticate headers.\n /// \n private static HashSet ExtractServerSupportedSchemes(HttpResponseMessage response)\n {\n var serverSchemes = new HashSet(StringComparer.OrdinalIgnoreCase);\n\n foreach (var header in response.Headers.WwwAuthenticate)\n {\n serverSchemes.Add(header.Scheme);\n }\n\n return serverSchemes;\n }\n\n /// \n /// Adds an authorization header to the request.\n /// \n private async Task AddAuthorizationHeaderAsync(HttpRequestMessage request, string scheme, CancellationToken cancellationToken)\n {\n if (request.RequestUri is null)\n {\n return;\n }\n\n var token = await credentialProvider.GetCredentialAsync(scheme, request.RequestUri, cancellationToken).ConfigureAwait(false);\n if (string.IsNullOrEmpty(token))\n {\n return;\n }\n\n request.Headers.Authorization = new AuthenticationHeaderValue(scheme, token);\n }\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer server,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await server.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DestinationBoundMcpServer.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class DestinationBoundMcpServer(McpServer server, ITransport? transport) : IMcpServer\n{\n public string EndpointName => server.EndpointName;\n public string? SessionId => transport?.SessionId ?? server.SessionId;\n public ClientCapabilities? ClientCapabilities => server.ClientCapabilities;\n public Implementation? ClientInfo => server.ClientInfo;\n public McpServerOptions ServerOptions => server.ServerOptions;\n public IServiceProvider? Services => server.Services;\n public LoggingLevel? LoggingLevel => server.LoggingLevel;\n\n public ValueTask DisposeAsync() => server.DisposeAsync();\n\n public IAsyncDisposable RegisterNotificationHandler(string method, Func handler) => server.RegisterNotificationHandler(method, handler);\n\n // This will throw because the server must already be running for this class to be constructed, but it should give us a good Exception message.\n public Task RunAsync(CancellationToken cancellationToken) => server.RunAsync(cancellationToken);\n\n public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Debug.Assert(message.RelatedTransport is null);\n message.RelatedTransport = transport;\n return server.SendMessageAsync(message, cancellationToken);\n }\n\n public Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)\n {\n Debug.Assert(request.RelatedTransport is null);\n request.RelatedTransport = transport;\n return server.SendRequestAsync(request, cancellationToken);\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses depenency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await thisServer.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpEndpointExtensions.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class provides strongly-typed methods for working with the Model Context Protocol (MCP) endpoints,\n/// simplifying JSON-RPC communication by handling serialization and deserialization of parameters and results.\n/// \n/// \n/// These extension methods are designed to be used with both client () and\n/// server () implementations of the interface.\n/// \n/// \npublic static class McpEndpointExtensions\n{\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The request id for the request.\n /// The options governing request serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n public static ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo paramsTypeInfo = serializerOptions.GetTypeInfo();\n JsonTypeInfo resultTypeInfo = serializerOptions.GetTypeInfo();\n return SendRequestAsync(endpoint, method, parameters, paramsTypeInfo, resultTypeInfo, requestId, cancellationToken);\n }\n\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The type information for request parameter deserialization.\n /// The request id for the request.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n internal static async ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n JsonTypeInfo resultTypeInfo,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n Throw.IfNull(resultTypeInfo);\n\n JsonRpcRequest jsonRpcRequest = new()\n {\n Id = requestId,\n Method = method,\n Params = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo),\n };\n\n JsonRpcResponse response = await endpoint.SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.Deserialize(response.Result, resultTypeInfo) ?? throw new JsonException(\"Unexpected JSON result in response.\");\n }\n\n /// \n /// Sends a parameterless notification to the connected endpoint.\n /// \n /// The MCP client or server instance.\n /// The notification method name.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification without any parameters. Notifications are one-way messages \n /// that don't expect a response. They are commonly used for events, status updates, or to signal \n /// changes in state.\n /// \n /// \n public static Task SendNotificationAsync(this IMcpEndpoint client, string method, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(method);\n return client.SendMessageAsync(new JsonRpcNotification { Method = method }, cancellationToken);\n }\n\n /// \n /// Sends a notification with parameters to the connected endpoint.\n /// \n /// The type of the notification parameters to serialize.\n /// The MCP client or server instance.\n /// The JSON-RPC method name for the notification.\n /// Object representing the notification parameters.\n /// The options governing parameter serialization. If null, default options are used.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification with parameters to the connected endpoint. Notifications are one-way \n /// messages that don't expect a response, commonly used for events, status updates, or signaling changes.\n /// \n /// \n /// The parameters object is serialized to JSON according to the provided serializer options or the default \n /// options if none are specified.\n /// \n /// \n /// The Model Context Protocol defines several standard notification methods in ,\n /// but custom methods can also be used for application-specific notifications.\n /// \n /// \n public static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo parametersTypeInfo = serializerOptions.GetTypeInfo();\n return SendNotificationAsync(endpoint, method, parameters, parametersTypeInfo, cancellationToken);\n }\n\n /// \n /// Sends a notification to the server with parameters.\n /// \n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The to monitor for cancellation requests. The default is .\n internal static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n\n JsonNode? parametersJson = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo);\n return endpoint.SendMessageAsync(new JsonRpcNotification { Method = method, Params = parametersJson }, cancellationToken);\n }\n\n /// \n /// Notifies the connected endpoint of progress for a long-running operation.\n /// \n /// The endpoint issuing the notification.\n /// The identifying the operation for which progress is being reported.\n /// The progress update to send, containing information such as percentage complete or status message.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the completion of the notification operation (not the operation being tracked).\n /// is .\n /// \n /// \n /// This method sends a progress notification to the connected endpoint using the Model Context Protocol's\n /// standardized progress notification format. Progress updates are identified by a \n /// that allows the recipient to correlate multiple updates with a specific long-running operation.\n /// \n /// \n /// Progress notifications are sent asynchronously and don't block the operation from continuing.\n /// \n /// \n public static Task NotifyProgressAsync(\n this IMcpEndpoint endpoint,\n ProgressToken progressToken,\n ProgressNotificationValue progress, \n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n\n return endpoint.SendNotificationAsync(\n NotificationMethods.ProgressNotification,\n new ProgressNotificationParams\n {\n ProgressToken = progressToken,\n Progress = progress,\n },\n McpJsonUtilities.JsonContext.Default.ProgressNotificationParams,\n cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContentBlock.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents content within the Model Context Protocol (MCP).\n/// \n/// \n/// \n/// The class is a fundamental type in the MCP that can represent different forms of content\n/// based on the property. Derived types like , ,\n/// and provide the type-specific content.\n/// \n/// \n/// This class is used throughout the MCP for representing content in messages, tool responses,\n/// and other communication between clients and servers.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\npublic abstract class ContentBlock\n{\n /// Prevent external derivations.\n private protected ContentBlock()\n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This determines the structure of the content object. Valid values include \"image\", \"audio\", \"text\", \"resource\", and \"resource_link\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Gets or sets optional annotations for the content.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the content. Clients can use this information to filter or prioritize content for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ContentBlock? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? text = null;\n string? name = null;\n string? data = null;\n string? mimeType = null;\n string? uri = null;\n string? description = null;\n long? size = null;\n ResourceContents? resource = null;\n Annotations? annotations = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"data\":\n data = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"size\":\n size = reader.GetInt64();\n break;\n\n case \"resource\":\n resource = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.ResourceContents);\n break;\n\n case \"annotations\":\n annotations = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.Annotations);\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n return type switch\n {\n \"text\" => new TextContentBlock\n {\n Text = text ?? throw new JsonException(\"Text contents must be provided for 'text' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"image\" => new ImageContentBlock\n {\n Data = data ?? throw new JsonException(\"Image data must be provided for 'image' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'image' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"audio\" => new AudioContentBlock\n {\n Data = data ?? throw new JsonException(\"Audio data must be provided for 'audio' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'audio' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource\" => new EmbeddedResourceBlock\n {\n Resource = resource ?? throw new JsonException(\"Resource contents must be provided for 'resource' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource_link\" => new ResourceLinkBlock\n {\n Uri = uri ?? throw new JsonException(\"URI must be provided for 'resource_link' type.\"),\n Name = name ?? throw new JsonException(\"Name must be provided for 'resource_link' type.\"),\n Description = description,\n MimeType = mimeType,\n Size = size,\n Annotations = annotations,\n },\n\n _ => throw new JsonException($\"Unknown content type: '{type}'\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case TextContentBlock textContent:\n writer.WriteString(\"text\", textContent.Text);\n if (textContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, textContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ImageContentBlock imageContent:\n writer.WriteString(\"data\", imageContent.Data);\n writer.WriteString(\"mimeType\", imageContent.MimeType);\n if (imageContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, imageContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case AudioContentBlock audioContent:\n writer.WriteString(\"data\", audioContent.Data);\n writer.WriteString(\"mimeType\", audioContent.MimeType);\n if (audioContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, audioContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case EmbeddedResourceBlock embeddedResource:\n writer.WritePropertyName(\"resource\");\n JsonSerializer.Serialize(writer, embeddedResource.Resource, McpJsonUtilities.JsonContext.Default.ResourceContents);\n if (embeddedResource.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, embeddedResource.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ResourceLinkBlock resourceLink:\n writer.WriteString(\"uri\", resourceLink.Uri);\n writer.WriteString(\"name\", resourceLink.Name);\n if (resourceLink.Description is not null)\n {\n writer.WriteString(\"description\", resourceLink.Description);\n }\n if (resourceLink.MimeType is not null)\n {\n writer.WriteString(\"mimeType\", resourceLink.MimeType);\n }\n if (resourceLink.Size.HasValue)\n {\n writer.WriteNumber(\"size\", resourceLink.Size.Value);\n }\n break;\n }\n\n if (value.Annotations is { } annotations)\n {\n writer.WritePropertyName(\"annotations\");\n JsonSerializer.Serialize(writer, annotations, McpJsonUtilities.JsonContext.Default.Annotations);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// Represents text provided to or from an LLM.\npublic sealed class TextContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public TextContentBlock() => Type = \"text\";\n\n /// \n /// Gets or sets the text content of the message.\n /// \n [JsonPropertyName(\"text\")]\n public required string Text { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents an image provided to or from an LLM.\npublic sealed class ImageContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ImageContentBlock() => Type = \"image\";\n\n /// \n /// Gets or sets the base64-encoded image data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"image/png\" and \"image/jpeg\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents audio provided to or from an LLM.\npublic sealed class AudioContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public AudioContentBlock() => Type = \"audio\";\n\n /// \n /// Gets or sets the base64-encoded audio data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"audio/wav\" and \"audio/mp3\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents the contents of a resource, embedded into a prompt or tool call result.\n/// \n/// It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user.\n/// \npublic sealed class EmbeddedResourceBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public EmbeddedResourceBlock() => Type = \"resource\";\n\n /// \n /// Gets or sets the resource content of the message when is \"resource\".\n /// \n /// \n /// \n /// Resources can be either text-based () or \n /// binary (), allowing for flexible data representation.\n /// Each resource has a URI that can be used for identification and retrieval.\n /// \n /// \n [JsonPropertyName(\"resource\")]\n public required ResourceContents Resource { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents a resource that the server is capable of reading, included in a prompt or tool call result.\n/// \n/// Resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n/// \npublic sealed class ResourceLinkBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ResourceLinkBlock() => Type = \"resource_link\";\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for this resource.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientPrompt.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named prompt that can be retrieved from an MCP server and invoked with arguments.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a prompt defined on an MCP server. It allows\n/// retrieving the prompt's content by sending a request to the server with optional arguments.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \n/// Each prompt has a name and optionally a description, and it can be invoked with arguments\n/// to produce customized prompt content from the server.\n/// \n/// \npublic sealed class McpClientPrompt\n{\n private readonly IMcpClient _client;\n\n internal McpClientPrompt(IMcpClient client, Prompt prompt)\n {\n _client = client;\n ProtocolPrompt = prompt;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the prompt,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Prompt ProtocolPrompt { get; }\n\n /// Gets the name of the prompt.\n public string Name => ProtocolPrompt.Name;\n\n /// Gets the title of the prompt.\n public string? Title => ProtocolPrompt.Title;\n\n /// Gets a description of the prompt.\n public string? Description => ProtocolPrompt.Description;\n\n /// \n /// Gets this prompt's content by sending a request to the server with optional arguments.\n /// \n /// Optional arguments to pass to the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to execute this prompt with the provided arguments.\n /// The server will process the request and return a result containing messages or other content.\n /// \n /// \n /// This is a convenience method that internally calls \n /// with this prompt's name and arguments.\n /// \n /// \n public async ValueTask GetAsync(\n IEnumerable>? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n IReadOnlyDictionary? argDict =\n arguments as IReadOnlyDictionary ??\n arguments?.ToDictionary();\n\n return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, serializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ITransport.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Server;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a transport mechanism for MCP (Model Context Protocol) communication between clients and servers.\n/// \n/// \n/// \n/// The interface is the core abstraction for bidirectional communication.\n/// It provides methods for sending and receiving messages, abstracting away the underlying transport mechanism\n/// and allowing protocol implementations to be decoupled from communication details.\n/// \n/// \n/// Implementations of handle the serialization, transmission, and reception of\n/// messages over various channels like standard input/output streams and HTTP (Server-Sent Events).\n/// \n/// \n/// While is responsible for establishing a client's connection,\n/// represents an established session. Client implementations typically obtain an\n/// instance by calling .\n/// \n/// \npublic interface ITransport : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Gets a channel reader for receiving messages from the transport.\n /// \n /// \n /// \n /// The provides access to incoming JSON-RPC messages received by the transport.\n /// It returns a which allows consuming messages in a thread-safe manner.\n /// \n /// \n /// The reader will continue to provide messages as long as the transport is connected. When the transport\n /// is disconnected or disposed, the channel will be completed and no more messages will be available after\n /// any already transmitted messages are consumed.\n /// \n /// \n ChannelReader MessageReader { get; }\n\n /// \n /// Sends a JSON-RPC message through the transport.\n /// \n /// The JSON-RPC message to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// \n /// \n /// This method serializes and sends the provided JSON-RPC message through the transport connection.\n /// \n /// \n /// This is a core method used by higher-level abstractions in the MCP protocol implementation.\n /// Most client code should use the higher-level methods provided by ,\n /// , , or ,\n /// rather than accessing this method directly.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientFactory.cs", "using Microsoft.Extensions.Logging;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides factory methods for creating Model Context Protocol (MCP) clients.\n/// \n/// \n/// This factory class is the primary way to instantiate instances\n/// that connect to MCP servers. It handles the creation and connection\n/// of appropriate implementations through the supplied transport.\n/// \npublic static partial class McpClientFactory\n{\n /// Creates an , connecting it to the specified server.\n /// The transport instance used to communicate with the server.\n /// \n /// A client configuration object which specifies client capabilities and protocol version.\n /// If , details based on the current process will be employed.\n /// \n /// A logger factory for creating loggers for clients.\n /// The to monitor for cancellation requests. The default is .\n /// An that's connected to the specified server.\n /// is .\n /// is .\n public static async Task CreateAsync(\n IClientTransport clientTransport,\n McpClientOptions? clientOptions = null,\n ILoggerFactory? loggerFactory = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(clientTransport);\n\n McpClient client = new(clientTransport, clientOptions, loggerFactory);\n try\n {\n await client.ConnectAsync(cancellationToken).ConfigureAwait(false);\n if (loggerFactory?.CreateLogger(typeof(McpClientFactory)) is ILogger logger)\n {\n logger.LogClientCreated(client.EndpointName);\n }\n }\n catch\n {\n await client.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n\n return client;\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} client created and connected.\")]\n private static partial void LogClientCreated(this ILogger logger, string endpointName);\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/UriTemplate.cs", "#if NET\nusing System.Buffers;\n#endif\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol;\n\n/// Provides basic support for parsing and formatting URI templates.\n/// \n/// This implementation should correctly handle valid URI templates, but it has undefined output for invalid templates,\n/// e.g. it may treat portions of invalid templates as literals rather than throwing.\n/// \ninternal static partial class UriTemplate\n{\n /// Regex pattern for finding URI template expressions and parsing out the operator and varname.\n private const string UriTemplateExpressionPattern = \"\"\"\n { # opening brace\n (?[+#./;?&]?) # optional operator\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}) # varchar: letter, digit, underscore, or pct-encoded\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))* # optionally dot-separated subsequent varchars\n )\n (?: :[1-9][0-9]{0,3} )? # optional prefix modifier (1–4 digits)\n \\*? # optional explode\n (?:, # comma separator, followed by the same as above\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*\n )\n (?: :[1-9][0-9]{0,3} )?\n \\*?\n )* # zero or more additional vars\n } # closing brace\n \"\"\";\n\n /// Gets a regex for finding URI template expressions and parsing out the operator and varname.\n /// \n /// This regex is for parsing a static URI template.\n /// It is not for parsing a URI according to a template.\n /// \n#if NET\n [GeneratedRegex(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace)]\n private static partial Regex UriTemplateExpression();\n#else\n private static Regex UriTemplateExpression() => s_uriTemplateExpression;\n private static readonly Regex s_uriTemplateExpression = new(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n#endif\n\n#if NET\n /// SearchValues for characters that needn't be escaped when allowing reserved characters.\n private static readonly SearchValues s_appendWhenAllowReserved = SearchValues.Create(\n \"abcdefghijklmnopqrstuvwxyz\" + // ASCII lowercase letters\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" + // ASCII uppercase letters\n \"0123456789\" + // ASCII digits\n \"-._~\" + // unreserved characters\n \":/?#[]@!$&'()*+,;=\"); // reserved characters\n#endif\n\n /// Create a for matching a URI against a URI template.\n /// The template against which to match.\n /// A regex pattern that can be used to match the specified URI template.\n public static Regex CreateParser(string uriTemplate)\n {\n DefaultInterpolatedStringHandler pattern = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n pattern.AppendFormatted('^');\n\n int lastIndex = 0;\n for (Match m = UriTemplateExpression().Match(uriTemplate); m.Success; m = m.NextMatch())\n {\n pattern.AppendFormatted(Regex.Escape(uriTemplate[lastIndex..m.Index]));\n lastIndex = m.Index + m.Length;\n\n var captures = m.Groups[\"varname\"].Captures;\n List paramNames = new(captures.Count);\n foreach (Capture c in captures)\n {\n paramNames.Add(c.Value);\n }\n\n switch (m.Groups[\"operator\"].Value)\n {\n case \"#\": AppendExpression(ref pattern, paramNames, '#', \"[^,]+\"); break;\n case \"/\": AppendExpression(ref pattern, paramNames, '/', \"[^/?]+\"); break;\n default: AppendExpression(ref pattern, paramNames, null, \"[^/?&]+\"); break;\n \n case \"?\": AppendQueryExpression(ref pattern, paramNames, '?'); break;\n case \"&\": AppendQueryExpression(ref pattern, paramNames, '&'); break;\n }\n }\n\n pattern.AppendFormatted(Regex.Escape(uriTemplate.Substring(lastIndex)));\n pattern.AppendFormatted('$');\n\n return new Regex(\n pattern.ToStringAndClear(),\n RegexOptions.IgnoreCase | RegexOptions.CultureInvariant |\n#if NET\n RegexOptions.NonBacktracking);\n#else\n RegexOptions.Compiled, TimeSpan.FromSeconds(10));\n#endif\n\n // Appends a regex fragment to `pattern` that matches an optional query string starting\n // with the given `prefix` (? or &), and up to one occurrence of each name in\n // `paramNames`. Each parameter is made optional and captured by a named group\n // of the form “paramName=value”.\n static void AppendQueryExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char prefix)\n {\n Debug.Assert(prefix is '?' or '&');\n\n pattern.AppendFormatted(\"(?:\\\\\");\n pattern.AppendFormatted(prefix);\n\n if (paramNames.Count > 0)\n {\n AppendParameter(ref pattern, paramNames[0]);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\&?\");\n AppendParameter(ref pattern, paramNames[i]);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName)\n {\n paramName = Regex.Escape(paramName);\n pattern.AppendFormatted(\"(?:\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\"=(?<\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\">[^/?&]+))?\");\n }\n }\n\n pattern.AppendFormatted(\")?\");\n }\n\n // Chooses a regex character‐class (`valueChars`) based on the initial `prefix` to define which\n // characters make up a parameter value. Then, for each name in `paramNames`, it optionally\n // appends the escaped `prefix` (only on the first parameter, then switches to ','), and\n // adds an optional named capture group `(?valueChars)` to match and capture that value.\n static void AppendExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char? prefix, string valueChars)\n {\n Debug.Assert(prefix is '#' or '/' or null);\n\n if (paramNames.Count > 0)\n {\n if (prefix is not null)\n {\n pattern.AppendFormatted('\\\\');\n pattern.AppendFormatted(prefix);\n pattern.AppendFormatted('?');\n }\n\n AppendParameter(ref pattern, paramNames[0], valueChars);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\,?\");\n AppendParameter(ref pattern, paramNames[i], valueChars);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName, string valueChars)\n {\n pattern.AppendFormatted(\"(?<\");\n pattern.AppendFormatted(Regex.Escape(paramName));\n pattern.AppendFormatted('>');\n pattern.AppendFormatted(valueChars);\n pattern.AppendFormatted(\")?\");\n }\n }\n }\n }\n\n /// \n /// Expand a URI template using the given variable values.\n /// \n public static string FormatUri(string uriTemplate, IReadOnlyDictionary arguments)\n {\n Throw.IfNull(uriTemplate);\n\n ReadOnlySpan uriTemplateSpan = uriTemplate.AsSpan();\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n while (!uriTemplateSpan.IsEmpty)\n {\n // Find the next expression.\n int openBracePos = uriTemplateSpan.IndexOf('{');\n if (openBracePos < 0)\n {\n if (uriTemplate.Length == uriTemplateSpan.Length)\n {\n return uriTemplate;\n }\n\n builder.AppendFormatted(uriTemplateSpan);\n break;\n }\n\n // Append as a literal everything before the next expression.\n builder.AppendFormatted(uriTemplateSpan.Slice(0, openBracePos));\n uriTemplateSpan = uriTemplateSpan.Slice(openBracePos + 1);\n\n int closeBracePos = uriTemplateSpan.IndexOf('}');\n if (closeBracePos < 0)\n {\n throw new FormatException($\"Unmatched '{{' in URI template '{uriTemplate}'\");\n }\n\n ReadOnlySpan expression = uriTemplateSpan.Slice(0, closeBracePos);\n uriTemplateSpan = uriTemplateSpan.Slice(closeBracePos + 1);\n if (expression.IsEmpty)\n {\n continue;\n }\n\n // The start of the expression may be a modifier; if it is, slice it off the expression.\n char modifier = expression[0];\n (string Prefix, string Separator, bool Named, bool IncludeNameIfEmpty, bool IncludeSeparatorIfEmpty, bool AllowReserved, bool PrefixEmptyExpansions, int ExpressionSlice) modifierBehavior = modifier switch\n {\n '+' => (string.Empty, \",\", false, false, true, true, false, 1),\n '#' => (\"#\", \",\", false, false, true, true, true, 1),\n '.' => (\".\", \".\", false, false, true, false, true, 1),\n '/' => (\"/\", \"/\", false, false, true, false, false, 1),\n ';' => (\";\", \";\", true, true, false, false, false, 1),\n '?' => (\"?\", \"&\", true, true, true, false, false, 1),\n '&' => (\"&\", \"&\", true, true, true, false, false, 1),\n _ => (string.Empty, \",\", false, false, true, false, false, 0),\n };\n expression = expression.Slice(modifierBehavior.ExpressionSlice);\n\n List expansions = [];\n\n // Process each varspec in the comma-delimited list in the expression (if it doesn't have any\n // commas, it will be the whole expression).\n while (!expression.IsEmpty)\n {\n // Find the next name.\n int commaPos = expression.IndexOf(',');\n ReadOnlySpan name;\n if (commaPos < 0)\n {\n name = expression;\n expression = ReadOnlySpan.Empty;\n }\n else\n {\n name = expression.Slice(0, commaPos);\n expression = expression.Slice(commaPos + 1);\n }\n\n bool explode = false;\n int prefixLength = -1;\n\n // If the name ends with a *, it means we should explode the value into separate\n // name=value pairs. If it has a colon, it means we should only take the first N characters\n // of the value. If it has both, the * takes precedence and we ignore the colon.\n if (!name.IsEmpty && name[name.Length - 1] == '*')\n {\n explode = true;\n name = name.Slice(0, name.Length - 1);\n }\n else if (name.IndexOf(':') >= 0)\n {\n int colonPos = name.IndexOf(':');\n if (colonPos < 0)\n {\n throw new FormatException($\"Invalid varspec '{name.ToString()}'\");\n }\n\n if (!int.TryParse(name.Slice(colonPos + 1)\n#if !NET\n .ToString()\n#endif\n , out prefixLength))\n {\n throw new FormatException($\"Invalid prefix length in varspec '{name.ToString()}'\");\n }\n\n name = name.Slice(0, colonPos);\n }\n\n // Look up the value for this name. If it doesn't exist, skip it.\n string nameString = name.ToString();\n if (!arguments.TryGetValue(nameString, out var value) || value is null)\n {\n continue;\n }\n\n if (value is IEnumerable list)\n {\n var items = list.Select(i => Encode(i, modifierBehavior.AllowReserved));\n if (explode)\n {\n if (modifierBehavior.Named)\n {\n foreach (var item in items)\n {\n expansions.Add($\"{nameString}={item}\");\n }\n }\n else\n {\n foreach (var item in items)\n {\n expansions.Add(item);\n }\n }\n }\n else\n {\n var joined = string.Join(\",\", items);\n expansions.Add(joined.Length > 0 && modifierBehavior.Named ?\n $\"{nameString}={joined}\" :\n joined);\n }\n }\n else if (value is IReadOnlyDictionary assoc)\n {\n var pairs = assoc.Select(kvp => (\n Encode(kvp.Key, modifierBehavior.AllowReserved),\n Encode(kvp.Value, modifierBehavior.AllowReserved)\n ));\n\n if (explode)\n {\n foreach (var (k, v) in pairs)\n {\n expansions.Add($\"{k}={v}\");\n }\n }\n else\n {\n var joined = string.Join(\",\", pairs.Select(p => $\"{p.Item1},{p.Item2}\"));\n if (joined.Length > 0)\n {\n expansions.Add(modifierBehavior.Named ? $\"{nameString}={joined}\" : joined);\n }\n }\n }\n else\n {\n string s =\n value as string ??\n (value is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) : value.ToString()) ??\n string.Empty;\n\n s = Encode((uint)prefixLength < s.Length ? s.Substring(0, prefixLength) : s, modifierBehavior.AllowReserved);\n if (!modifierBehavior.Named)\n {\n expansions.Add(s);\n }\n else if (s.Length != 0 || modifierBehavior.IncludeNameIfEmpty)\n {\n expansions.Add(\n s.Length != 0 ? $\"{nameString}={s}\" :\n modifierBehavior.IncludeSeparatorIfEmpty ? $\"{nameString}=\" :\n nameString);\n }\n }\n }\n\n if (expansions.Count > 0 && \n (modifierBehavior.PrefixEmptyExpansions || !expansions.All(string.IsNullOrEmpty)))\n {\n builder.AppendLiteral(modifierBehavior.Prefix);\n AppendJoin(ref builder, modifierBehavior.Separator, expansions);\n }\n }\n\n return builder.ToStringAndClear();\n }\n\n private static void AppendJoin(ref DefaultInterpolatedStringHandler builder, string separator, IList values)\n {\n int count = values.Count;\n if (count > 0)\n {\n builder.AppendLiteral(values[0]);\n for (int i = 1; i < count; i++)\n {\n builder.AppendLiteral(separator);\n builder.AppendLiteral(values[i]);\n }\n }\n }\n\n private static string Encode(string value, bool allowReserved)\n {\n if (!allowReserved)\n {\n return Uri.EscapeDataString(value);\n }\n\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n int i = 0;\n#if NET\n i = value.AsSpan().IndexOfAnyExcept(s_appendWhenAllowReserved);\n if (i < 0)\n {\n return value;\n }\n\n builder.AppendFormatted(value.AsSpan(0, i));\n#endif\n\n for (; i < value.Length; ++i)\n {\n char c = value[i];\n if (((uint)((c | 0x20) - 'a') <= 'z' - 'a') ||\n ((uint)(c - '0') <= '9' - '0') ||\n \"-._~:/?#[]@!$&'()*+,;=\".Contains(c))\n {\n builder.AppendFormatted(c);\n }\n else if (c == '%' && i < value.Length - 2 && Uri.IsHexDigit(value[i + 1]) && Uri.IsHexDigit(value[i + 2]))\n {\n builder.AppendFormatted(value.AsSpan(i, 3));\n i += 2;\n }\n else\n {\n AppendHex(ref builder, c);\n }\n }\n\n return builder.ToStringAndClear();\n\n static void AppendHex(ref DefaultInterpolatedStringHandler builder, char c)\n {\n ReadOnlySpan hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];\n\n if (c <= 0x7F)\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[c >> 4]);\n builder.AppendFormatted(hexDigits[c & 0xF]);\n }\n else\n {\n#if NET\n Span utf8 = stackalloc byte[Encoding.UTF8.GetMaxByteCount(1)];\n foreach (byte b in utf8.Slice(0, new Rune(c).EncodeToUtf8(utf8)))\n#else\n foreach (byte b in Encoding.UTF8.GetBytes([c]))\n#endif\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[b >> 4]);\n builder.AppendFormatted(hexDigits[b & 0xF]);\n }\n }\n }\n }\n\n /// \n /// Defines an equality comparer for Uri templates as follows:\n /// 1. Non-templated Uris use regular System.Uri equality comparison (host name is case insensitive).\n /// 2. Templated Uris use regular string equality.\n /// \n /// We do this because non-templated resources are looked up directly from the resource dictionary\n /// and we need to make sure equality is implemented correctly. Templated Uris are resolved in a\n /// fallback step using linear traversal of the resource dictionary, so their equality is only\n /// there to distinguish between different templates.\n /// \n public sealed class UriTemplateComparer : IEqualityComparer\n {\n public static IEqualityComparer Instance { get; } = new UriTemplateComparer();\n\n public bool Equals(string? uriTemplate1, string? uriTemplate2)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate1, out Uri? uri1) &&\n TryParseAsNonTemplatedUri(uriTemplate2, out Uri? uri2))\n {\n return uri1 == uri2;\n }\n\n return string.Equals(uriTemplate1, uriTemplate2, StringComparison.Ordinal);\n }\n\n public int GetHashCode([DisallowNull] string uriTemplate)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate, out Uri? uri))\n {\n return uri.GetHashCode();\n }\n else\n {\n return StringComparer.Ordinal.GetHashCode(uriTemplate);\n }\n }\n\n private static bool TryParseAsNonTemplatedUri(string? uriTemplate, [NotNullWhen(true)] out Uri? uri)\n {\n if (uriTemplate is null || uriTemplate.Contains('{'))\n {\n uri = null;\n return false;\n }\n\n return Uri.TryCreate(uriTemplate, UriKind.Absolute, out uri);\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessage.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents any JSON-RPC message used in the Model Context Protocol (MCP).\n/// \n/// \n/// This interface serves as the foundation for all message types in the JSON-RPC 2.0 protocol\n/// used by MCP, including requests, responses, notifications, and errors. JSON-RPC is a stateless,\n/// lightweight remote procedure call (RPC) protocol that uses JSON as its data format.\n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessage()\n {\n }\n\n /// \n /// Gets the JSON-RPC protocol version used.\n /// \n /// \n [JsonPropertyName(\"jsonrpc\")]\n public string JsonRpc { get; init; } = \"2.0\";\n\n /// \n /// Gets or sets the transport the was received on or should be sent over.\n /// \n /// \n /// This is used to support the Streamable HTTP transport where the specification states that the server\n /// SHOULD include JSON-RPC responses in the HTTP response body for the POST request containing\n /// the corresponding JSON-RPC request. It may be for other transports.\n /// \n [JsonIgnore]\n public ITransport? RelatedTransport { get; set; }\n\n /// \n /// Gets or sets the that should be used to run any handlers\n /// \n /// \n /// This is used to support the Streamable HTTP transport in its default stateful mode. In this mode,\n /// the outlives the initial HTTP request context it was created on, and new\n /// JSON-RPC messages can originate from future HTTP requests. This allows the transport to flow the\n /// context with the JSON-RPC message. This is particularly useful for enabling IHttpContextAccessor\n /// in tool calls.\n /// \n [JsonIgnore]\n public ExecutionContext? ExecutionContext { get; set; }\n\n /// \n /// Provides a for messages,\n /// handling polymorphic deserialization of different message types.\n /// \n /// \n /// \n /// This converter is responsible for correctly deserializing JSON-RPC messages into their appropriate\n /// concrete types based on the message structure. It analyzes the JSON payload and determines if it\n /// represents a request, notification, successful response, or error response.\n /// \n /// \n /// The type determination rules follow the JSON-RPC 2.0 specification:\n /// \n /// Messages with \"method\" and \"id\" properties are deserialized as .\n /// Messages with \"method\" but no \"id\" property are deserialized as .\n /// Messages with \"id\" and \"result\" properties are deserialized as .\n /// Messages with \"id\" and \"error\" properties are deserialized as .\n /// \n /// \n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override JsonRpcMessage? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException(\"Expected StartObject token\");\n }\n\n using var doc = JsonDocument.ParseValue(ref reader);\n var root = doc.RootElement;\n\n // All JSON-RPC messages must have a jsonrpc property with value \"2.0\"\n if (!root.TryGetProperty(\"jsonrpc\", out var versionProperty) ||\n versionProperty.GetString() != \"2.0\")\n {\n throw new JsonException(\"Invalid or missing jsonrpc version\");\n }\n\n // Determine the message type based on the presence of id, method, and error properties\n bool hasId = root.TryGetProperty(\"id\", out _);\n bool hasMethod = root.TryGetProperty(\"method\", out _);\n bool hasError = root.TryGetProperty(\"error\", out _);\n\n var rawText = root.GetRawText();\n\n // Messages with an id but no method are responses\n if (hasId && !hasMethod)\n {\n // Messages with an error property are error responses\n if (hasError)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with a result property are success responses\n if (root.TryGetProperty(\"result\", out _))\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Response must have either result or error\");\n }\n\n // Messages with a method but no id are notifications\n if (hasMethod && !hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with both method and id are requests\n if (hasMethod && hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Invalid JSON-RPC message format\");\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, JsonRpcMessage value, JsonSerializerOptions options)\n {\n switch (value)\n {\n case JsonRpcRequest request:\n JsonSerializer.Serialize(writer, request, options.GetTypeInfo());\n break;\n case JsonRpcNotification notification:\n JsonSerializer.Serialize(writer, notification, options.GetTypeInfo());\n break;\n case JsonRpcResponse response:\n JsonSerializer.Serialize(writer, response, options.GetTypeInfo());\n break;\n case JsonRpcError error:\n JsonSerializer.Serialize(writer, error, options.GetTypeInfo());\n break;\n default:\n throw new JsonException($\"Unknown JSON-RPC message type: {value.GetType()}\");\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/AIContentExtensions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\n#if !NET\nusing System.Runtime.InteropServices;\n#endif\nusing System.Text.Json;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for converting between Model Context Protocol (MCP) types and Microsoft.Extensions.AI types.\n/// \n/// \n/// This class serves as an adapter layer between Model Context Protocol (MCP) types and the model types\n/// from the Microsoft.Extensions.AI namespace.\n/// \npublic static class AIContentExtensions\n{\n /// \n /// Converts a to a object.\n /// \n /// The prompt message to convert.\n /// A object created from the prompt message.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries.\n /// \n public static ChatMessage ToChatMessage(this PromptMessage promptMessage)\n {\n Throw.IfNull(promptMessage);\n\n AIContent? content = ToAIContent(promptMessage.Content);\n\n return new()\n {\n RawRepresentation = promptMessage,\n Role = promptMessage.Role == Role.User ? ChatRole.User : ChatRole.Assistant,\n Contents = content is not null ? [content] : [],\n };\n }\n\n /// \n /// Converts a to a object.\n /// \n /// The tool result to convert.\n /// The identifier for the function call request that triggered the tool invocation.\n /// A object created from the tool result.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries. It produces a\n /// message containing a with result as a\n /// serialized .\n /// \n public static ChatMessage ToChatMessage(this CallToolResult result, string callId)\n {\n Throw.IfNull(result);\n Throw.IfNull(callId);\n\n return new(ChatRole.Tool, [new FunctionResultContent(callId, JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult))\n {\n RawRepresentation = result,\n }]);\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The prompt result containing messages to convert.\n /// A list of objects created from the prompt messages.\n /// \n /// This method transforms protocol-specific objects from a Model Context Protocol\n /// prompt result into standard objects that can be used with AI client libraries.\n /// \n public static IList ToChatMessages(this GetPromptResult promptResult)\n {\n Throw.IfNull(promptResult);\n\n return promptResult.Messages.Select(m => m.ToChatMessage()).ToList();\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The chat message to convert.\n /// A list of objects created from the chat message's contents.\n /// \n /// This method transforms standard objects used with AI client libraries into\n /// protocol-specific objects for the Model Context Protocol system.\n /// Only representable content items are processed.\n /// \n public static IList ToPromptMessages(this ChatMessage chatMessage)\n {\n Throw.IfNull(chatMessage);\n\n Role r = chatMessage.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n List messages = [];\n foreach (var content in chatMessage.Contents)\n {\n if (content is TextContent or DataContent)\n {\n messages.Add(new PromptMessage { Role = r, Content = content.ToContent() });\n }\n }\n\n return messages;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// \n /// The created . If the content can't be converted (such as when it's a resource link), is returned.\n /// \n /// \n /// This method converts Model Context Protocol content types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent? ToAIContent(this ContentBlock content)\n {\n Throw.IfNull(content);\n\n AIContent? ac = content switch\n {\n TextContentBlock textContent => new TextContent(textContent.Text),\n ImageContentBlock imageContent => new DataContent(Convert.FromBase64String(imageContent.Data), imageContent.MimeType),\n AudioContentBlock audioContent => new DataContent(Convert.FromBase64String(audioContent.Data), audioContent.MimeType),\n EmbeddedResourceBlock resourceContent => resourceContent.Resource.ToAIContent(),\n _ => null,\n };\n\n if (ac is not null)\n {\n ac.RawRepresentation = content;\n }\n\n return ac;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// The created .\n /// \n /// This method converts Model Context Protocol resource types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent ToAIContent(this ResourceContents content)\n {\n Throw.IfNull(content);\n\n AIContent ac = content switch\n {\n BlobResourceContents blobResource => new DataContent(Convert.FromBase64String(blobResource.Blob), blobResource.MimeType ?? \"application/octet-stream\"),\n TextResourceContents textResource => new TextContent(textResource.Text),\n _ => throw new NotSupportedException($\"Resource type '{content.GetType().Name}' is not supported.\")\n };\n\n (ac.AdditionalProperties ??= [])[\"uri\"] = content.Uri;\n ac.RawRepresentation = content;\n\n return ac;\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// The created instances.\n /// \n /// \n /// This method converts a collection of Model Context Protocol content objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple content items, such as\n /// when processing the contents of a message or response.\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic for text, images, audio, and resources.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent).OfType()];\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// A list of objects created from the resource contents.\n /// \n /// \n /// This method converts a collection of Model Context Protocol resource objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple resources, such as\n /// when processing the contents of a .\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic: text resources become objects and\n /// binary resources become objects.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent)];\n }\n\n internal static ContentBlock ToContent(this AIContent content) =>\n content switch\n {\n TextContent textContent => new TextContentBlock\n {\n Text = textContent.Text,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") => new ImageContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"audio\") => new AudioContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent => new EmbeddedResourceBlock\n {\n Resource = new BlobResourceContents\n {\n Blob = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n }\n },\n\n _ => new TextContentBlock\n {\n Text = JsonSerializer.Serialize(content, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))),\n }\n };\n}\n"], ["/csharp-sdk/samples/EverythingServer/SubscriptionMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\ninternal class SubscriptionMessageSender(IMcpServer server, HashSet subscriptions) : BackgroundService\n{\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n foreach (var uri in subscriptions)\n {\n await server.SendNotificationAsync(\"notifications/resource/updated\",\n new\n {\n Uri = uri,\n }, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(5000, stoppingToken);\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring HTTP MCP servers via dependency injection.\n/// \npublic static class HttpMcpServerBuilderExtensions\n{\n /// \n /// Adds the services necessary for \n /// to handle MCP requests and sessions using the MCP Streamable HTTP transport. For more information on configuring the underlying HTTP server\n /// to control things like port binding custom TLS certificates, see the Minimal APIs quick reference.\n /// \n /// The builder instance.\n /// Configures options for the Streamable HTTP transport. This allows configuring per-session\n /// and running logic before and after a session.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithHttpTransport(this IMcpServerBuilder builder, Action? configureOptions = null)\n {\n ArgumentNullException.ThrowIfNull(builder);\n\n builder.Services.TryAddSingleton();\n builder.Services.TryAddSingleton();\n builder.Services.AddHostedService();\n builder.Services.AddDataProtection();\n\n if (configureOptions is not null)\n {\n builder.Services.Configure(configureOptions);\n }\n\n return builder;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestId.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC request identifier, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct RequestId : IEquatable\n{\n /// The id, either a string or a boxed long or null.\n private readonly object? _id;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(string value)\n {\n Throw.IfNull(value);\n _id = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(long value)\n {\n // Box the long. Request IDs are almost always strings in practice, so this should be rare.\n _id = value;\n }\n\n /// Gets the underlying object for this id.\n /// This will either be a , a boxed , or .\n public object? Id => _id;\n\n /// \n public override string ToString() =>\n _id is string stringValue ? stringValue :\n _id is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n string.Empty;\n\n /// \n public bool Equals(RequestId other) => Equals(_id, other._id);\n\n /// \n public override bool Equals(object? obj) => obj is RequestId other && Equals(other);\n\n /// \n public override int GetHashCode() => _id?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(RequestId left, RequestId right) => left.Equals(right);\n\n /// \n public static bool operator !=(RequestId left, RequestId right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override RequestId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"requestId must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, RequestId value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._id)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ProgressToken.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a progress token, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct ProgressToken : IEquatable\n{\n /// The token, either a string or a boxed long or null.\n private readonly object? _token;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(string value)\n {\n Throw.IfNull(value);\n _token = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(long value)\n {\n // Box the long. Progress tokens are almost always strings in practice, so this should be rare.\n _token = value;\n }\n\n /// Gets the underlying object for this token.\n /// This will either be a , a boxed , or .\n public object? Token => _token;\n\n /// \n public override string? ToString() =>\n _token is string stringValue ? stringValue :\n _token is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n null;\n\n /// \n public bool Equals(ProgressToken other) => Equals(_token, other._token);\n\n /// \n public override bool Equals(object? obj) => obj is ProgressToken other && Equals(other);\n\n /// \n public override int GetHashCode() => _token?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(ProgressToken left, ProgressToken right) => left.Equals(right);\n\n /// \n public static bool operator !=(ProgressToken left, ProgressToken right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"progressToken must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressToken value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._token)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.ObjectModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides an that calls a tool via an .\n/// \n/// \n/// \n/// The class encapsulates an along with a description of \n/// a tool available via that client, allowing it to be invoked as an . This enables integration\n/// with AI models that support function calling capabilities.\n/// \n/// \n/// Tools retrieved from an MCP server can be customized for model presentation using methods like\n/// and without changing the underlying tool functionality.\n/// \n/// \n/// Typically, you would get instances of this class by calling the \n/// or extension methods on an instance.\n/// \n/// \npublic sealed class McpClientTool : AIFunction\n{\n /// Additional properties exposed from tools.\n private static readonly ReadOnlyDictionary s_additionalProperties =\n new(new Dictionary()\n {\n [\"Strict\"] = false, // some MCP schemas may not meet \"strict\" requirements\n });\n\n private readonly IMcpClient _client;\n private readonly string _name;\n private readonly string _description;\n private readonly IProgress? _progress;\n\n internal McpClientTool(\n IMcpClient client,\n Tool tool,\n JsonSerializerOptions serializerOptions,\n string? name = null,\n string? description = null,\n IProgress? progress = null)\n {\n _client = client;\n ProtocolTool = tool;\n JsonSerializerOptions = serializerOptions;\n _name = name ?? tool.Name;\n _description = description ?? tool.Description ?? string.Empty;\n _progress = progress;\n }\n\n /// \n /// Gets the protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the tool,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// It contains the original metadata about the tool as provided by the server, including its\n /// name, description, and schema information before any customizations applied through methods\n /// like or .\n /// \n public Tool ProtocolTool { get; }\n\n /// \n public override string Name => _name;\n\n /// Gets the tool's title.\n public string? Title => ProtocolTool.Title ?? ProtocolTool.Annotations?.Title;\n\n /// \n public override string Description => _description;\n\n /// \n public override JsonElement JsonSchema => ProtocolTool.InputSchema;\n\n /// \n public override JsonElement? ReturnJsonSchema => ProtocolTool.OutputSchema;\n\n /// \n public override JsonSerializerOptions JsonSerializerOptions { get; }\n\n /// \n public override IReadOnlyDictionary AdditionalProperties => s_additionalProperties;\n\n /// \n protected async override ValueTask InvokeCoreAsync(\n AIFunctionArguments arguments, CancellationToken cancellationToken)\n {\n CallToolResult result = await CallAsync(arguments, _progress, JsonSerializerOptions, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult);\n }\n\n /// \n /// Invokes the tool on the server.\n /// \n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// \n /// The base method is overridden to invoke this method.\n /// The only difference in behavior is will serialize the resulting \"/>\n /// such that the returned is a containing the serialized .\n /// This method is intended to be called directly by user code, whereas the base \n /// is intended to be used polymorphically via the base class, typically as part of an operation.\n /// \n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// var result = await tool.CallAsync(\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public ValueTask CallAsync(\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default) =>\n _client.CallToolAsync(ProtocolTool.Name, arguments, progress, serializerOptions, cancellationToken);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified name from its property.\n /// \n /// The model-facing name to give the tool.\n /// A new instance of with the provided name.\n /// \n /// \n /// This is useful for optimizing the tool name for specific models or for prefixing the tool name \n /// with a namespace to avoid conflicts.\n /// \n /// \n /// Changing the name can help with:\n /// \n /// \n /// Making the tool name more intuitive for the model\n /// Preventing name collisions when using tools from multiple sources\n /// Creating specialized versions of a general tool for specific contexts\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool name, so no mapping is required on the server side. This new name only affects\n /// the value returned from this instance's .\n /// \n /// \n public McpClientTool WithName(string name) =>\n new(_client, ProtocolTool, JsonSerializerOptions, name, _description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified description from its property.\n /// \n /// The description to give the tool.\n /// \n /// \n /// Changing the description can help the model better understand the tool's purpose or provide more\n /// context about how the tool should be used. This is particularly useful when:\n /// \n /// \n /// The original description is too technical or lacks clarity for the model\n /// You want to add example usage scenarios to improve the model's understanding\n /// You need to tailor the tool's description for specific model requirements\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool description, so no mapping is required on the server side. This new description only affects\n /// the value returned from this instance's .\n /// \n /// \n /// A new instance of with the provided description.\n public McpClientTool WithDescription(string description) =>\n new(_client, ProtocolTool, JsonSerializerOptions, _name, description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to report progress via the specified .\n /// \n /// The to which progress notifications should be reported.\n /// \n /// \n /// Adding an to the tool does not impact how it is reported to any AI model.\n /// Rather, when the tool is invoked, the request to the MCP server will include a unique progress token,\n /// and any progress notifications issued by the server with that progress token while the operation is in\n /// flight will be reported to the instance.\n /// \n /// \n /// Only one can be specified at a time. Calling again\n /// will overwrite any previously specified progress instance.\n /// \n /// \n /// A new instance of , configured with the provided progress instance.\n public McpClientTool WithProgress(IProgress progress)\n {\n Throw.IfNull(progress);\n\n return new McpClientTool(_client, ProtocolTool, JsonSerializerOptions, _name, _description, progress);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResourceTemplate.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource template that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource template defined on an MCP server. It allows\n/// retrieving the resource template's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResourceTemplate\n{\n private readonly IMcpClient _client;\n\n internal McpClientResourceTemplate(IMcpClient client, ResourceTemplate resourceTemplate)\n {\n _client = client;\n ProtocolResourceTemplate = resourceTemplate;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource template,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the URI template of the resource template.\n public string UriTemplate => ProtocolResourceTemplate.UriTemplate;\n\n /// Gets the name of the resource template.\n public string Name => ProtocolResourceTemplate.Name;\n\n /// Gets the title of the resource template.\n public string? Title => ProtocolResourceTemplate.Title;\n\n /// Gets a description of the resource template.\n public string? Description => ProtocolResourceTemplate.Description;\n\n /// Gets a media (MIME) type of the resource template.\n public string? MimeType => ProtocolResourceTemplate.MimeType;\n\n /// \n /// Gets this resource template's content by formatting a URI from the template and supplied arguments\n /// and sending a request to the server.\n /// \n /// A dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource template's result with content and messages.\n public ValueTask ReadAsync(\n IReadOnlyDictionary arguments,\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(UriTemplate, arguments, cancellationToken);\n}"], ["/csharp-sdk/src/ModelContextProtocol/McpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring MCP servers via dependency injection.\n/// \npublic static partial class McpServerBuilderExtensions\n{\n #region WithTools\n private const string WithToolsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithTools)} and {nameof(WithToolsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithTools)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The tool type.\n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n public static IMcpServerBuilder WithTools<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TToolType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var toolMethod in typeof(TToolType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, static r => CreateTarget(r.Services, typeof(TToolType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable tools)\n {\n Throw.IfNull(builder);\n Throw.IfNull(tools);\n\n foreach (var tool in tools)\n {\n if (tool is not null)\n {\n builder.Services.AddSingleton(tool);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with -attributed methods to add as tools to the server.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable toolTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(toolTypes);\n\n foreach (var toolType in toolTypes)\n {\n if (toolType is not null)\n {\n foreach (var toolMethod in toolType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services , SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, r => CreateTarget(r.Services, toolType), new() { Services = services , SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as tools to the server.\n /// \n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the tool.\n /// \n /// \n /// Tools registered through this method can be discovered by clients using the list_tools request\n /// and invoked using the call_tool request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithToolsFromAssembly(this IMcpServerBuilder builder, Assembly? toolAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n toolAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithTools(\n from t in toolAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithPrompts\n private const string WithPromptsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithPrompts)} and {nameof(WithPromptsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithPrompts)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The prompt type.\n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n public static IMcpServerBuilder WithPrompts<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TPromptType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var promptMethod in typeof(TPromptType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, static r => CreateTarget(r.Services, typeof(TPromptType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable prompts)\n {\n Throw.IfNull(builder);\n Throw.IfNull(prompts);\n\n foreach (var prompt in prompts)\n {\n if (prompt is not null)\n {\n builder.Services.AddSingleton(prompt);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as prompts to the server.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable promptTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(promptTypes);\n\n foreach (var promptType in promptTypes)\n {\n if (promptType is not null)\n {\n foreach (var promptMethod in promptType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, r => CreateTarget(r.Services, promptType), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as prompts to the server.\n /// \n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the prompt.\n /// \n /// \n /// Prompts registered through this method can be discovered by clients using the list_prompts request\n /// and invoked using the call_prompt request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPromptsFromAssembly(this IMcpServerBuilder builder, Assembly? promptAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n promptAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithPrompts(\n from t in promptAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithResources\n private const string WithResourcesRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithResources)} and {nameof(WithResourcesFromAssembly)} methods require dynamic lookup of member metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithResources)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The resource type.\n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the members are attributed as , and adds an \n /// instance for each. For instance members, an instance will be constructed for each invocation of the resource.\n /// \n public static IMcpServerBuilder WithResources<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TResourceType>(\n this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n foreach (var resourceTemplateMethod in typeof(TResourceType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, static r => CreateTarget(r.Services, typeof(TResourceType)), new() { Services = services })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplates)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplates);\n\n foreach (var resourceTemplate in resourceTemplates)\n {\n if (resourceTemplate is not null)\n {\n builder.Services.AddSingleton(resourceTemplate);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as resources to the server.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the resource.\n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplateTypes)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplateTypes);\n\n foreach (var resourceTemplateType in resourceTemplateTypes)\n {\n if (resourceTemplateType is not null)\n {\n foreach (var resourceTemplateMethod in resourceTemplateType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, r => CreateTarget(r.Services, resourceTemplateType), new() { Services = services })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as resources to the server.\n /// \n /// The builder instance.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all members within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance members. For instance members, a new instance\n /// of the containing class will be constructed for each invocation of the resource.\n /// \n /// \n /// Resource templates registered through this method can be discovered by clients using the list_resourceTemplates request\n /// and invoked using the read_resource request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResourcesFromAssembly(this IMcpServerBuilder builder, Assembly? resourceAssembly = null)\n {\n Throw.IfNull(builder);\n\n resourceAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithResources(\n from t in resourceAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t);\n }\n #endregion\n\n #region Handlers\n /// \n /// Configures a handler for listing resource templates available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource template list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is responsible for providing clients with information about available resource templates\n /// that can be used to construct resource URIs.\n /// \n /// \n /// Resource templates describe the structure of resource URIs that the server can handle. They include\n /// URI templates (according to RFC 6570) that clients can use to construct valid resource URIs.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// resource system where templates define the URI patterns and the read handler provides the actual content.\n /// \n /// \n public static IMcpServerBuilder WithListResourceTemplatesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourceTemplatesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list tools requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available tools. It should return all tools\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// tool collections.\n /// \n /// \n /// When tools are also defined using collection, both sets of tools\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// tools and dynamically generated tools.\n /// \n /// \n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and \n /// executes them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListToolsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListToolsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for calling tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes tool calls.\n /// The builder provided in .\n /// is .\n /// \n /// The call tool handler is responsible for executing custom tools and returning their results to clients.\n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and this handler executes them.\n /// \n public static IMcpServerBuilder WithCallToolHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CallToolHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing prompts available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list prompts requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available prompts. It should return all prompts\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// prompt collections.\n /// \n /// \n /// When prompts are also defined using collection, both sets of prompts\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// prompts and dynamically generated prompts.\n /// \n /// \n /// This method is typically paired with to provide a complete prompts implementation,\n /// where advertises available prompts and \n /// produces them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListPromptsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListPromptsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for getting a prompt available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes prompt requests.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithGetPromptHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.GetPromptHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing resources available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where this handler advertises available resources and the read handler provides their content when requested.\n /// \n /// \n public static IMcpServerBuilder WithListResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for reading a resource available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource read requests.\n /// The builder provided in .\n /// is .\n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where the list handler advertises available resources and the read handler provides their content when requested.\n /// \n public static IMcpServerBuilder WithReadResourceHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ReadResourceHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for auto-completion suggestions for prompt arguments or resource references available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes completion requests.\n /// The builder provided in .\n /// is .\n /// \n /// The completion handler is invoked when clients request suggestions for argument values.\n /// This enables auto-complete functionality for both prompt arguments and resource references.\n /// \n public static IMcpServerBuilder WithCompleteHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CompleteHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource subscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource subscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The subscribe handler is responsible for registering client interest in specific resources. When a resource\n /// changes, the server can notify all subscribed clients about the change.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. Resource subscriptions allow clients to maintain up-to-date information without\n /// needing to poll resources constantly.\n /// \n /// \n /// After registering a subscription, it's the server's responsibility to track which client is subscribed to which\n /// resources and to send appropriate notifications through the connection when resources change.\n /// \n /// \n public static IMcpServerBuilder WithSubscribeToResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SubscribeToResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource unsubscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource unsubscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The unsubscribe handler is responsible for removing client interest in specific resources. When a client\n /// no longer needs to receive notifications about resource changes, it can send an unsubscribe request.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. The unsubscribe operation is idempotent, meaning it can be called multiple\n /// times for the same resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// After removing a subscription, the server should stop sending notifications to the client about changes\n /// to the specified resource.\n /// \n /// \n public static IMcpServerBuilder WithUnsubscribeFromResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.UnsubscribeFromResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for processing logging level change requests from clients.\n /// \n /// The server builder instance.\n /// The handler that processes requests to change the logging level.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// When a client sends a logging/setLevel request, this handler will be invoked to process\n /// the requested level change. The server typically adjusts its internal logging level threshold\n /// and may begin sending log messages at or above the specified level to the client.\n /// \n /// \n /// Regardless of whether a handler is provided, an should itself handle\n /// such notifications by updating its property to return the\n /// most recently set level.\n /// \n /// \n public static IMcpServerBuilder WithSetLoggingLevelHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SetLoggingLevelHandler = handler);\n return builder;\n }\n #endregion\n\n #region Transports\n /// \n /// Adds a server transport that uses standard input (stdin) and standard output (stdout) for communication.\n /// \n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method configures the server to communicate using the standard input and output streams,\n /// which is commonly used when the Model Context Protocol server is launched locally by a client process.\n /// \n /// \n /// When using this transport, the server runs as a single-session service that exits when the\n /// stdin stream is closed. This makes it suitable for scenarios where the server should terminate\n /// when the parent process disconnects.\n /// \n /// \n /// is .\n public static IMcpServerBuilder WithStdioServerTransport(this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(sp =>\n {\n var serverOptions = sp.GetRequiredService>();\n var loggerFactory = sp.GetService();\n return new StdioServerTransport(serverOptions.Value, loggerFactory);\n });\n\n return builder;\n }\n\n /// \n /// Adds a server transport that uses the specified input and output streams for communication.\n /// \n /// The builder instance.\n /// The input to use as standard input.\n /// The output to use as standard output.\n /// The builder provided in .\n /// is .\n /// is .\n /// is .\n public static IMcpServerBuilder WithStreamServerTransport(\n this IMcpServerBuilder builder,\n Stream inputStream,\n Stream outputStream)\n {\n Throw.IfNull(builder);\n Throw.IfNull(inputStream);\n Throw.IfNull(outputStream);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(new StreamServerTransport(inputStream, outputStream));\n\n return builder;\n }\n\n private static void AddSingleSessionServerDependencies(IServiceCollection services)\n {\n services.AddHostedService();\n services.TryAddSingleton(services =>\n {\n ITransport serverTransport = services.GetRequiredService();\n IOptions options = services.GetRequiredService>();\n ILoggerFactory? loggerFactory = services.GetService();\n return McpServerFactory.Create(serverTransport, options.Value, loggerFactory, services);\n });\n }\n #endregion\n\n #region Helpers\n /// Creates an instance of the target object.\n private static object CreateTarget(\n IServiceProvider? services,\n [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) =>\n services is not null ? ActivatorUtilities.CreateInstance(services, type) :\n Activator.CreateInstance(type)!;\n #endregion\n}\n"], ["/csharp-sdk/samples/ProtectedMCPClient/Program.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Text;\nusing System.Web;\n\nvar serverUrl = \"http://localhost:7071/\";\n\nConsole.WriteLine(\"Protected MCP Client\");\nConsole.WriteLine($\"Connecting to weather server at {serverUrl}...\");\nConsole.WriteLine();\n\n// We can customize a shared HttpClient with a custom handler if desired\nvar sharedHandler = new SocketsHttpHandler\n{\n PooledConnectionLifetime = TimeSpan.FromMinutes(2),\n PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1)\n};\nvar httpClient = new HttpClient(sharedHandler);\n\nvar consoleLoggerFactory = LoggerFactory.Create(builder =>\n{\n builder.AddConsole();\n});\n\nvar transport = new SseClientTransport(new()\n{\n Endpoint = new Uri(serverUrl),\n Name = \"Secure Weather Client\",\n OAuth = new()\n {\n ClientName = \"ProtectedMcpClient\",\n RedirectUri = new Uri(\"http://localhost:1179/callback\"),\n AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,\n }\n}, httpClient, consoleLoggerFactory);\n\nvar client = await McpClientFactory.CreateAsync(transport, loggerFactory: consoleLoggerFactory);\n\nvar tools = await client.ListToolsAsync();\nif (tools.Count == 0)\n{\n Console.WriteLine(\"No tools available on the server.\");\n return;\n}\n\nConsole.WriteLine($\"Found {tools.Count} tools on the server.\");\nConsole.WriteLine();\n\nif (tools.Any(t => t.Name == \"get_alerts\"))\n{\n Console.WriteLine(\"Calling get_alerts tool...\");\n\n var result = await client.CallToolAsync(\n \"get_alerts\",\n new Dictionary { { \"state\", \"WA\" } }\n );\n\n Console.WriteLine(\"Result: \" + ((TextContentBlock)result.Content[0]).Text);\n Console.WriteLine();\n}\n\n/// Handles the OAuth authorization URL by starting a local HTTP server and opening a browser.\n/// This implementation demonstrates how SDK consumers can provide their own authorization flow.\n/// \n/// The authorization URL to open in the browser.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// The authorization code extracted from the callback, or null if the operation failed.\nstatic async Task HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken)\n{\n Console.WriteLine(\"Starting OAuth authorization flow...\");\n Console.WriteLine($\"Opening browser to: {authorizationUrl}\");\n\n var listenerPrefix = redirectUri.GetLeftPart(UriPartial.Authority);\n if (!listenerPrefix.EndsWith(\"/\")) listenerPrefix += \"/\";\n\n using var listener = new HttpListener();\n listener.Prefixes.Add(listenerPrefix);\n\n try\n {\n listener.Start();\n Console.WriteLine($\"Listening for OAuth callback on: {listenerPrefix}\");\n\n OpenBrowser(authorizationUrl);\n\n var context = await listener.GetContextAsync();\n var query = HttpUtility.ParseQueryString(context.Request.Url?.Query ?? string.Empty);\n var code = query[\"code\"];\n var error = query[\"error\"];\n\n string responseHtml = \"

Authentication complete

You can close this window now.

\";\n byte[] buffer = Encoding.UTF8.GetBytes(responseHtml);\n context.Response.ContentLength64 = buffer.Length;\n context.Response.ContentType = \"text/html\";\n context.Response.OutputStream.Write(buffer, 0, buffer.Length);\n context.Response.Close();\n\n if (!string.IsNullOrEmpty(error))\n {\n Console.WriteLine($\"Auth error: {error}\");\n return null;\n }\n\n if (string.IsNullOrEmpty(code))\n {\n Console.WriteLine(\"No authorization code received\");\n return null;\n }\n\n Console.WriteLine(\"Authorization code received successfully.\");\n return code;\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error getting auth code: {ex.Message}\");\n return null;\n }\n finally\n {\n if (listener.IsListening) listener.Stop();\n }\n}\n\n/// \n/// Opens the specified URL in the default browser.\n/// \n/// The URL to open.\nstatic void OpenBrowser(Uri url)\n{\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = url.ToString(),\n UseShellExecute = true\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error opening browser. {ex.Message}\");\n Console.WriteLine($\"Please manually open this URL: {url}\");\n }\n}"], ["/csharp-sdk/src/Common/CancellableStreamReader/ValueStringBuilder.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.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n#nullable enable\n\nnamespace System.Text\n{\n internal ref partial struct ValueStringBuilder\n {\n private char[]? _arrayToReturnToPool;\n private Span _chars;\n private int _pos;\n\n public ValueStringBuilder(Span initialBuffer)\n {\n _arrayToReturnToPool = null;\n _chars = initialBuffer;\n _pos = 0;\n }\n\n public ValueStringBuilder(int initialCapacity)\n {\n _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity);\n _chars = _arrayToReturnToPool;\n _pos = 0;\n }\n\n public int Length\n {\n get => _pos;\n set\n {\n Debug.Assert(value >= 0);\n Debug.Assert(value <= _chars.Length);\n _pos = value;\n }\n }\n\n public int Capacity => _chars.Length;\n\n public void EnsureCapacity(int capacity)\n {\n // This is not expected to be called this with negative capacity\n Debug.Assert(capacity >= 0);\n\n // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.\n if ((uint)capacity > (uint)_chars.Length)\n Grow(capacity - _pos);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// Does not ensure there is a null char after \n /// This overload is pattern matched in the C# 7.3+ compiler so you can omit\n /// the explicit method call, and write eg \"fixed (char* c = builder)\"\n /// \n public ref char GetPinnableReference()\n {\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// \n /// Ensures that the builder has a null char after \n public ref char GetPinnableReference(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n public ref char this[int index]\n {\n get\n {\n Debug.Assert(index < _pos);\n return ref _chars[index];\n }\n }\n\n public override string ToString()\n {\n string s = _chars.Slice(0, _pos).ToString();\n Dispose();\n return s;\n }\n\n /// Returns the underlying storage of the builder.\n public Span RawChars => _chars;\n\n /// \n /// Returns a span around the contents of the builder.\n /// \n /// Ensures that the builder has a null char after \n public ReadOnlySpan AsSpan(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return _chars.Slice(0, _pos);\n }\n\n public ReadOnlySpan AsSpan() => _chars.Slice(0, _pos);\n public ReadOnlySpan AsSpan(int start) => _chars.Slice(start, _pos - start);\n public ReadOnlySpan AsSpan(int start, int length) => _chars.Slice(start, length);\n\n public bool TryCopyTo(Span destination, out int charsWritten)\n {\n if (_chars.Slice(0, _pos).TryCopyTo(destination))\n {\n charsWritten = _pos;\n Dispose();\n return true;\n }\n else\n {\n charsWritten = 0;\n Dispose();\n return false;\n }\n }\n\n public void Insert(int index, char value, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n _chars.Slice(index, count).Fill(value);\n _pos += count;\n }\n\n public void Insert(int index, string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int count = s.Length;\n\n if (_pos > (_chars.Length - count))\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(index));\n _pos += count;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(char c)\n {\n int pos = _pos;\n Span chars = _chars;\n if ((uint)pos < (uint)chars.Length)\n {\n chars[pos] = c;\n _pos = pos + 1;\n }\n else\n {\n GrowAndAppend(c);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int pos = _pos;\n if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.\n {\n _chars[pos] = s[0];\n _pos = pos + 1;\n }\n else\n {\n AppendSlow(s);\n }\n }\n\n private void AppendSlow(string s)\n {\n int pos = _pos;\n if (pos > _chars.Length - s.Length)\n {\n Grow(s.Length);\n }\n\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(pos));\n _pos += s.Length;\n }\n\n public void Append(char c, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n Span dst = _chars.Slice(_pos, count);\n for (int i = 0; i < dst.Length; i++)\n {\n dst[i] = c;\n }\n _pos += count;\n }\n\n public void Append(scoped ReadOnlySpan value)\n {\n int pos = _pos;\n if (pos > _chars.Length - value.Length)\n {\n Grow(value.Length);\n }\n\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public Span AppendSpan(int length)\n {\n int origPos = _pos;\n if (origPos > _chars.Length - length)\n {\n Grow(length);\n }\n\n _pos = origPos + length;\n return _chars.Slice(origPos, length);\n }\n\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowAndAppend(char c)\n {\n Grow(1);\n Append(c);\n }\n\n /// \n /// Resize the internal buffer either by doubling current buffer size or\n /// by adding to\n /// whichever is greater.\n /// \n /// \n /// Number of chars requested beyond current position.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void Grow(int additionalCapacityBeyondPos)\n {\n Debug.Assert(additionalCapacityBeyondPos > 0);\n Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, \"Grow called incorrectly, no resize is needed.\");\n\n const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength\n\n // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try\n // to double the size if possible, bounding the doubling to not go beyond the max array length.\n int newCapacity = (int)Math.Max(\n (uint)(_pos + additionalCapacityBeyondPos),\n Math.Min((uint)_chars.Length * 2, ArrayMaxLength));\n\n // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.\n // This could also go negative if the actual required length wraps around.\n char[] poolArray = ArrayPool.Shared.Rent(newCapacity);\n\n _chars.Slice(0, _pos).CopyTo(poolArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = poolArray;\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Dispose()\n {\n char[]? toReturn = _arrayToReturnToPool;\n this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n }\n}"], ["/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/samples/EverythingServer/Program.cs", "using EverythingServer;\nusing EverythingServer.Prompts;\nusing EverythingServer.Resources;\nusing EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Resources;\nusing OpenTelemetry.Trace;\n\nvar builder = Host.CreateApplicationBuilder(args);\nbuilder.Logging.AddConsole(consoleLogOptions =>\n{\n // Configure all logs to go to stderr\n consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nHashSet subscriptions = [];\nvar _minimumLoggingLevel = LoggingLevel.Debug;\n\nbuilder.Services\n .AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithPrompts()\n .WithPrompts()\n .WithResources()\n .WithSubscribeToResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n\n if (uri is not null)\n {\n subscriptions.Add(uri);\n\n await ctx.Server.SampleAsync([\n new ChatMessage(ChatRole.System, \"You are a helpful test server\"),\n new ChatMessage(ChatRole.User, $\"Resource {uri}, context: A new subscription was started\"),\n ],\n options: new ChatOptions\n {\n MaxOutputTokens = 100,\n Temperature = 0.7f,\n },\n cancellationToken: ct);\n }\n\n return new EmptyResult();\n })\n .WithUnsubscribeFromResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n if (uri is not null)\n {\n subscriptions.Remove(uri);\n }\n return new EmptyResult();\n })\n .WithCompleteHandler(async (ctx, ct) =>\n {\n var exampleCompletions = new Dictionary>\n {\n { \"style\", [\"casual\", \"formal\", \"technical\", \"friendly\"] },\n { \"temperature\", [\"0\", \"0.5\", \"0.7\", \"1.0\"] },\n { \"resourceId\", [\"1\", \"2\", \"3\", \"4\", \"5\"] }\n };\n\n if (ctx.Params is not { } @params)\n {\n throw new NotSupportedException($\"Params are required.\");\n }\n\n var @ref = @params.Ref;\n var argument = @params.Argument;\n\n if (@ref is ResourceTemplateReference rtr)\n {\n var resourceId = rtr.Uri?.Split(\"/\").Last();\n\n if (resourceId is null)\n {\n return new CompleteResult();\n }\n\n var values = exampleCompletions[\"resourceId\"].Where(id => id.StartsWith(argument.Value));\n\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n if (@ref is PromptReference pr)\n {\n if (!exampleCompletions.TryGetValue(argument.Name, out IEnumerable? value))\n {\n throw new NotSupportedException($\"Unknown argument name: {argument.Name}\");\n }\n\n var values = value.Where(value => value.StartsWith(argument.Value));\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n throw new NotSupportedException($\"Unknown reference type: {@ref.Type}\");\n })\n .WithSetLoggingLevelHandler(async (ctx, ct) =>\n {\n if (ctx.Params?.Level is null)\n {\n throw new McpException(\"Missing required argument 'level'\", McpErrorCode.InvalidParams);\n }\n\n _minimumLoggingLevel = ctx.Params.Level;\n\n await ctx.Server.SendNotificationAsync(\"notifications/message\", new\n {\n Level = \"debug\",\n Logger = \"test-server\",\n Data = $\"Logging level set to {_minimumLoggingLevel}\",\n }, cancellationToken: ct);\n\n return new EmptyResult();\n });\n\nResourceBuilder resource = ResourceBuilder.CreateDefault().AddService(\"everything-server\");\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithMetrics(b => b.AddMeter(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithLogging(b => b.SetResourceBuilder(resource))\n .UseOtlpExporter();\n\nbuilder.Services.AddSingleton(subscriptions);\nbuilder.Services.AddHostedService();\nbuilder.Services.AddHostedService();\n\nbuilder.Services.AddSingleton>(_ => () => _minimumLoggingLevel);\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource defined on an MCP server. It allows\n/// retrieving the resource's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResource\n{\n private readonly IMcpClient _client;\n\n internal McpClientResource(IMcpClient client, Resource resource)\n {\n _client = client;\n ProtocolResource = resource;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Resource ProtocolResource { get; }\n\n /// Gets the URI of the resource.\n public string Uri => ProtocolResource.Uri;\n\n /// Gets the name of the resource.\n public string Name => ProtocolResource.Name;\n\n /// Gets the title of the resource.\n public string? Title => ProtocolResource.Title;\n\n /// Gets a description of the resource.\n public string? Description => ProtocolResource.Description;\n\n /// Gets a media (MIME) type of the resource.\n public string? MimeType => ProtocolResource.MimeType;\n\n /// \n /// Gets this resource's content by sending a request to the server.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource's result with content and messages.\n /// \n /// \n /// This is a convenience method that internally calls .\n /// \n /// \n public ValueTask ReadAsync(\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(Uri, cancellationToken);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpJsonUtilities.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Authentication;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// Provides a collection of utility methods for working with JSON data in the context of MCP.\npublic static partial class McpJsonUtilities\n{\n /// \n /// Gets the singleton used as the default in JSON serialization operations.\n /// \n /// \n /// \n /// For Native AOT or applications disabling , this instance \n /// includes source generated contracts for all common exchange types contained in the ModelContextProtocol library.\n /// \n /// \n /// It additionally turns on the following settings:\n /// \n /// Enables defaults.\n /// Enables as the default ignore condition for properties.\n /// Enables as the default number handling for number types.\n /// \n /// \n /// \n public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();\n\n /// \n /// Creates default options to use for MCP-related serialization.\n /// \n /// The configured options.\n [UnconditionalSuppressMessage(\"ReflectionAnalysis\", \"IL3050:RequiresDynamicCode\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n [UnconditionalSuppressMessage(\"Trimming\", \"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n private static JsonSerializerOptions CreateDefaultOptions()\n {\n // Copy the configuration from the source generated context.\n JsonSerializerOptions options = new(JsonContext.Default.Options);\n\n // Chain with all supported types from MEAI.\n options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);\n\n // Add a converter for user-defined enums, if reflection is enabled by default.\n if (JsonSerializer.IsReflectionEnabledByDefault)\n {\n options.Converters.Add(new CustomizableJsonStringEnumConverter());\n }\n\n options.MakeReadOnly();\n return options;\n }\n\n internal static JsonTypeInfo GetTypeInfo(this JsonSerializerOptions options) =>\n (JsonTypeInfo)options.GetTypeInfo(typeof(T));\n\n internal static JsonElement DefaultMcpToolSchema { get; } = ParseJsonElement(\"\"\"{\"type\":\"object\"}\"\"\"u8);\n internal static object? AsObject(this JsonElement element) => element.ValueKind is JsonValueKind.Null ? null : element;\n\n internal static bool IsValidMcpToolSchema(JsonElement element)\n {\n if (element.ValueKind is not JsonValueKind.Object)\n {\n return false;\n }\n\n foreach (JsonProperty property in element.EnumerateObject())\n {\n if (property.NameEquals(\"type\"))\n {\n if (property.Value.ValueKind is not JsonValueKind.String ||\n !property.Value.ValueEquals(\"object\"))\n {\n return false;\n }\n\n return true; // No need to check other properties\n }\n }\n\n return false; // No type keyword found.\n }\n\n // Keep in sync with CreateDefaultOptions above.\n [JsonSourceGenerationOptions(JsonSerializerDefaults.Web,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n NumberHandling = JsonNumberHandling.AllowReadingFromString)]\n \n // JSON-RPC\n [JsonSerializable(typeof(JsonRpcMessage))]\n [JsonSerializable(typeof(JsonRpcMessage[]))]\n [JsonSerializable(typeof(JsonRpcRequest))]\n [JsonSerializable(typeof(JsonRpcNotification))]\n [JsonSerializable(typeof(JsonRpcResponse))]\n [JsonSerializable(typeof(JsonRpcError))]\n\n // MCP Notification Params\n [JsonSerializable(typeof(CancelledNotificationParams))]\n [JsonSerializable(typeof(InitializedNotificationParams))]\n [JsonSerializable(typeof(LoggingMessageNotificationParams))]\n [JsonSerializable(typeof(ProgressNotificationParams))]\n [JsonSerializable(typeof(PromptListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceUpdatedNotificationParams))]\n [JsonSerializable(typeof(RootsListChangedNotificationParams))]\n [JsonSerializable(typeof(ToolListChangedNotificationParams))]\n\n // MCP Request Params / Results\n [JsonSerializable(typeof(CallToolRequestParams))]\n [JsonSerializable(typeof(CallToolResult))]\n [JsonSerializable(typeof(CompleteRequestParams))]\n [JsonSerializable(typeof(CompleteResult))]\n [JsonSerializable(typeof(CreateMessageRequestParams))]\n [JsonSerializable(typeof(CreateMessageResult))]\n [JsonSerializable(typeof(ElicitRequestParams))]\n [JsonSerializable(typeof(ElicitResult))]\n [JsonSerializable(typeof(EmptyResult))]\n [JsonSerializable(typeof(GetPromptRequestParams))]\n [JsonSerializable(typeof(GetPromptResult))]\n [JsonSerializable(typeof(InitializeRequestParams))]\n [JsonSerializable(typeof(InitializeResult))]\n [JsonSerializable(typeof(ListPromptsRequestParams))]\n [JsonSerializable(typeof(ListPromptsResult))]\n [JsonSerializable(typeof(ListResourcesRequestParams))]\n [JsonSerializable(typeof(ListResourcesResult))]\n [JsonSerializable(typeof(ListResourceTemplatesRequestParams))]\n [JsonSerializable(typeof(ListResourceTemplatesResult))]\n [JsonSerializable(typeof(ListRootsRequestParams))]\n [JsonSerializable(typeof(ListRootsResult))]\n [JsonSerializable(typeof(ListToolsRequestParams))]\n [JsonSerializable(typeof(ListToolsResult))]\n [JsonSerializable(typeof(PingResult))]\n [JsonSerializable(typeof(ReadResourceRequestParams))]\n [JsonSerializable(typeof(ReadResourceResult))]\n [JsonSerializable(typeof(SetLevelRequestParams))]\n [JsonSerializable(typeof(SubscribeRequestParams))]\n [JsonSerializable(typeof(UnsubscribeRequestParams))]\n\n // MCP Content\n [JsonSerializable(typeof(ContentBlock))]\n [JsonSerializable(typeof(TextContentBlock))]\n [JsonSerializable(typeof(ImageContentBlock))]\n [JsonSerializable(typeof(AudioContentBlock))]\n [JsonSerializable(typeof(EmbeddedResourceBlock))]\n [JsonSerializable(typeof(ResourceLinkBlock))]\n [JsonSerializable(typeof(PromptReference))]\n [JsonSerializable(typeof(ResourceTemplateReference))]\n [JsonSerializable(typeof(BlobResourceContents))]\n [JsonSerializable(typeof(TextResourceContents))]\n\n // Other MCP Types\n [JsonSerializable(typeof(IReadOnlyDictionary))]\n [JsonSerializable(typeof(ProgressToken))]\n\n [JsonSerializable(typeof(ProtectedResourceMetadata))]\n [JsonSerializable(typeof(AuthorizationServerMetadata))]\n [JsonSerializable(typeof(TokenContainer))]\n [JsonSerializable(typeof(DynamicClientRegistrationRequest))]\n [JsonSerializable(typeof(DynamicClientRegistrationResponse))]\n\n // Primitive types for use in consuming AIFunctions\n [JsonSerializable(typeof(string))]\n [JsonSerializable(typeof(byte))]\n [JsonSerializable(typeof(byte?))]\n [JsonSerializable(typeof(sbyte))]\n [JsonSerializable(typeof(sbyte?))]\n [JsonSerializable(typeof(ushort))]\n [JsonSerializable(typeof(ushort?))]\n [JsonSerializable(typeof(short))]\n [JsonSerializable(typeof(short?))]\n [JsonSerializable(typeof(uint))]\n [JsonSerializable(typeof(uint?))]\n [JsonSerializable(typeof(int))]\n [JsonSerializable(typeof(int?))]\n [JsonSerializable(typeof(ulong))]\n [JsonSerializable(typeof(ulong?))]\n [JsonSerializable(typeof(long))]\n [JsonSerializable(typeof(long?))]\n [JsonSerializable(typeof(nuint))]\n [JsonSerializable(typeof(nuint?))]\n [JsonSerializable(typeof(nint))]\n [JsonSerializable(typeof(nint?))]\n [JsonSerializable(typeof(bool))]\n [JsonSerializable(typeof(bool?))]\n [JsonSerializable(typeof(char))]\n [JsonSerializable(typeof(char?))]\n [JsonSerializable(typeof(float))]\n [JsonSerializable(typeof(float?))]\n [JsonSerializable(typeof(double))]\n [JsonSerializable(typeof(double?))]\n [JsonSerializable(typeof(decimal))]\n [JsonSerializable(typeof(decimal?))]\n [JsonSerializable(typeof(Guid))]\n [JsonSerializable(typeof(Guid?))]\n [JsonSerializable(typeof(Uri))]\n [JsonSerializable(typeof(Version))]\n [JsonSerializable(typeof(TimeSpan))]\n [JsonSerializable(typeof(TimeSpan?))]\n [JsonSerializable(typeof(DateTime))]\n [JsonSerializable(typeof(DateTime?))]\n [JsonSerializable(typeof(DateTimeOffset))]\n [JsonSerializable(typeof(DateTimeOffset?))]\n#if NET\n [JsonSerializable(typeof(DateOnly))]\n [JsonSerializable(typeof(DateOnly?))]\n [JsonSerializable(typeof(TimeOnly))]\n [JsonSerializable(typeof(TimeOnly?))]\n [JsonSerializable(typeof(Half))]\n [JsonSerializable(typeof(Half?))]\n [JsonSerializable(typeof(Int128))]\n [JsonSerializable(typeof(Int128?))]\n [JsonSerializable(typeof(UInt128))]\n [JsonSerializable(typeof(UInt128?))]\n#endif\n\n [ExcludeFromCodeCoverage]\n internal sealed partial class JsonContext : JsonSerializerContext;\n\n private static JsonElement ParseJsonElement(ReadOnlySpan utf8Json)\n {\n Utf8JsonReader reader = new(utf8Json);\n return JsonElement.ParseValue(ref reader);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/McpEndpointRouteBuilderExtensions.cs", "using Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Metadata;\nusing Microsoft.AspNetCore.Routing;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.AspNetCore.Builder;\n\n/// \n/// Provides extension methods for to add MCP endpoints.\n/// \npublic static class McpEndpointRouteBuilderExtensions\n{\n /// \n /// Sets up endpoints for handling MCP Streamable HTTP transport.\n /// See the 2025-06-18 protocol specification for details about the Streamable HTTP transport.\n /// Also maps legacy SSE endpoints for backward compatibility at the path \"/sse\" and \"/message\". the 2024-11-05 protocol specification for details about the HTTP with SSE transport.\n /// \n /// The web application to attach MCP HTTP endpoints.\n /// The route pattern prefix to map to.\n /// Returns a builder for configuring additional endpoint conventions like authorization policies.\n public static IEndpointConventionBuilder MapMcp(this IEndpointRouteBuilder endpoints, [StringSyntax(\"Route\")] string pattern = \"\")\n {\n var streamableHttpHandler = endpoints.ServiceProvider.GetService() ??\n throw new InvalidOperationException(\"You must call WithHttpTransport(). Unable to find required services. Call builder.Services.AddMcpServer().WithHttpTransport() in application startup code.\");\n\n var mcpGroup = endpoints.MapGroup(pattern);\n var streamableHttpGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP Streamable HTTP | {b.DisplayName}\")\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status404NotFound, typeof(JsonRpcError), contentTypes: [\"application/json\"]));\n\n streamableHttpGroup.MapPost(\"\", streamableHttpHandler.HandlePostRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n\n if (!streamableHttpHandler.HttpServerTransportOptions.Stateless)\n {\n // The GET and DELETE endpoints are not mapped in Stateless mode since there's no way to send unsolicited messages\n // for the GET to handle, and there is no server-side state for the DELETE to clean up.\n streamableHttpGroup.MapGet(\"\", streamableHttpHandler.HandleGetRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n streamableHttpGroup.MapDelete(\"\", streamableHttpHandler.HandleDeleteRequestAsync);\n\n // Map legacy HTTP with SSE endpoints only if not in Stateless mode, because we cannot guarantee the /message requests\n // will be handled by the same process as the /sse request.\n var sseHandler = endpoints.ServiceProvider.GetRequiredService();\n var sseGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP HTTP with SSE | {b.DisplayName}\");\n\n sseGroup.MapGet(\"/sse\", sseHandler.HandleSseRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n sseGroup.MapPost(\"/message\", sseHandler.HandleMessageRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n }\n\n return mcpGroup;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Diagnostics.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\n\nnamespace ModelContextProtocol;\n\ninternal static class Diagnostics\n{\n internal static ActivitySource ActivitySource { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Meter Meter { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Histogram CreateDurationHistogram(string name, string description, bool longBuckets) =>\n Meter.CreateHistogram(name, \"s\", description\n#if NET9_0_OR_GREATER\n , advice: longBuckets ? LongSecondsBucketBoundaries : ShortSecondsBucketBoundaries\n#endif\n );\n\n#if NET9_0_OR_GREATER\n /// \n /// Follows boundaries from http.server.request.duration/http.client.request.duration\n /// \n private static InstrumentAdvice ShortSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n };\n\n /// \n /// Not based on a standard. Larger bucket sizes for longer lasting operations, e.g. HTTP connection duration.\n /// See https://github.com/open-telemetry/semantic-conventions/issues/336\n /// \n private static InstrumentAdvice LongSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300],\n };\n#endif\n\n internal static ActivityContext ExtractActivityContext(this DistributedContextPropagator propagator, JsonRpcMessage message)\n {\n propagator.ExtractTraceIdAndState(message, ExtractContext, out var traceparent, out var tracestate);\n ActivityContext.TryParse(traceparent, tracestate, true, out var activityContext);\n return activityContext;\n }\n\n private static void ExtractContext(object? message, string fieldName, out string? fieldValue, out IEnumerable? fieldValues)\n {\n fieldValues = null;\n fieldValue = null;\n\n JsonNode? meta = null;\n switch (message)\n {\n case JsonRpcRequest request:\n meta = request.Params?[\"_meta\"];\n break;\n\n case JsonRpcNotification notification:\n meta = notification.Params?[\"_meta\"];\n break;\n }\n\n if (meta?[fieldName] is JsonValue value && value.GetValueKind() == JsonValueKind.String)\n {\n fieldValue = value.GetValue();\n }\n }\n\n internal static void InjectActivityContext(this DistributedContextPropagator propagator, Activity? activity, JsonRpcMessage message)\n {\n // noop if activity is null\n propagator.Inject(activity, message, InjectContext);\n }\n\n private static void InjectContext(object? message, string key, string value)\n {\n JsonNode? parameters = null;\n switch (message)\n {\n case JsonRpcRequest request:\n parameters = request.Params;\n break;\n\n case JsonRpcNotification notification:\n parameters = notification.Params;\n break;\n }\n\n // Replace any params._meta with the current value\n if (parameters is JsonObject jsonObject)\n {\n if (jsonObject[\"_meta\"] is not JsonObject meta)\n {\n meta = new JsonObject();\n jsonObject[\"_meta\"] = meta;\n }\n meta[key] = value;\n }\n }\n\n internal static bool ShouldInstrumentMessage(JsonRpcMessage message) =>\n ActivitySource.HasListeners() &&\n message switch\n {\n JsonRpcRequest => true,\n JsonRpcNotification notification => notification.Method != NotificationMethods.LoggingMessageNotification,\n _ => false\n };\n\n internal static ActivityLink[] ActivityLinkFromCurrent() => Activity.Current is null ? [] : [new ActivityLink(Activity.Current.Context)];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerHandlers.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a container for handlers used in the creation of an MCP server.\n/// \n/// \n/// \n/// This class provides a centralized collection of delegates that implement various capabilities of the Model Context Protocol.\n/// Each handler in this class corresponds to a specific endpoint in the Model Context Protocol and\n/// is responsible for processing a particular type of request. The handlers are used to customize\n/// the behavior of the MCP server by providing implementations for the various protocol operations.\n/// \n/// \n/// Handlers can be configured individually using the extension methods in \n/// such as and\n/// .\n/// \n/// \n/// When a client sends a request to the server, the appropriate handler is invoked to process the\n/// request and produce a response according to the protocol specification. Which handler is selected\n/// is done based on an ordinal, case-sensitive string comparison.\n/// \n/// \npublic sealed class McpServerHandlers\n{\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// \n /// \n /// This handler works alongside any tools defined in the collection.\n /// Tools from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the collection.\n /// The handler should implement logic to execute the requested tool and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available prompts when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more prompts.\n /// \n /// \n /// This handler works alongside any prompts defined in the collection.\n /// Prompts from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt that isn't found in the collection.\n /// The handler should implement logic to fetch or generate the requested prompt and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resource templates when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resource templates.\n /// \n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resources when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resources.\n /// \n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests the content of a specific resource identified by its URI.\n /// The handler should implement logic to locate and retrieve the requested resource.\n /// \n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler processes auto-completion requests, returning a list of suggestions based on the \n /// reference type and current argument value.\n /// \n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to receive notifications about changes to specific resources or resource patterns.\n /// The handler should implement logic to register the client's interest in the specified resources\n /// and set up the necessary infrastructure to send notifications when those resources change.\n /// \n /// \n /// After a successful subscription, the server should send resource change notifications to the client\n /// whenever a relevant resource is created, updated, or deleted.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to stop receiving notifications about previously subscribed resources.\n /// The handler should implement logic to remove the client's subscriptions to the specified resources\n /// and clean up any associated resources.\n /// \n /// \n /// After a successful unsubscription, the server should no longer send resource change notifications\n /// to the client for the specified resources.\n /// \n /// \n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler processes requests from clients. When set, it enables\n /// clients to control which log messages they receive by specifying a minimum severity threshold.\n /// \n /// \n /// After handling a level change request, the server typically begins sending log messages\n /// at or above the specified level to the client as notifications/message notifications.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n\n /// \n /// Overwrite any handlers in McpServerOptions with non-null handlers from this instance.\n /// \n /// \n /// \n internal void OverwriteWithSetHandlers(McpServerOptions options)\n {\n PromptsCapability? promptsCapability = options.Capabilities?.Prompts;\n if (ListPromptsHandler is not null || GetPromptHandler is not null)\n {\n promptsCapability ??= new();\n promptsCapability.ListPromptsHandler = ListPromptsHandler ?? promptsCapability.ListPromptsHandler;\n promptsCapability.GetPromptHandler = GetPromptHandler ?? promptsCapability.GetPromptHandler;\n }\n\n ResourcesCapability? resourcesCapability = options.Capabilities?.Resources;\n if (ListResourcesHandler is not null ||\n ReadResourceHandler is not null)\n {\n resourcesCapability ??= new();\n resourcesCapability.ListResourceTemplatesHandler = ListResourceTemplatesHandler ?? resourcesCapability.ListResourceTemplatesHandler;\n resourcesCapability.ListResourcesHandler = ListResourcesHandler ?? resourcesCapability.ListResourcesHandler;\n resourcesCapability.ReadResourceHandler = ReadResourceHandler ?? resourcesCapability.ReadResourceHandler;\n\n if (SubscribeToResourcesHandler is not null || UnsubscribeFromResourcesHandler is not null)\n {\n resourcesCapability.SubscribeToResourcesHandler = SubscribeToResourcesHandler ?? resourcesCapability.SubscribeToResourcesHandler;\n resourcesCapability.UnsubscribeFromResourcesHandler = UnsubscribeFromResourcesHandler ?? resourcesCapability.UnsubscribeFromResourcesHandler;\n resourcesCapability.Subscribe = true;\n }\n }\n\n ToolsCapability? toolsCapability = options.Capabilities?.Tools;\n if (ListToolsHandler is not null || CallToolHandler is not null)\n {\n toolsCapability ??= new();\n toolsCapability.ListToolsHandler = ListToolsHandler ?? toolsCapability.ListToolsHandler;\n toolsCapability.CallToolHandler = CallToolHandler ?? toolsCapability.CallToolHandler;\n }\n\n LoggingCapability? loggingCapability = options.Capabilities?.Logging;\n if (SetLoggingLevelHandler is not null)\n {\n loggingCapability ??= new();\n loggingCapability.SetLoggingLevelHandler = SetLoggingLevelHandler;\n }\n\n CompletionsCapability? completionsCapability = options.Capabilities?.Completions;\n if (CompleteHandler is not null)\n {\n completionsCapability ??= new();\n completionsCapability.CompleteHandler = CompleteHandler;\n }\n\n options.Capabilities ??= new();\n options.Capabilities.Prompts = promptsCapability;\n options.Capabilities.Resources = resourcesCapability;\n options.Capabilities.Tools = toolsCapability;\n options.Capabilities.Logging = loggingCapability;\n options.Capabilities.Completions = completionsCapability;\n }\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/SampleLlmTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses dependency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n ChatOptions options = new()\n {\n Instructions = \"You are a helpful test server.\",\n MaxOutputTokens = maxTokens,\n Temperature = 0.7f,\n };\n\n var samplingResponse = await thisServer.AsSamplingChatClient().GetResponseAsync(prompt, options, cancellationToken);\n\n return $\"LLM sampling result: {samplingResponse}\";\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpHttpClient.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\n#if NET\nusing System.Net.Http.Json;\n#else\nusing System.Text;\nusing System.Text.Json;\n#endif\n\nnamespace ModelContextProtocol.Client;\n\ninternal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n Debug.Assert(request.Content is null, \"The request body should only be supplied as a JsonRpcMessage\");\n Debug.Assert(message is null || request.Method == HttpMethod.Post, \"All messages should be sent in POST requests.\");\n\n using var content = CreatePostBodyContent(message);\n request.Content = content;\n return await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);\n }\n\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null)\n {\n return null;\n }\n\n#if NET\n return JsonContent.Create(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n#else\n return new StringContent(\n JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage),\n Encoding.UTF8,\n \"application/json\"\n );\n#endif\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/RequestHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\ninternal sealed class RequestHandlers : Dictionary>>\n{\n /// \n /// Registers a handler for incoming requests of a specific method in the MCP protocol.\n /// \n /// Type of request payload that will be deserialized from incoming JSON\n /// Type of response payload that will be serialized to JSON (not full RPC response)\n /// Method identifier to register for (e.g., \"tools/list\", \"logging/setLevel\")\n /// Handler function to be called when a request with the specified method identifier is received\n /// The JSON contract governing request parameter deserialization\n /// The JSON contract governing response serialization\n /// \n /// \n /// This method is used internally by the MCP infrastructure to register handlers for various protocol methods.\n /// When an incoming request matches the specified method, the registered handler will be invoked with the\n /// deserialized request parameters.\n /// \n /// \n /// The handler function receives the deserialized request object and a cancellation token, and should return\n /// a response object that will be serialized back to the client.\n /// \n /// \n public void Set(\n string method,\n Func> handler,\n JsonTypeInfo requestTypeInfo,\n JsonTypeInfo responseTypeInfo)\n {\n Throw.IfNull(method);\n Throw.IfNull(handler);\n Throw.IfNull(requestTypeInfo);\n Throw.IfNull(responseTypeInfo);\n\n this[method] = async (request, cancellationToken) =>\n {\n TRequest? typedRequest = JsonSerializer.Deserialize(request.Params, requestTypeInfo);\n object? result = await handler(typedRequest, request.RelatedTransport, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToNode(result, responseTypeInfo);\n };\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/LoggingUpdateMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace EverythingServer;\n\npublic class LoggingUpdateMessageSender(IMcpServer server, Func getMinLevel) : BackgroundService\n{\n readonly Dictionary _loggingLevelMap = new()\n {\n { LoggingLevel.Debug, \"Debug-level message\" },\n { LoggingLevel.Info, \"Info-level message\" },\n { LoggingLevel.Notice, \"Notice-level message\" },\n { LoggingLevel.Warning, \"Warning-level message\" },\n { LoggingLevel.Error, \"Error-level message\" },\n { LoggingLevel.Critical, \"Critical-level message\" },\n { LoggingLevel.Alert, \"Alert-level message\" },\n { LoggingLevel.Emergency, \"Emergency-level message\" }\n };\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n var newLevel = (LoggingLevel)Random.Shared.Next(_loggingLevelMap.Count);\n\n var message = new\n {\n Level = newLevel.ToString().ToLower(),\n Data = _loggingLevelMap[newLevel],\n };\n\n if (newLevel > getMinLevel())\n {\n await server.SendNotificationAsync(\"notifications/message\", message, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(15000, stoppingToken);\n }\n }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/dd75c45c123055baacd7aa4418f425f412797a29/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs\n// and then modified to build on netstandard2.0.\n\n#if !NET\nusing System.Buffers;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Provides a handler used by the language compiler to process interpolated strings into instances.\n internal ref struct DefaultInterpolatedStringHandler\n {\n // Implementation note:\n // As this type lives in CompilerServices and is only intended to be targeted by the compiler,\n // public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input\n // when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException.\n\n /// Expected average length of formatted data used for an individual interpolation expression result.\n /// \n /// This is inherited from string.Format, and could be changed based on further data.\n /// string.Format actually uses `format.Length + args.Length * 8`, but format.Length\n /// includes the format items themselves, e.g. \"{0}\", and since it's rare to have double-digit\n /// numbers of items, we bump the 8 up to 11 to account for the three extra characters in \"{d}\",\n /// since the compiler-provided base length won't include the equivalent character count.\n /// \n private const int GuessedLengthPerHole = 11;\n /// Minimum size array to rent from the pool.\n /// Same as stack-allocation size used today by string.Format.\n private const int MinimumArrayPoolLength = 256;\n\n /// Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.\n private readonly IFormatProvider? _provider;\n /// Array rented from the array pool and used to back .\n private char[]? _arrayToReturnToPool;\n /// The span to write into.\n private Span _chars;\n /// Position at which to write the next character.\n private int _pos;\n /// Whether provides an ICustomFormatter.\n /// \n /// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive\n /// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field\n /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider\n /// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a\n /// formatter, we pay for the extra interface call on each AppendFormatted that needs it.\n /// \n private readonly bool _hasCustomFormatter;\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)\n {\n _provider = null;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = false;\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)\n {\n _provider = provider;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer)\n {\n _provider = provider;\n _chars = initialBuffer;\n _arrayToReturnToPool = null;\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Derives a default length with which to seed the handler.\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant\n internal static int GetDefaultLength(int literalLength, int formattedCount) =>\n Math.Max(MinimumArrayPoolLength, literalLength + (formattedCount * GuessedLengthPerHole));\n\n /// Gets the built .\n /// The built string.\n public override string ToString() => Text.ToString();\n\n /// Gets the built and clears the handler.\n /// The built string.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after\n /// is called on any one of them.\n /// \n public string ToStringAndClear()\n {\n string result = Text.ToString();\n Clear();\n return result;\n }\n\n /// Clears the handler.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after \n /// is called on any one of them.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Clear()\n {\n char[]? toReturn = _arrayToReturnToPool;\n\n // Defensive clear\n _arrayToReturnToPool = null;\n _chars = default;\n _pos = 0;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n /// Gets a span of the characters appended to the handler.\n public ReadOnlySpan Text => _chars.Slice(0, _pos);\n\n /// Writes the specified string to the handler.\n /// The string to write.\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void AppendLiteral(string value)\n {\n if (value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopyString(value);\n }\n }\n\n #region AppendFormatted\n // Design note:\n // The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression;\n // if it can't find an appropriate overload, for handlers in general it'll simply fail to compile.\n // (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to\n // its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case,\n // interpolated strings will still work, but it has the downside that a developer generally won't know\n // if the fallback is happening and they're paying more.)\n //\n // At a minimum, then, we would need an overload that accepts:\n // (object value, int alignment = 0, string? format = null)\n // Such an overload would provide the same expressiveness as string.Format. However, this has several\n // shortcomings:\n // - Every value type in an interpolation expression would be boxed.\n // - ReadOnlySpan could not be used in interpolation expressions.\n // - Every AppendFormatted call would have three arguments at the call site, bloating the IL further.\n // - Every invocation would be more expensive, due to lack of specialization, every call needing to account\n // for alignment and format, etc.\n //\n // To address that, we could just have overloads for T and ReadOnlySpan:\n // (T)\n // (T, int alignment)\n // (T, string? format)\n // (T, int alignment, string? format)\n // (ReadOnlySpan)\n // (ReadOnlySpan, int alignment)\n // (ReadOnlySpan, string? format)\n // (ReadOnlySpan, int alignment, string? format)\n // but this also has shortcomings:\n // - Some expressions that would have worked with an object overload will now force a fallback to string.Format\n // (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler\n // can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully\n // be passed as an argument of type `object` but not of type `T`.\n // - Reference types get no benefit from going through the generic code paths, and actually incur some overheads\n // from doing so.\n // - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate\n // at compile time for value types but don't (currently) if the Nullable goes through the same code paths\n // (see https://github.com/dotnet/runtime/issues/50915).\n //\n // We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common handler\n // and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads for each of:\n // (T, ...) where T : struct\n // (T?, ...) where T : struct\n // (object, ...)\n // (ReadOnlySpan, ...)\n // (string, ...)\n // but this also has shortcomings, most importantly:\n // - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object overload.\n // This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, so without those\n // they'd all map to the object overloads as well.\n // - Any reference type with an implicit cast to ROS will fail to compile due to ambiguities between the overloads. string\n // is one such type, hence needing dedicated overloads for it that can be bound to more tightly.\n //\n // A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, would be the set:\n // (T, ...) with no constraint\n // (ReadOnlySpan) and (ReadOnlySpan, int)\n // (object, int alignment = 0, string? format = null)\n // (string) and (string, int)\n // This would address most of the concerns, at the expense of:\n // - Most reference types going through the generic code paths and so being a bit more expensive.\n // - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed.\n // We could choose to add a T? where T : struct set of overloads if necessary.\n // Strings don't require their own overloads here, but as they're expected to be very common and as we can\n // optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't\n // need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them.\n //\n // Hole values are formatted according to the following policy:\n // 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if the value is null).\n // 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat.\n // 3. If the type implements IFormattable, use IFormattable.ToString.\n // 4. Otherwise, use object.ToString.\n // This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this doesn't\n // apply is ReadOnlySpan, which isn't supported by either string.Format nor StringBuilder.AppendFormat, but more\n // importantly which can't be boxed to be passed to ICustomFormatter.Format.\n\n #region AppendFormatted T\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The type of the value to write.\n public void AppendFormatted(T value)\n {\n // This method could delegate to AppendFormatted with a null format, but explicitly passing\n // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined,\n // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format.\n\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n return;\n }\n\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n public void AppendFormatted(T value, string? format)\n {\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format);\n return;\n }\n\n // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter\n // requires the former. For value types, it won't matter as the type checks devolve into\n // JIT-time constants. For reference types, they're more likely to implement IFormattable\n // than they are to implement ISpanFormattable: if they don't implement either, we save an\n // interface check over first checking for ISpanFormattable and then for IFormattable, and\n // if it only implements IFormattable, we come out even: only if it implements both do we\n // end up paying for an extra interface check.\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment)\n {\n int startingPos = _pos;\n AppendFormatted(value);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment, string? format)\n {\n int startingPos = _pos;\n AppendFormatted(value, format);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n #endregion\n\n #region AppendFormatted ReadOnlySpan\n /// Writes the specified character span to the handler.\n /// The span to write.\n public void AppendFormatted(scoped ReadOnlySpan value)\n {\n // Fast path for when the value fits in the current buffer\n if (value.TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopySpan(value);\n }\n }\n\n /// Writes the specified string of chars to the handler.\n /// The span to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(scoped ReadOnlySpan value, int alignment = 0, string? format = null)\n {\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingRequired = alignment - value.Length;\n if (paddingRequired <= 0)\n {\n // The value is as large or larger than the required amount of padding,\n // so just write the value.\n AppendFormatted(value);\n return;\n }\n\n // Write the value along with the appropriate padding.\n EnsureCapacityForAdditionalChars(value.Length + paddingRequired);\n if (leftAlign)\n {\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n }\n else\n {\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n #endregion\n\n #region AppendFormatted string\n /// Writes the specified value to the handler.\n /// The value to write.\n public void AppendFormatted(string? value)\n {\n // Fast-path for no custom formatter and a non-null string that fits in the current destination buffer.\n if (!_hasCustomFormatter &&\n value is not null &&\n value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n AppendFormattedSlow(value);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// \n /// Slow path to handle a custom formatter, potentially null value,\n /// or a string that doesn't fit in the current buffer.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendFormattedSlow(string? value)\n {\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n }\n else if (value is not null)\n {\n EnsureCapacityForAdditionalChars(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>\n // Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload\n // simply to disambiguate between ROS and object, just in case someone does specify a format, as\n // string is implicitly convertible to both. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n\n #region AppendFormatted object\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>\n // This overload is expected to be used rarely, only if either a) something strongly typed as object is\n // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It\n // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n #endregion\n\n /// Gets whether the provider provides a custom formatter.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites\n internal static bool HasCustomFormatter(IFormatProvider provider)\n {\n Debug.Assert(provider is not null);\n Debug.Assert(provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, \"Expected CultureInfo to not provide a custom formatter\");\n return\n provider!.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case\n provider.GetFormat(typeof(ICustomFormatter)) != null;\n }\n\n /// Formats the value using the custom formatter from the provider.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendCustomFormatter(T value, string? format)\n {\n // This case is very rare, but we need to handle it prior to the other checks in case\n // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.\n // We do the cast here rather than in the ctor, even though this could be executed multiple times per\n // formatting, to make the cast pay for play.\n Debug.Assert(_hasCustomFormatter);\n Debug.Assert(_provider != null);\n\n ICustomFormatter? formatter = (ICustomFormatter?)_provider!.GetFormat(typeof(ICustomFormatter));\n Debug.Assert(formatter != null, \"An incorrectly written provider said it implemented ICustomFormatter, and then didn't\");\n\n if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted)\n {\n AppendLiteral(customFormatted);\n }\n }\n\n /// Handles adding any padding required for aligning a formatted value in an interpolation expression.\n /// The position at which the written value started.\n /// Non-zero minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)\n {\n Debug.Assert(startingPos >= 0 && startingPos <= _pos);\n Debug.Assert(alignment != 0);\n\n int charsWritten = _pos - startingPos;\n\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingNeeded = alignment - charsWritten;\n if (paddingNeeded > 0)\n {\n EnsureCapacityForAdditionalChars(paddingNeeded);\n\n if (leftAlign)\n {\n _chars.Slice(_pos, paddingNeeded).Fill(' ');\n }\n else\n {\n _chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded));\n _chars.Slice(startingPos, paddingNeeded).Fill(' ');\n }\n\n _pos += paddingNeeded;\n }\n }\n\n /// Ensures has the capacity to store beyond .\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void EnsureCapacityForAdditionalChars(int additionalChars)\n {\n if (_chars.Length - _pos < additionalChars)\n {\n Grow(additionalChars);\n }\n }\n\n /// Fallback for fast path in when there's not enough space in the destination.\n /// The string to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopyString(string value)\n {\n Grow(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Fallback for for when not enough space exists in the current buffer.\n /// The span to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopySpan(scoped ReadOnlySpan value)\n {\n Grow(value.Length);\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Grows to have the capacity to store at least beyond .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow(int additionalChars)\n {\n // This method is called when the remaining space (_chars.Length - _pos) is\n // insufficient to store a specific number of additional characters. Thus, we\n // need to grow to at least that new total. GrowCore will handle growing by more\n // than that if possible.\n Debug.Assert(additionalChars > _chars.Length - _pos);\n GrowCore((uint)_pos + (uint)additionalChars);\n }\n\n /// Grows the size of .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow()\n {\n // This method is called when the remaining space in _chars isn't sufficient to continue\n // the operation. Thus, we need at least one character beyond _chars.Length. GrowCore\n // will handle growing by more than that if possible.\n GrowCore((uint)_chars.Length + 1);\n }\n\n /// Grow the size of to at least the specified .\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines\n private void GrowCore(uint requiredMinCapacity)\n {\n // We want the max of how much space we actually required and doubling our capacity (without going beyond the max allowed length). We\n // also want to avoid asking for small arrays, to reduce the number of times we need to grow, and since we're working with unsigned\n // ints that could technically overflow if someone tried to, for example, append a huge string to a huge string, we also clamp to int.MaxValue.\n // Even if the array creation fails in such a case, we may later fail in ToStringAndClear.\n\n const int StringMaxLength = 0x3FFFFFDF;\n uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, StringMaxLength));\n int arraySize = (int)Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue);\n\n char[] newArray = ArrayPool.Shared.Rent(arraySize);\n _chars.Slice(0, _pos).CopyTo(newArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = newArray;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n private static uint Clamp(uint value, uint min, uint max)\n {\n Debug.Assert(min <= max);\n\n if (value < min)\n {\n return min;\n }\n else if (value > max)\n {\n return max;\n }\n\n return value;\n }\n }\n}\n#endif"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace QuickstartWeatherServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public static async Task GetAlerts(\n HttpClient client,\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public static async Task GetForecast(\n HttpClient client,\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/LongRunningTool.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class LongRunningTool\n{\n [McpServerTool(Name = \"longRunningOperation\"), Description(\"Demonstrates a long running operation with progress updates\")]\n public static async Task LongRunningOperation(\n IMcpServer server,\n RequestContext context,\n int duration = 10,\n int steps = 5)\n {\n var progressToken = context.Params?.ProgressToken;\n var stepDuration = duration / steps;\n\n for (int i = 1; i <= steps + 1; i++)\n {\n await Task.Delay(stepDuration * 1000);\n \n if (progressToken is not null)\n {\n await server.SendNotificationAsync(\"notifications/progress\", new\n {\n Progress = i,\n Total = steps,\n progressToken\n });\n }\n }\n\n return $\"Long running operation completed. Duration: {duration} seconds. Steps: {steps}.\";\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/AnnotatedMessageTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AnnotatedMessageTool\n{\n public enum MessageType\n {\n Error,\n Success,\n Debug,\n }\n\n [McpServerTool(Name = \"annotatedMessage\"), Description(\"Generates an annotated message\")]\n public static IEnumerable AnnotatedMessage(MessageType messageType, bool includeImage = true)\n {\n List contents = messageType switch\n {\n MessageType.Error => [new TextContentBlock\n {\n Text = \"Error: Operation failed\",\n Annotations = new() { Audience = [Role.User, Role.Assistant], Priority = 1.0f }\n }],\n MessageType.Success => [new TextContentBlock\n {\n Text = \"Operation completed successfully\",\n Annotations = new() { Audience = [Role.User], Priority = 0.7f }\n }],\n MessageType.Debug => [new TextContentBlock\n {\n Text = \"Debug: Cache hit ratio 0.95, latency 150ms\",\n Annotations = new() { Audience = [Role.Assistant], Priority = 0.3f }\n }],\n _ => throw new ArgumentOutOfRangeException(nameof(messageType), messageType, null)\n };\n\n if (includeImage)\n {\n contents.Add(new ImageContentBlock\n {\n Data = TinyImageTool.MCP_TINY_IMAGE.Split(\",\").Last(),\n MimeType = \"image/png\",\n Annotations = new() { Audience = [Role.User], Priority = 0.5f }\n });\n }\n\n return contents;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building resources that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner resource instance.\n/// \npublic abstract class DelegatingMcpServerResource : McpServerResource\n{\n private readonly McpServerResource _innerResource;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner resource wrapped by this delegating resource.\n protected DelegatingMcpServerResource(McpServerResource innerResource)\n {\n Throw.IfNull(innerResource);\n _innerResource = innerResource;\n }\n\n /// \n public override Resource? ProtocolResource => _innerResource.ProtocolResource;\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate => _innerResource.ProtocolResourceTemplate;\n\n /// \n public override ValueTask ReadAsync(RequestContext request, CancellationToken cancellationToken = default) => \n _innerResource.ReadAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerResource.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationHandler.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Authentication;\nusing System.Text.Encodings.Web;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Authentication handler for MCP protocol that adds resource metadata to challenge responses\n/// and handles resource metadata endpoint requests.\n/// \npublic class McpAuthenticationHandler : AuthenticationHandler, IAuthenticationRequestHandler\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationHandler(\n IOptionsMonitor options,\n ILoggerFactory logger,\n UrlEncoder encoder)\n : base(options, logger, encoder)\n {\n }\n\n /// \n public async Task HandleRequestAsync()\n {\n // Check if the request is for the resource metadata endpoint\n string requestPath = Request.Path.Value ?? string.Empty;\n\n string expectedMetadataPath = Options.ResourceMetadataUri?.ToString() ?? string.Empty;\n if (Options.ResourceMetadataUri != null && !Options.ResourceMetadataUri.IsAbsoluteUri)\n {\n // For relative URIs, it's just the path component.\n expectedMetadataPath = Options.ResourceMetadataUri.OriginalString;\n }\n\n // If the path doesn't match, let the request continue through the pipeline\n if (!string.Equals(requestPath, expectedMetadataPath, StringComparison.OrdinalIgnoreCase))\n {\n return false;\n }\n\n return await HandleResourceMetadataRequestAsync();\n }\n\n /// \n /// Gets the base URL from the current request, including scheme, host, and path base.\n /// \n private string GetBaseUrl() => $\"{Request.Scheme}://{Request.Host}{Request.PathBase}\";\n\n /// \n /// Gets the absolute URI for the resource metadata endpoint.\n /// \n private string GetAbsoluteResourceMetadataUri()\n {\n var resourceMetadataUri = Options.ResourceMetadataUri;\n\n string currentPath = resourceMetadataUri?.ToString() ?? string.Empty;\n\n if (resourceMetadataUri != null && resourceMetadataUri.IsAbsoluteUri)\n {\n return currentPath;\n }\n\n // For relative URIs, combine with the base URL\n string baseUrl = GetBaseUrl();\n string relativePath = resourceMetadataUri?.OriginalString.TrimStart('/') ?? string.Empty;\n\n if (!Uri.TryCreate($\"{baseUrl.TrimEnd('/')}/{relativePath}\", UriKind.Absolute, out var absoluteUri))\n {\n throw new InvalidOperationException($\"Could not create absolute URI for resource metadata. Base URL: {baseUrl}, Relative Path: {relativePath}\");\n }\n\n return absoluteUri.ToString();\n }\n\n private async Task HandleResourceMetadataRequestAsync()\n {\n var resourceMetadata = Options.ResourceMetadata;\n\n if (Options.Events.OnResourceMetadataRequest is not null)\n {\n var context = new ResourceMetadataRequestContext(Request.HttpContext, Scheme, Options)\n {\n ResourceMetadata = CloneResourceMetadata(resourceMetadata),\n };\n\n await Options.Events.OnResourceMetadataRequest(context);\n\n if (context.Result is not null)\n {\n if (context.Result.Handled)\n {\n return true;\n }\n else if (context.Result.Skipped)\n {\n return false;\n }\n else if (context.Result.Failure is not null)\n {\n throw new AuthenticationFailureException(\"An error occurred from the OnResourceMetadataRequest event.\", context.Result.Failure);\n }\n }\n\n resourceMetadata = context.ResourceMetadata;\n }\n\n if (resourceMetadata == null)\n {\n throw new InvalidOperationException(\n \"ResourceMetadata has not been configured. Please set McpAuthenticationOptions.ResourceMetadata or ensure context.ResourceMetadata is set inside McpAuthenticationOptions.Events.OnResourceMetadataRequest.\"\n );\n }\n\n await Results.Json(resourceMetadata, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ProtectedResourceMetadata))).ExecuteAsync(Context);\n return true;\n }\n\n /// \n // If no forwarding is configured, this handler doesn't perform authentication\n protected override async Task HandleAuthenticateAsync() => AuthenticateResult.NoResult();\n\n /// \n protected override Task HandleChallengeAsync(AuthenticationProperties properties)\n {\n // Get the absolute URI for the resource metadata\n string rawPrmDocumentUri = GetAbsoluteResourceMetadataUri();\n\n properties ??= new AuthenticationProperties();\n\n // Store the resource_metadata in properties in case other handlers need it\n properties.Items[\"resource_metadata\"] = rawPrmDocumentUri;\n\n // Add the WWW-Authenticate header with Bearer scheme and resource metadata\n string headerValue = $\"Bearer realm=\\\"{Scheme.Name}\\\", resource_metadata=\\\"{rawPrmDocumentUri}\\\"\";\n Response.Headers.Append(\"WWW-Authenticate\", headerValue);\n\n return base.HandleChallengeAsync(properties);\n }\n\n internal static ProtectedResourceMetadata? CloneResourceMetadata(ProtectedResourceMetadata? resourceMetadata)\n {\n if (resourceMetadata is null)\n {\n return null;\n }\n\n return new ProtectedResourceMetadata\n {\n Resource = resourceMetadata.Resource,\n AuthorizationServers = [.. resourceMetadata.AuthorizationServers],\n BearerMethodsSupported = [.. resourceMetadata.BearerMethodsSupported],\n ScopesSupported = [.. resourceMetadata.ScopesSupported],\n JwksUri = resourceMetadata.JwksUri,\n ResourceSigningAlgValuesSupported = resourceMetadata.ResourceSigningAlgValuesSupported is not null ? [.. resourceMetadata.ResourceSigningAlgValuesSupported] : null,\n ResourceName = resourceMetadata.ResourceName,\n ResourceDocumentation = resourceMetadata.ResourceDocumentation,\n ResourcePolicyUri = resourceMetadata.ResourcePolicyUri,\n ResourceTosUri = resourceMetadata.ResourceTosUri,\n TlsClientCertificateBoundAccessTokens = resourceMetadata.TlsClientCertificateBoundAccessTokens,\n AuthorizationDetailsTypesSupported = resourceMetadata.AuthorizationDetailsTypesSupported is not null ? [.. resourceMetadata.AuthorizationDetailsTypesSupported] : null,\n DpopSigningAlgValuesSupported = resourceMetadata.DpopSigningAlgValuesSupported is not null ? [.. resourceMetadata.DpopSigningAlgValuesSupported] : null,\n DpopBoundAccessTokensRequired = resourceMetadata.DpopBoundAccessTokensRequired\n };\n }\n\n}\n"], ["/csharp-sdk/samples/QuickstartClient/Program.cs", "using Anthropic.SDK;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Client;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Configuration\n .AddEnvironmentVariables()\n .AddUserSecrets();\n\nvar (command, arguments) = GetCommandAndArguments(args);\n\nvar clientTransport = new StdioClientTransport(new()\n{\n Name = \"Demo Server\",\n Command = command,\n Arguments = arguments,\n});\n\nawait using var mcpClient = await McpClientFactory.CreateAsync(clientTransport);\n\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\"Connected to server with tools: {tool.Name}\");\n}\n\nusing var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration[\"ANTHROPIC_API_KEY\"]))\n .Messages\n .AsBuilder()\n .UseFunctionInvocation()\n .Build();\n\nvar options = new ChatOptions\n{\n MaxOutputTokens = 1000,\n ModelId = \"claude-3-5-sonnet-20241022\",\n Tools = [.. tools]\n};\n\nConsole.ForegroundColor = ConsoleColor.Green;\nConsole.WriteLine(\"MCP Client Started!\");\nConsole.ResetColor();\n\nPromptForInput();\nwhile(Console.ReadLine() is string query && !\"exit\".Equals(query, StringComparison.OrdinalIgnoreCase))\n{\n if (string.IsNullOrWhiteSpace(query))\n {\n PromptForInput();\n continue;\n }\n\n await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))\n {\n Console.Write(message);\n }\n Console.WriteLine();\n\n PromptForInput();\n}\n\nstatic void PromptForInput()\n{\n Console.WriteLine(\"Enter a command (or 'exit' to quit):\");\n Console.ForegroundColor = ConsoleColor.Cyan;\n Console.Write(\"> \");\n Console.ResetColor();\n}\n\n/// \n/// Determines the command (executable) to run and the script/path to pass to it. This allows different\n/// languages/runtime environments to be used as the MCP server.\n/// \n/// \n/// This method uses the file extension of the first argument to determine the command, if it's py, it'll run python,\n/// if it's js, it'll run node, if it's a directory or a csproj file, it'll run dotnet.\n/// \n/// If no arguments are provided, it defaults to running the QuickstartWeatherServer project from the current repo.\n/// \n/// This method would only be required if you're creating a generic client, such as we use for the quickstart.\n/// \nstatic (string command, string[] arguments) GetCommandAndArguments(string[] args)\n{\n return args switch\n {\n [var script] when script.EndsWith(\".py\") => (\"python\", args),\n [var script] when script.EndsWith(\".js\") => (\"node\", args),\n [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(\".csproj\")) => (\"dotnet\", [\"run\", \"--project\", script]),\n _ => (\"dotnet\", [\"run\", \"--project\", Path.Combine(GetCurrentSourceDirectory(), \"../QuickstartWeatherServer\")])\n };\n}\n\nstatic string GetCurrentSourceDirectory([CallerFilePath] string? currentFile = null)\n{\n Debug.Assert(!string.IsNullOrWhiteSpace(currentFile));\n return Path.GetDirectoryName(currentFile) ?? throw new InvalidOperationException(\"Unable to determine source directory.\");\n}"], ["/csharp-sdk/src/Common/Throw.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace ModelContextProtocol;\n\n/// Provides helper methods for throwing exceptions.\ninternal static class Throw\n{\n // NOTE: Most of these should be replaced with extension statics for the relevant extension\n // type as downlevel polyfills once the C# 14 extension everything feature is available.\n\n public static void IfNull([NotNull] object? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n }\n\n public static void IfNullOrWhiteSpace([NotNull] string? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null || arg.AsSpan().IsWhiteSpace())\n {\n ThrowArgumentNullOrWhiteSpaceException(parameterName);\n }\n }\n\n public static void IfNegative(int arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg < 0)\n {\n Throw(parameterName);\n static void Throw(string? parameterName) => throw new ArgumentOutOfRangeException(parameterName, \"must not be negative.\");\n }\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullOrWhiteSpaceException(string? parameterName)\n {\n if (parameterName is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n\n throw new ArgumentException(\"Value cannot be empty or composed entirely of whitespace.\", parameterName);\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullException(string? parameterName) => throw new ArgumentNullException(parameterName);\n}"], ["/csharp-sdk/samples/EverythingServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test://direct/text/resource\", Name = \"Direct Text Resource\", MimeType = \"text/plain\")]\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n\n [McpServerResource(UriTemplate = \"test://template/resource/{id}\", Name = \"Template Resource\")]\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id)\n {\n int index = id - 1;\n if ((uint)index >= ResourceGenerator.Resources.Count)\n {\n throw new NotSupportedException($\"Unknown resource: {requestContext.Params?.Uri}\");\n }\n\n var resource = ResourceGenerator.Resources[index];\n return resource.MimeType == \"text/plain\" ?\n new TextResourceContents\n {\n Text = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n } :\n new BlobResourceContents\n {\n Blob = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerTool.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building tools that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner tool instance.\n/// \npublic abstract class DelegatingMcpServerTool : McpServerTool\n{\n private readonly McpServerTool _innerTool;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner tool wrapped by this delegating tool.\n protected DelegatingMcpServerTool(McpServerTool innerTool)\n {\n Throw.IfNull(innerTool);\n _innerTool = innerTool;\n }\n\n /// \n public override Tool ProtocolTool => _innerTool.ProtocolTool;\n\n /// \n public override ValueTask InvokeAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerTool.InvokeAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerTool.ToString();\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/PasteArguments.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/d2650b6ae7023a2d9d2c74c56116f1f18472ab04/src/libraries/System.Private.CoreLib/src/System/PasteArguments.cs\n// and changed from using ValueStringBuilder to StringBuilder.\n\n#if !NET\nusing System.Text;\n\nnamespace System;\n\ninternal static partial class PasteArguments\n{\n internal static void AppendArgument(StringBuilder stringBuilder, string argument)\n {\n if (stringBuilder.Length != 0)\n {\n stringBuilder.Append(' ');\n }\n\n // Parsing rules for non-argv[0] arguments:\n // - Backslash is a normal character except followed by a quote.\n // - 2N backslashes followed by a quote ==> N literal backslashes followed by unescaped quote\n // - 2N+1 backslashes followed by a quote ==> N literal backslashes followed by a literal quote\n // - Parsing stops at first whitespace outside of quoted region.\n // - (post 2008 rule): A closing quote followed by another quote ==> literal quote, and parsing remains in quoting mode.\n if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument))\n {\n // Simple case - no quoting or changes needed.\n stringBuilder.Append(argument);\n }\n else\n {\n stringBuilder.Append(Quote);\n int idx = 0;\n while (idx < argument.Length)\n {\n char c = argument[idx++];\n if (c == Backslash)\n {\n int numBackSlash = 1;\n while (idx < argument.Length && argument[idx] == Backslash)\n {\n idx++;\n numBackSlash++;\n }\n\n if (idx == argument.Length)\n {\n // We'll emit an end quote after this so must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2);\n }\n else if (argument[idx] == Quote)\n {\n // Backslashes will be followed by a quote. Must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2 + 1);\n stringBuilder.Append(Quote);\n idx++;\n }\n else\n {\n // Backslash will not be followed by a quote, so emit as normal characters.\n stringBuilder.Append(Backslash, numBackSlash);\n }\n\n continue;\n }\n\n if (c == Quote)\n {\n // Escape the quote so it appears as a literal. This also guarantees that we won't end up generating a closing quote followed\n // by another quote (which parses differently pre-2008 vs. post-2008.)\n stringBuilder.Append(Backslash);\n stringBuilder.Append(Quote);\n continue;\n }\n\n stringBuilder.Append(c);\n }\n\n stringBuilder.Append(Quote);\n }\n }\n\n private static bool ContainsNoWhitespaceOrQuotes(string s)\n {\n for (int i = 0; i < s.Length; i++)\n {\n char c = s[i];\n if (char.IsWhiteSpace(c) || c == Quote)\n {\n return false;\n }\n }\n\n return true;\n }\n\n private const char Quote = '\\\"';\n private const char Backslash = '\\\\';\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrimitiveCollection.cs", "using System.Collections;\nusing System.Collections.Concurrent;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their names.\n/// Specifies the type of primitive stored in the collection.\npublic class McpServerPrimitiveCollection : ICollection, IReadOnlyCollection\n where T : IMcpServerPrimitive\n{\n /// Concurrent dictionary of primitives, indexed by their names.\n private readonly ConcurrentDictionary _primitives;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPrimitiveCollection(IEqualityComparer? keyComparer = null)\n {\n _primitives = new(keyComparer ?? EqualityComparer.Default);\n }\n\n /// Occurs when the collection is changed.\n /// \n /// By default, this is raised when a primitive is added or removed. However, a derived implementation\n /// may raise this event for other reasons, such as when a primitive is modified.\n /// \n public event EventHandler? Changed;\n\n /// Gets the number of primitives in the collection.\n public int Count => _primitives.Count;\n\n /// Gets whether there are any primitives in the collection.\n public bool IsEmpty => _primitives.IsEmpty;\n\n /// Raises if there are registered handlers.\n protected void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);\n\n /// Gets the with the specified from the collection.\n /// The name of the primitive to retrieve.\n /// The with the specified name.\n /// is .\n /// An primitive with the specified name does not exist in the collection.\n public T this[string name]\n {\n get\n {\n Throw.IfNull(name);\n return _primitives[name];\n }\n }\n\n /// Clears all primitives from the collection.\n public virtual void Clear()\n {\n _primitives.Clear();\n RaiseChanged();\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// is .\n /// A primitive with the same name as already exists in the collection.\n public void Add(T primitive)\n {\n if (!TryAdd(primitive))\n {\n throw new ArgumentException($\"A primitive with the same name '{primitive.Id}' already exists in the collection.\", nameof(primitive));\n }\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// if the primitive was added; otherwise, .\n /// is .\n public virtual bool TryAdd(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool added = _primitives.TryAdd(primitive.Id, primitive);\n if (added)\n {\n RaiseChanged();\n }\n\n return added;\n }\n\n /// Removes the specified primitivefrom the collection.\n /// The primitive to be removed from the collection.\n /// \n /// if the primitive was found in the collection and removed; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool Remove(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool removed = ((ICollection>)_primitives).Remove(new(primitive.Id, primitive));\n if (removed)\n {\n RaiseChanged();\n }\n\n return removed;\n }\n\n /// Attempts to get the primitive with the specified name from the collection.\n /// The name of the primitive to retrieve.\n /// The primitive, if found; otherwise, .\n /// \n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool TryGetPrimitive(string name, [NotNullWhen(true)] out T? primitive)\n {\n Throw.IfNull(name);\n return _primitives.TryGetValue(name, out primitive);\n }\n\n /// Checks if a specific primitive is present in the collection of primitives.\n /// The primitive to search for in the collection.\n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// is .\n public virtual bool Contains(T primitive)\n {\n Throw.IfNull(primitive);\n return ((ICollection>)_primitives).Contains(new(primitive.Id, primitive));\n }\n\n /// Gets the names of all of the primitives in the collection.\n public virtual ICollection PrimitiveNames => _primitives.Keys;\n\n /// Creates an array containing all of the primitives in the collection.\n /// An array containing all of the primitives in the collection.\n public virtual T[] ToArray() => _primitives.Values.ToArray();\n\n /// \n public virtual void CopyTo(T[] array, int arrayIndex)\n {\n Throw.IfNull(array);\n\n _primitives.Values.CopyTo(array, arrayIndex);\n }\n\n /// \n public virtual IEnumerator GetEnumerator()\n {\n foreach (var entry in _primitives)\n {\n yield return entry.Value;\n }\n }\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n bool ICollection.IsReadOnly => false;\n}"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace ProtectedMCPServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n private readonly IHttpClientFactory _httpClientFactory;\n\n public WeatherTools(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public async Task GetAlerts(\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public async Task GetForecast(\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerPrompt.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building prompts that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner prompt instance.\n/// \npublic abstract class DelegatingMcpServerPrompt : McpServerPrompt\n{\n private readonly McpServerPrompt _innerPrompt;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner prompt wrapped by this delegating prompt.\n protected DelegatingMcpServerPrompt(McpServerPrompt innerPrompt)\n {\n Throw.IfNull(innerPrompt);\n _innerPrompt = innerPrompt;\n }\n\n /// \n public override Prompt ProtocolPrompt => _innerPrompt.ProtocolPrompt;\n\n /// \n public override ValueTask GetAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerPrompt.GetAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerPrompt.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/CustomizableJsonStringEnumConverter.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.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\n#if !NET9_0_OR_GREATER\nusing System.Reflection;\n#endif\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n#if !NET9_0_OR_GREATER\nusing ModelContextProtocol;\n#endif\n\n// NOTE:\n// This is a workaround for lack of System.Text.Json's JsonStringEnumConverter\n// 9.x support for JsonStringEnumMemberNameAttribute. Once all builds use the System.Text.Json 9.x\n// version, this whole file can be removed. Note that the type is public so that external source\n// generators can use it, so removing it is a potential breaking change.\n\nnamespace ModelContextProtocol\n{\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// The enum type to convert.\n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class CustomizableJsonStringEnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum> :\n JsonStringEnumConverter where TEnum : struct, Enum\n {\n#if !NET9_0_OR_GREATER\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The converter automatically detects any enum members decorated with \n /// and uses those values during serialization and deserialization.\n /// \n public CustomizableJsonStringEnumConverter() :\n base(namingPolicy: ResolveNamingPolicy())\n {\n }\n\n private static JsonNamingPolicy? ResolveNamingPolicy()\n {\n var map = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)\n .Select(f => (f.Name, AttributeName: f.GetCustomAttribute()?.Name))\n .Where(pair => pair.AttributeName != null)\n .ToDictionary(pair => pair.Name, pair => pair.AttributeName);\n\n return map.Count > 0 ? new EnumMemberNamingPolicy(map!) : null;\n }\n\n private sealed class EnumMemberNamingPolicy(Dictionary map) : JsonNamingPolicy\n {\n public override string ConvertName(string name) =>\n map.TryGetValue(name, out string? newName) ?\n newName :\n name;\n }\n#endif\n }\n\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n [RequiresUnreferencedCode(\"Requires unreferenced code to instantiate the generic enum converter.\")]\n [RequiresDynamicCode(\"Requires dynamic code to instantiate the generic enum converter.\")]\n public sealed class CustomizableJsonStringEnumConverter : JsonConverterFactory\n {\n /// \n public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum;\n /// \n public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)\n {\n Type converterType = typeof(CustomizableJsonStringEnumConverter<>).MakeGenericType(typeToConvert)!;\n var factory = (JsonConverterFactory)Activator.CreateInstance(converterType)!;\n return factory.CreateConverter(typeToConvert, options);\n }\n }\n}\n\n#if !NET9_0_OR_GREATER\nnamespace System.Text.Json.Serialization\n{\n /// \n /// Determines the custom string value that should be used when serializing an enum member using JSON.\n /// \n /// \n /// This attribute is a temporary workaround for lack of System.Text.Json's support for custom enum member naming\n /// in versions prior to .NET 9. It works together with \n /// to provide customized string representations of enum values during JSON serialization and deserialization.\n /// \n [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\n internal sealed class JsonStringEnumMemberNameAttribute : Attribute\n {\n /// \n /// Creates new attribute instance with a specified enum member name.\n /// \n /// The name to apply to the current enum member when serialized to JSON.\n public JsonStringEnumMemberNameAttribute(string name)\n {\n Name = name;\n }\n\n /// \n /// Gets the custom JSON name of the enum member.\n /// \n public string Name { get; }\n }\n}\n#endif"], ["/csharp-sdk/samples/ChatWithTools/Program.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing OpenAI;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\n\nusing var tracerProvider = Sdk.CreateTracerProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddSource(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var metricsProvider = Sdk.CreateMeterProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddMeter(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var loggerFactory = LoggerFactory.Create(builder => builder.AddOpenTelemetry(opt => opt.AddOtlpExporter()));\n\n// Connect to an MCP server\nConsole.WriteLine(\"Connecting client to MCP 'everything' server\");\n\n// Create OpenAI client (or any other compatible with IChatClient)\n// Provide your own OPENAI_API_KEY via an environment variable.\nvar openAIClient = new OpenAIClient(Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")).GetChatClient(\"gpt-4o-mini\");\n\n// Create a sampling client.\nusing IChatClient samplingClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\nvar mcpClient = await McpClientFactory.CreateAsync(\n new StdioClientTransport(new()\n {\n Command = \"npx\",\n Arguments = [\"-y\", \"--verbose\", \"@modelcontextprotocol/server-everything\"],\n Name = \"Everything\",\n }),\n clientOptions: new()\n {\n Capabilities = new() { Sampling = new() { SamplingHandler = samplingClient.CreateSamplingHandler() } },\n },\n loggerFactory: loggerFactory);\n\n// Get all available tools\nConsole.WriteLine(\"Tools available:\");\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\" {tool}\");\n}\n\nConsole.WriteLine();\n\n// Create an IChatClient that can use the tools.\nusing IChatClient chatClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseFunctionInvocation()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\n// Have a conversation, making all tools available to the LLM.\nList messages = [];\nwhile (true)\n{\n Console.Write(\"Q: \");\n messages.Add(new(ChatRole.User, Console.ReadLine()));\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, new() { Tools = [.. tools] }))\n {\n Console.Write(update);\n updates.Add(update);\n }\n Console.WriteLine();\n\n messages.AddMessages(updates);\n}"], ["/csharp-sdk/src/ModelContextProtocol/McpServerServiceCollectionExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides extension methods for configuring MCP servers with dependency injection.\n/// \npublic static class McpServerServiceCollectionExtensions\n{\n /// \n /// Adds the Model Context Protocol (MCP) server to the service collection with default options.\n /// \n /// The to add the server to.\n /// Optional callback to configure the .\n /// An that can be used to further configure the MCP server.\n\n public static IMcpServerBuilder AddMcpServer(this IServiceCollection services, Action? configureOptions = null)\n {\n services.AddOptions();\n services.TryAddEnumerable(ServiceDescriptor.Transient, McpServerOptionsSetup>());\n if (configureOptions is not null)\n {\n services.Configure(configureOptions);\n }\n\n return new DefaultMcpServerBuilder(services);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AugmentedServiceProvider.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Augments a service provider with additional request-related services.\ninternal sealed class RequestServiceProvider(\n RequestContext request, IServiceProvider? innerServices) :\n IServiceProvider, IKeyedServiceProvider,\n IServiceProviderIsService, IServiceProviderIsKeyedService,\n IDisposable, IAsyncDisposable\n where TRequestParams : RequestParams\n{\n /// Gets the request associated with this instance.\n public RequestContext Request => request;\n\n /// Gets whether the specified type is in the list of additional types this service provider wraps around the one in a provided request's services.\n public static bool IsAugmentedWith(Type serviceType) =>\n serviceType == typeof(RequestContext) ||\n serviceType == typeof(IMcpServer) ||\n serviceType == typeof(IProgress);\n\n /// \n public object? GetService(Type serviceType) =>\n serviceType == typeof(RequestContext) ? request :\n serviceType == typeof(IMcpServer) ? request.Server :\n serviceType == typeof(IProgress) ?\n (request.Params?.ProgressToken is { } progressToken ? new TokenProgress(request.Server, progressToken) : NullProgress.Instance) :\n innerServices?.GetService(serviceType);\n\n /// \n public bool IsService(Type serviceType) =>\n IsAugmentedWith(serviceType) ||\n (innerServices as IServiceProviderIsService)?.IsService(serviceType) is true;\n\n /// \n public bool IsKeyedService(Type serviceType, object? serviceKey) =>\n (serviceKey is null && IsService(serviceType)) ||\n (innerServices as IServiceProviderIsKeyedService)?.IsKeyedService(serviceType, serviceKey) is true;\n\n /// \n public object? GetKeyedService(Type serviceType, object? serviceKey) =>\n serviceKey is null ? GetService(serviceType) :\n (innerServices as IKeyedServiceProvider)?.GetKeyedService(serviceType, serviceKey);\n\n /// \n public object GetRequiredKeyedService(Type serviceType, object? serviceKey) =>\n GetKeyedService(serviceType, serviceKey) ??\n throw new InvalidOperationException($\"No service of type '{serviceType}' with key '{serviceKey}' is registered.\");\n\n /// \n public void Dispose() =>\n (innerServices as IDisposable)?.Dispose();\n\n /// \n public ValueTask DisposeAsync() =>\n innerServices is IAsyncDisposable asyncDisposable ? asyncDisposable.DisposeAsync() : default;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/IMcpEndpoint.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Represents a client or server Model Context Protocol (MCP) endpoint.\n/// \n/// \n/// \n/// The MCP endpoint provides the core communication functionality used by both clients and servers:\n/// \n/// Sending JSON-RPC requests and receiving responses.\n/// Sending notifications to the connected endpoint.\n/// Registering handlers for receiving notifications.\n/// \n/// \n/// \n/// serves as the base interface for both and \n/// interfaces, providing the common functionality needed for MCP protocol \n/// communication. Most applications will use these more specific interfaces rather than working with \n/// directly.\n/// \n/// \n/// All MCP endpoints should be properly disposed after use as they implement .\n/// \n/// \npublic interface IMcpEndpoint : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Sends a JSON-RPC request to the connected endpoint and waits for a response.\n /// \n /// The JSON-RPC request to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the endpoint's response.\n /// The transport is not connected, or another error occurs during request processing.\n /// An error occured during request processing.\n /// \n /// This method provides low-level access to send raw JSON-RPC requests. For most use cases,\n /// consider using the strongly-typed extension methods that provide a more convenient API.\n /// \n Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default);\n\n /// \n /// Sends a JSON-RPC message to the connected endpoint.\n /// \n /// \n /// The JSON-RPC message to send. This can be any type that implements JsonRpcMessage, such as\n /// JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, or JsonRpcError.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// is .\n /// \n /// \n /// This method provides low-level access to send any JSON-RPC message. For specific message types,\n /// consider using the higher-level methods such as or extension methods\n /// like ,\n /// which provide a simpler API.\n /// \n /// \n /// The method will serialize the message and transmit it using the underlying transport mechanism.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n\n /// Registers a handler to be invoked when a notification for the specified method is received.\n /// The notification method.\n /// The handler to be invoked.\n /// An that will remove the registered handler when disposed.\n IAsyncDisposable RegisterNotificationHandler(string method, Func handler);\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Collections/Generic/CollectionExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Collections.Generic;\n\ninternal static class CollectionExtensions\n{\n public static TValue? GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key)\n {\n return dictionary.GetValueOrDefault(key, default!);\n }\n\n public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key, TValue defaultValue)\n {\n Throw.IfNull(dictionary);\n\n return dictionary.TryGetValue(key, out TValue? value) ? value : defaultValue;\n }\n\n public static Dictionary ToDictionary(this IEnumerable> source) =>\n source.ToDictionary(kv => kv.Key, kv => kv.Value);\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StreamClientTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides an implemented around a pair of input/output streams.\n/// \n/// \n/// This transport is useful for scenarios where you already have established streams for communication,\n/// such as custom network protocols, pipe connections, or for testing purposes. It works with any\n/// readable and writable streams.\n/// \npublic sealed class StreamClientTransport : IClientTransport\n{\n private readonly Stream _serverInput;\n private readonly Stream _serverOutput;\n private readonly ILoggerFactory? _loggerFactory;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The stream representing the connected server's input. \n /// Writes to this stream will be sent to the server.\n /// \n /// \n /// The stream representing the connected server's output.\n /// Reads from this stream will receive messages from the server.\n /// \n /// A logger factory for creating loggers.\n public StreamClientTransport(\n Stream serverInput, Stream serverOutput, ILoggerFactory? loggerFactory = null)\n {\n Throw.IfNull(serverInput);\n Throw.IfNull(serverOutput);\n\n _serverInput = serverInput;\n _serverOutput = serverOutput;\n _loggerFactory = loggerFactory;\n }\n\n /// \n public string Name => \"in-memory-stream\";\n\n /// \n public Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n return Task.FromResult(new StreamClientSessionTransport(\n _serverInput,\n _serverOutput,\n encoding: null,\n \"Client (stream)\",\n _loggerFactory));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/SseClientTransportOptions.cs", "using ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class SseClientTransportOptions\n{\n /// \n /// Gets or sets the base address of the server for SSE connections.\n /// \n public required Uri Endpoint\n {\n get;\n set\n {\n if (value is null)\n {\n throw new ArgumentNullException(nameof(value), \"Endpoint cannot be null.\");\n }\n if (!value.IsAbsoluteUri)\n {\n throw new ArgumentException(\"Endpoint must be an absolute URI.\", nameof(value));\n }\n if (value.Scheme != Uri.UriSchemeHttp && value.Scheme != Uri.UriSchemeHttps)\n {\n throw new ArgumentException(\"Endpoint must use HTTP or HTTPS scheme.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the transport mode to use for the connection. Defaults to .\n /// \n /// \n /// \n /// When set to (the default), the client will first attempt to use\n /// Streamable HTTP transport and automatically fall back to SSE transport if the server doesn't support it.\n /// \n /// \n /// Streamable HTTP transport specification.\n /// HTTP with SSE transport specification.\n /// \n /// \n public HttpTransportMode TransportMode { get; set; } = HttpTransportMode.AutoDetect;\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets a timeout used to establish the initial connection to the SSE server. Defaults to 30 seconds.\n /// \n /// \n /// This timeout controls how long the client waits for:\n /// \n /// The initial HTTP connection to be established with the SSE server\n /// The endpoint event to be received, which indicates the message endpoint URL\n /// \n /// If the timeout expires before the connection is established, a will be thrown.\n /// \n public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);\n\n /// \n /// Gets custom HTTP headers to include in requests to the SSE server.\n /// \n /// \n /// Use this property to specify custom HTTP headers that should be sent with each request to the server.\n /// \n public IDictionary? AdditionalHeaders { get; set; }\n\n /// \n /// Gets sor sets the authorization provider to use for authentication.\n /// \n public ClientOAuthOptions? OAuth { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable prompt used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP prompt for use in the server (as opposed\n/// to , which provides the protocol representation of a prompt, and , which\n/// provides a client-side representation of a prompt). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithPromptsFromAssembly and WithPrompts. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to \n/// rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerPrompt : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerPrompt()\n {\n }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolPrompt property represents the underlying prompt definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the prompt's name,\n /// description, and acceptable arguments.\n /// \n public abstract Prompt ProtocolPrompt { get; }\n\n /// \n /// Gets the prompt, rendering it with the provided request parameters and returning the prompt result.\n /// \n /// \n /// The request context containing information about the prompt invocation, including any arguments\n /// passed to the prompt. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the prompt content and messages.\n /// \n /// is .\n /// The prompt implementation returns or an unsupported result type.\n public abstract ValueTask GetAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerPrompt Create(\n MethodInfo method, \n object? target = null,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerPrompt Create(\n AIFunction function,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(function, options);\n\n /// \n public override string ToString() => ProtocolPrompt.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolPrompt.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable resource used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP resource for use in the server (as opposed\n/// to or , which provide the protocol representations of a resource). Instances of \n/// can be added into a to be picked up automatically when\n/// is used to create an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithResourcesFromAssembly and\n/// . The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the URI received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// is used to represent both direct resources (e.g. \"resource://example\") and templated\n/// resources (e.g. \"resource://example/{id}\").\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerResource : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerResource()\n {\n }\n\n /// Gets whether this resource is a URI template with parameters as opposed to a direct resource.\n public bool IsTemplated => ProtocolResourceTemplate.UriTemplate.Contains('{');\n\n /// Gets the protocol type for this instance.\n /// \n /// \n /// The property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n /// \n /// Every valid resource URI is a valid resource URI template, and thus this property always returns an instance.\n /// In contrast, the property may return if the resource template\n /// contains a parameter, in which case the resource template URI is not a valid resource URI.\n /// \n /// \n public abstract ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolResourceTemplate property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n public virtual Resource? ProtocolResource => ProtocolResourceTemplate.AsResource();\n\n /// \n /// Gets the resource, rendering it with the provided request parameters and returning the resource result.\n /// \n /// \n /// The request context containing information about the resource invocation, including any arguments\n /// passed to the resource. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the resource content and messages. If and only if this doesn't match the ,\n /// the method returns .\n /// \n /// is .\n /// The resource implementation returned or an unsupported result type.\n public abstract ValueTask ReadAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerResource Create(\n MethodInfo method, \n object? target = null,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerResource Create(\n AIFunction function,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(function, options);\n\n /// \n public override string ToString() => ProtocolResourceTemplate.UriTemplate;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolResourceTemplate.UriTemplate;\n}\n"], ["/csharp-sdk/samples/EverythingServer/ResourceGenerator.cs", "using ModelContextProtocol.Protocol;\n\nnamespace EverythingServer;\n\nstatic class ResourceGenerator\n{\n private static readonly List _resources = Enumerable.Range(1, 100).Select(i =>\n {\n var uri = $\"test://template/resource/{i}\";\n if (i % 2 != 0)\n {\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"text/plain\",\n Description = $\"Resource {i}: This is a plaintext resource\"\n };\n }\n else\n {\n var buffer = System.Text.Encoding.UTF8.GetBytes($\"Resource {i}: This is a base64 blob\");\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"application/octet-stream\",\n Description = Convert.ToBase64String(buffer)\n };\n }\n }).ToList();\n\n public static IReadOnlyList Resources => _resources;\n}"], ["/csharp-sdk/samples/TestServerWithHosting/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Serilog;\nusing TestServerWithHosting.Tools;\n\nLog.Logger = new LoggerConfiguration()\n .MinimumLevel.Verbose() // Capture all log levels\n .WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"logs\", \"TestServer_.log\"),\n rollingInterval: RollingInterval.Day,\n outputTemplate: \"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}\")\n .WriteTo.Debug()\n .WriteTo.Console(standardErrorFromLevel: Serilog.Events.LogEventLevel.Verbose)\n .CreateLogger();\n\ntry\n{\n Log.Information(\"Starting server...\");\n\n var builder = Host.CreateApplicationBuilder(args);\n builder.Services.AddSerilog();\n builder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools();\n\n var app = builder.Build();\n\n await app.RunAsync();\n return 0;\n}\ncatch (Exception ex)\n{\n Log.Fatal(ex, \"Host terminated unexpectedly\");\n return 1;\n}\nfinally\n{\n Log.CloseAndFlush();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable tool used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP tool for use in the server (as opposed\n/// to , which provides the protocol representation of a tool, and , which\n/// provides a client-side representation of a tool). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithToolsFromAssembly and WithTools. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \npublic abstract class McpServerTool : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerTool()\n {\n }\n\n /// Gets the protocol type for this instance.\n public abstract Tool ProtocolTool { get; }\n\n /// Invokes the .\n /// The request information resulting in the invocation of this tool.\n /// The to monitor for cancellation requests. The default is .\n /// The call response from invoking the tool.\n /// is .\n public abstract ValueTask InvokeAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerTool Create(\n MethodInfo method, \n object? target = null,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerTool Create(\n AIFunction function,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(function, options);\n\n /// \n public override string ToString() => ProtocolTool.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolTool.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/SingleSessionMcpServerHostedService.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Hosted service for a single-session (e.g. stdio) MCP server.\n/// \n/// The server representing the session being hosted.\n/// \n/// The host's application lifetime. If available, it will have termination requested when the session's run completes.\n/// \ninternal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime? lifetime = null) : BackgroundService\n{\n /// \n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n try\n {\n await session.RunAsync(stoppingToken).ConfigureAwait(false);\n }\n finally\n {\n lifetime?.StopApplication();\n }\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/NullableAttributes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n /// Specifies that null is allowed as an input even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class AllowNullAttribute : Attribute;\n\n /// Specifies that null is disallowed as an input even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class DisallowNullAttribute : Attribute;\n\n /// Specifies that an output may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class MaybeNullAttribute : Attribute;\n\n /// Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class NotNullAttribute : Attribute;\n\n /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class MaybeNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter may be null.\n /// \n public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class NotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter will not be null.\n /// \n public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that the output will be non-null if the named parameter is non-null.\n [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]\n internal sealed class NotNullIfNotNullAttribute : Attribute\n {\n /// Initializes the attribute with the associated parameter name.\n /// \n /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.\n /// \n public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;\n\n /// Gets the associated parameter name.\n public string ParameterName { get; }\n }\n\n /// Applied to a method that will never return under any circumstance.\n [AttributeUsage(AttributeTargets.Method, Inherited = false)]\n internal sealed class DoesNotReturnAttribute : Attribute;\n\n /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class DoesNotReturnIfAttribute : Attribute\n {\n /// Initializes the attribute with the specified parameter value.\n /// \n /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to\n /// the associated parameter matches this value.\n /// \n public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;\n\n /// Gets the condition parameter value.\n public bool ParameterValue { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullAttribute : Attribute\n {\n /// Initializes the attribute with a field or property member.\n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullAttribute(string member) => Members = [member];\n\n /// Initializes the attribute with the list of field and property members.\n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullAttribute(params string[] members) => Members = members;\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition and a field or property member.\n /// \n /// The return value condition. If the method returns this value, the associated field or property member will not be null.\n /// \n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, string member)\n {\n ReturnValue = returnValue;\n Members = [member];\n }\n\n /// Initializes the attribute with the specified return value condition and list of field and property members.\n /// \n /// The return value condition. If the method returns this value, the associated field and property members will not be null.\n /// \n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, params string[] members)\n {\n ReturnValue = returnValue;\n Members = members;\n }\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n}\n#endif"], ["/csharp-sdk/samples/ProtectedMCPServer/Program.cs", "using Microsoft.AspNetCore.Authentication.JwtBearer;\nusing Microsoft.IdentityModel.Tokens;\nusing ModelContextProtocol.AspNetCore.Authentication;\nusing ProtectedMCPServer.Tools;\nusing System.Net.Http.Headers;\nusing System.Security.Claims;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nvar serverUrl = \"http://localhost:7071/\";\nvar inMemoryOAuthServerUrl = \"https://localhost:7029\";\n\nbuilder.Services.AddAuthentication(options =>\n{\n options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;\n options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;\n})\n.AddJwtBearer(options =>\n{\n // Configure to validate tokens from our in-memory OAuth server\n options.Authority = inMemoryOAuthServerUrl;\n options.TokenValidationParameters = new TokenValidationParameters\n {\n ValidateIssuer = true,\n ValidateAudience = true,\n ValidateLifetime = true,\n ValidateIssuerSigningKey = true,\n ValidAudience = serverUrl, // Validate that the audience matches the resource metadata as suggested in RFC 8707\n ValidIssuer = inMemoryOAuthServerUrl,\n NameClaimType = \"name\",\n RoleClaimType = \"roles\"\n };\n\n options.Events = new JwtBearerEvents\n {\n OnTokenValidated = context =>\n {\n var name = context.Principal?.Identity?.Name ?? \"unknown\";\n var email = context.Principal?.FindFirstValue(\"preferred_username\") ?? \"unknown\";\n Console.WriteLine($\"Token validated for: {name} ({email})\");\n return Task.CompletedTask;\n },\n OnAuthenticationFailed = context =>\n {\n Console.WriteLine($\"Authentication failed: {context.Exception.Message}\");\n return Task.CompletedTask;\n },\n OnChallenge = context =>\n {\n Console.WriteLine($\"Challenging client to authenticate with Entra ID\");\n return Task.CompletedTask;\n }\n };\n})\n.AddMcp(options =>\n{\n options.ResourceMetadata = new()\n {\n Resource = new Uri(serverUrl),\n ResourceDocumentation = new Uri(\"https://docs.example.com/api/weather\"),\n AuthorizationServers = { new Uri(inMemoryOAuthServerUrl) },\n ScopesSupported = [\"mcp:tools\"],\n };\n});\n\nbuilder.Services.AddAuthorization();\n\nbuilder.Services.AddHttpContextAccessor();\nbuilder.Services.AddMcpServer()\n .WithTools()\n .WithHttpTransport();\n\n// Configure HttpClientFactory for weather.gov API\nbuilder.Services.AddHttpClient(\"WeatherApi\", client =>\n{\n client.BaseAddress = new Uri(\"https://api.weather.gov\");\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n});\n\nvar app = builder.Build();\n\napp.UseAuthentication();\napp.UseAuthorization();\n\n// Use the default MCP policy name that we've configured\napp.MapMcp().RequireAuthorization();\n\nConsole.WriteLine($\"Starting MCP server with authorization at {serverUrl}\");\nConsole.WriteLine($\"Using in-memory OAuth server at {inMemoryOAuthServerUrl}\");\nConsole.WriteLine($\"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource\");\nConsole.WriteLine(\"Press Ctrl+C to stop the server\");\n\napp.Run(serverUrl);\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for all request parameters.\n/// \n/// \n/// See the schema for details.\n/// \npublic abstract class RequestParams\n{\n /// Prevent external derivations.\n private protected RequestParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n [JsonIgnore]\n public ProgressToken? ProgressToken\n {\n get\n {\n if (Meta?[\"progressToken\"] is JsonValue progressToken)\n {\n if (progressToken.TryGetValue(out string? stringValue))\n {\n return new ProgressToken(stringValue);\n }\n\n if (progressToken.TryGetValue(out long longValue))\n {\n return new ProgressToken(longValue);\n }\n }\n\n return null;\n }\n set\n {\n if (value is null)\n {\n Meta?.Remove(\"progressToken\");\n }\n else\n {\n (Meta ??= [])[\"progressToken\"] = value.Value.Token switch\n {\n string s => JsonValue.Create(s),\n long l => JsonValue.Create(l),\n _ => throw new InvalidOperationException(\"ProgressToken must be a string or a long.\")\n };\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerOptionsSetup.cs", "using Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Configures the McpServerOptions using addition services from DI.\n/// \n/// The server handlers configuration options.\n/// Tools individually registered.\n/// Prompts individually registered.\n/// Resources individually registered.\ninternal sealed class McpServerOptionsSetup(\n IOptions serverHandlers,\n IEnumerable serverTools,\n IEnumerable serverPrompts,\n IEnumerable serverResources) : IConfigureOptions\n{\n /// \n /// Configures the given McpServerOptions instance by setting server information\n /// and applying custom server handlers and tools.\n /// \n /// The options instance to be configured.\n public void Configure(McpServerOptions options)\n {\n Throw.IfNull(options);\n\n // Collect all of the provided tools into a tools collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection toolCollection = options.Capabilities?.Tools?.ToolCollection ?? [];\n foreach (var tool in serverTools)\n {\n toolCollection.TryAdd(tool);\n }\n\n if (!toolCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Tools ??= new();\n options.Capabilities.Tools.ToolCollection = toolCollection;\n }\n\n // Collect all of the provided prompts into a prompts collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection promptCollection = options.Capabilities?.Prompts?.PromptCollection ?? [];\n foreach (var prompt in serverPrompts)\n {\n promptCollection.TryAdd(prompt);\n }\n\n if (!promptCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Prompts ??= new();\n options.Capabilities.Prompts.PromptCollection = promptCollection;\n }\n\n // Collect all of the provided resources into a resources collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerResourceCollection resourceCollection = options.Capabilities?.Resources?.ResourceCollection ?? [];\n foreach (var resource in serverResources)\n {\n resourceCollection.TryAdd(resource);\n }\n\n if (!resourceCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Resources ??= new();\n options.Capabilities.Resources.ResourceCollection = resourceCollection;\n }\n\n // Apply custom server handlers.\n serverHandlers.Value.OverwriteWithSetHandlers(options);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationExtensions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.AspNetCore.Authentication;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Extension methods for adding MCP authorization support to ASP.NET Core applications.\n/// \npublic static class McpAuthenticationExtensions\n{\n /// \n /// Adds MCP authorization support to the application.\n /// \n /// The authentication builder.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n Action? configureOptions = null)\n {\n return AddMcp(\n builder,\n McpAuthenticationDefaults.AuthenticationScheme,\n McpAuthenticationDefaults.DisplayName,\n configureOptions);\n }\n\n /// \n /// Adds MCP authorization support to the application with a custom scheme name.\n /// \n /// The authentication builder.\n /// The authentication scheme name to use.\n /// The display name for the authentication scheme.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n string authenticationScheme,\n string displayName,\n Action? configureOptions = null)\n {\n return builder.AddScheme(\n authenticationScheme,\n displayName,\n configureOptions);\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Prompts/ComplexPromptType.cs", "using EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class ComplexPromptType\n{\n [McpServerPrompt(Name = \"complex_prompt\"), Description(\"A prompt with arguments\")]\n public static IEnumerable ComplexPrompt(\n [Description(\"Temperature setting\")] int temperature,\n [Description(\"Output style\")] string? style = null)\n {\n return [\n new ChatMessage(ChatRole.User,$\"This is a complex prompt with arguments: temperature={temperature}, style={style}\"),\n new ChatMessage(ChatRole.Assistant, \"I understand. You've provided a complex prompt with temperature and style arguments. How would you like me to proceed?\"),\n new ChatMessage(ChatRole.User, [new DataContent(TinyImageTool.MCP_TINY_IMAGE)])\n ];\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourcesCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the resources capability configuration.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ResourcesCapability\n{\n /// \n /// Gets or sets whether this server supports subscribing to resource updates.\n /// \n [JsonPropertyName(\"subscribe\")]\n public bool? Subscribe { get; set; }\n\n /// \n /// Gets or sets whether this server supports notifications for changes to the resource list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when resources are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their resource cache.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is called when clients request available resource templates that can be used\n /// to create resources within the Model Context Protocol server.\n /// Resource templates define the structure and URI patterns for resources accessible in the system,\n /// allowing clients to discover available resource types and their access patterns.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler responds to client requests for available resources and returns information about resources accessible through the server.\n /// The implementation should return a with the matching resources.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is responsible for retrieving the content of a specific resource identified by its URI in the Model Context Protocol.\n /// When a client sends a resources/read request, this handler is invoked with the resource URI.\n /// The handler should implement logic to locate and retrieve the requested resource, then return\n /// its contents in a ReadResourceResult object.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be subscribed to. The implementation should register the client's interest in receiving updates\n /// for the specified resource.\n /// Subscriptions allow clients to receive real-time notifications when resources change, without\n /// requiring polling.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be unsubscribed from. The implementation should remove the client's registration for receiving updates\n /// about the specified resource.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets a collection of resources served by the server.\n /// \n /// \n /// \n /// Resources specified via augment the , \n /// and handlers, if provided. Resources with template expressions in their URI templates are considered resource templates\n /// and are listed via ListResourceTemplate, whereas resources without template parameters are considered static resources and are listed with ListResources.\n /// \n /// \n /// ReadResource requests will first check the for the exact resource being requested. If no match is found, they'll proceed to\n /// try to match the resource against each resource template in . If no match is still found, the request will fall back to\n /// any handler registered for .\n /// \n /// \n [JsonIgnore]\n public McpServerResourceCollection? ResourceCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationOptions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Options for the MCP authentication handler.\n/// \npublic class McpAuthenticationOptions : AuthenticationSchemeOptions\n{\n private static readonly Uri DefaultResourceMetadataUri = new(\"/.well-known/oauth-protected-resource\", UriKind.Relative);\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationOptions()\n {\n // \"Bearer\" is JwtBearerDefaults.AuthenticationScheme, but we don't have a reference to the JwtBearer package here.\n ForwardAuthenticate = \"Bearer\";\n ResourceMetadataUri = DefaultResourceMetadataUri;\n Events = new McpAuthenticationEvents();\n }\n\n /// \n /// Gets or sets the events used to handle authentication events.\n /// \n public new McpAuthenticationEvents Events\n {\n get { return (McpAuthenticationEvents)base.Events!; }\n set { base.Events = value; }\n }\n\n /// \n /// The URI to the resource metadata document.\n /// \n /// \n /// This URI will be included in the WWW-Authenticate header when a 401 response is returned.\n /// \n public Uri ResourceMetadataUri { get; set; }\n\n /// \n /// Gets or sets the protected resource metadata.\n /// \n /// \n /// This contains the OAuth metadata for the protected resource, including authorization servers,\n /// supported scopes, and other information needed for clients to authenticate.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CompilerFeatureRequiredAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Indicates that compiler support for a particular feature is required for the location where this attribute is applied.\n /// \n [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]\n internal sealed class CompilerFeatureRequiredAttribute : Attribute\n {\n public CompilerFeatureRequiredAttribute(string featureName)\n {\n FeatureName = featureName;\n }\n\n /// \n /// The name of the compiler feature.\n /// \n public string FeatureName { get; }\n\n /// \n /// If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand .\n /// \n public bool IsOptional { get; init; }\n\n /// \n /// The used for the required members C# feature.\n /// \n public const string RequiredMembers = nameof(RequiredMembers);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/TokenProgress.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides an tied to a specific progress token and that will issue\n/// progress notifications on the supplied endpoint.\n/// \ninternal sealed class TokenProgress(IMcpEndpoint endpoint, ProgressToken progressToken) : IProgress\n{\n /// \n public void Report(ProgressNotificationValue value)\n {\n _ = endpoint.NotifyProgressAsync(progressToken, value, CancellationToken.None);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ClientCapabilities.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a client may support.\n/// \n/// \n/// \n/// Capabilities define the features and functionality that a client can handle when communicating with an MCP server.\n/// These are advertised to the server during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ClientCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the client supports.\n /// \n /// \n /// \n /// The dictionary allows clients to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Servers should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets the client's roots capability, which are entry points for resource navigation.\n /// \n /// \n /// \n /// When is non-, the client indicates that it can respond to \n /// server requests for listing root URIs. Root URIs serve as entry points for resource navigation in the protocol.\n /// \n /// \n /// The server can use to request the list of\n /// available roots from the client, which will trigger the client's .\n /// \n /// \n [JsonPropertyName(\"roots\")]\n public RootsCapability? Roots { get; set; }\n\n /// \n /// Gets or sets the client's sampling capability, which indicates whether the client \n /// supports issuing requests to an LLM on behalf of the server.\n /// \n [JsonPropertyName(\"sampling\")]\n public SamplingCapability? Sampling { get; set; }\n\n /// \n /// Gets or sets the client's elicitation capability, which indicates whether the client \n /// supports elicitation of additional information from the user on behalf of the server.\n /// \n [JsonPropertyName(\"elicitation\")]\n public ElicitationCapability? Elicitation { get; set; }\n\n /// Gets or sets notification handlers to register with the client.\n /// \n /// \n /// When constructed, the client will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The client will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the client to respond to server-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the client for the lifetime of the client.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceTemplate.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource template that the server is capable of reading.\n/// \n/// \n/// Resource templates provide metadata about resources available on the server,\n/// including how to construct URIs for those resources.\n/// \npublic sealed class ResourceTemplate : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI template (according to RFC 6570) that can be used to construct resource URIs.\n /// \n [JsonPropertyName(\"uriTemplate\")]\n public required string UriTemplate { get; init; }\n\n /// \n /// Gets or sets a description of what this resource template represents.\n /// \n /// \n /// \n /// This description helps clients understand the purpose and content of resources\n /// that can be generated from this template. It can be used by client applications\n /// to provide context about available resource types or to display in user interfaces.\n /// \n /// \n /// For AI models, this description can serve as a hint about when and how to use\n /// the resource template, enhancing the model's ability to generate appropriate URIs.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource template, if known.\n /// \n /// \n /// \n /// Specifies the expected format of resources that can be generated from this template.\n /// This helps clients understand what type of content to expect when accessing resources\n /// created using this template.\n /// \n /// \n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, or \"application/json\" for JSON data.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource template.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource template. Clients can use this information to filter\n /// or prioritize resource templates for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n\n /// Gets whether contains any template expressions.\n [JsonIgnore]\n public bool IsTemplated => UriTemplate.Contains('{');\n\n /// Converts the into a .\n /// A if is ; otherwise, .\n public Resource? AsResource()\n {\n if (IsTemplated)\n {\n return null;\n }\n\n return new()\n {\n Uri = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n Annotations = Annotations,\n Meta = Meta,\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcRequest.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A request message in the JSON-RPC protocol.\n/// \n/// \n/// Requests are messages that require a response from the receiver. Each request includes a unique ID\n/// that will be included in the corresponding response message (either a success response or an error).\n/// \n/// The receiver of a request message is expected to execute the specified method with the provided parameters\n/// and return either a with the result, or a \n/// if the method execution fails.\n/// \npublic sealed class JsonRpcRequest : JsonRpcMessageWithId\n{\n /// \n /// Name of the method to invoke.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Optional parameters for the method.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n\n internal JsonRpcRequest WithId(RequestId id)\n {\n return new JsonRpcRequest\n {\n JsonRpc = JsonRpc,\n Id = id,\n Method = Method,\n Params = Params,\n RelatedTransport = RelatedTransport,\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientTransportOptions.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class StdioClientTransportOptions\n{\n /// \n /// Gets or sets the command to execute to start the server process.\n /// \n public required string Command\n {\n get;\n set\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Command cannot be null or empty.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the arguments to pass to the server process when it is started.\n /// \n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the working directory for the server process.\n /// \n public string? WorkingDirectory { get; set; }\n\n /// \n /// Gets or sets environment variables to set for the server process.\n /// \n /// \n /// \n /// This property allows you to specify environment variables that will be set in the server process's\n /// environment. This is useful for passing configuration, authentication information, or runtime flags\n /// to the server without modifying its code.\n /// \n /// \n /// By default, when starting the server process, the server process will inherit the current environment's variables,\n /// as discovered via . After those variables are found, the entries\n /// in this dictionary are used to augment and overwrite the entries read from the environment.\n /// That includes removing the variables for any of this collection's entries with a null value.\n /// \n /// \n public IDictionary? EnvironmentVariables { get; set; }\n\n /// \n /// Gets or sets the timeout to wait for the server to shut down gracefully.\n /// \n /// \n /// \n /// This property dictates how long the client should wait for the server process to exit cleanly during shutdown\n /// before forcibly terminating it. This balances between giving the server enough time to clean up \n /// resources and not hanging indefinitely if a server process becomes unresponsive.\n /// \n /// \n /// The default is five seconds.\n /// \n /// \n public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5);\n\n /// \n /// Gets or sets a callback that is invoked for each line of stderr received from the server process.\n /// \n public Action? StandardErrorLines { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerFactory.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a factory for creating instances.\n/// \n/// \n/// This is the recommended way to create instances.\n/// The factory handles proper initialization of server instances with the required dependencies.\n/// \npublic static class McpServerFactory\n{\n /// \n /// Creates a new instance of an .\n /// \n /// Transport to use for the server representing an already-established MCP session.\n /// Configuration options for this server, including capabilities. \n /// Logger factory to use for logging. If null, logging will be disabled.\n /// Optional service provider to create new instances of tools and other dependencies.\n /// An instance that should be disposed when no longer needed.\n /// is .\n /// is .\n public static IMcpServer Create(\n ITransport transport,\n McpServerOptions serverOptions,\n ILoggerFactory? loggerFactory = null,\n IServiceProvider? serviceProvider = null)\n {\n Throw.IfNull(transport);\n Throw.IfNull(serverOptions);\n\n return new McpServer(transport, serverOptions, loggerFactory, serviceProvider);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/RequestContext.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Provides a context container that provides access to the client request parameters and resources for the request.\n/// \n/// Type of the request parameters specific to each MCP operation.\n/// \n/// The encapsulates all contextual information for handling an MCP request.\n/// This type is typically received as a parameter in handler delegates registered with IMcpServerBuilder,\n/// and may be injected as parameters into s.\n/// \npublic sealed class RequestContext\n{\n /// The server with which this instance is associated.\n private IMcpServer _server;\n\n /// \n /// Initializes a new instance of the class with the specified server.\n /// \n /// The server with which this instance is associated.\n public RequestContext(IMcpServer server)\n {\n Throw.IfNull(server);\n\n _server = server;\n Services = server.Services;\n }\n\n /// Gets or sets the server with which this instance is associated.\n public IMcpServer Server \n {\n get => _server;\n set\n {\n Throw.IfNull(value);\n _server = value;\n }\n }\n\n /// Gets or sets the services associated with this request.\n /// \n /// This may not be the same instance stored in \n /// if was true, in which case this\n /// might be a scoped derived from the server's\n /// .\n /// \n public IServiceProvider? Services { get; set; }\n\n /// Gets or sets the parameters associated with this request.\n public TParams? Params { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's capability to provide predefined prompt templates that clients can use.\n/// \n/// \n/// \n/// The prompts capability allows a server to expose a collection of predefined prompt templates that clients\n/// can discover and use. These prompts can be static (defined in the ) or\n/// dynamically generated through handlers.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the prompt list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when prompts are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their prompt cache. This capability enables clients to stay synchronized with server-side changes \n /// to available prompts.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests a list of available prompts from the server\n /// via a request. Results from this handler are returned\n /// along with any prompts defined in .\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt by name and provides arguments \n /// for the prompt if needed. The handler receives the request context containing the prompt name and any arguments, \n /// and should return a with the prompt messages and other details.\n /// \n /// \n /// This handler will be invoked if the requested prompt name is not found in the ,\n /// allowing for dynamic prompt generation or retrieval from external sources.\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets a collection of prompts that will be served by the server.\n /// \n /// \n /// \n /// The contains the predefined prompts that clients can request from the server.\n /// This collection works in conjunction with and \n /// when those are provided:\n /// \n /// \n /// - For requests: The server returns all prompts from this collection \n /// plus any additional prompts provided by the if it's set.\n /// \n /// \n /// - For requests: The server first checks this collection for the requested prompt.\n /// If not found, it will invoke the as a fallback if one is set.\n /// \n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? PromptCollection { get; set; }\n}"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/DefaultMcpServerBuilder.cs", "using ModelContextProtocol;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Default implementation of that enables fluent configuration\n/// of the Model Context Protocol (MCP) server. This builder is returned by the\n/// extension method and\n/// provides access to the service collection for registering additional MCP components.\n/// \ninternal sealed class DefaultMcpServerBuilder : IMcpServerBuilder\n{\n /// \n public IServiceCollection Services { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service collection to which MCP server services will be added. This collection\n /// is exposed through the property to allow additional configuration.\n /// Thrown when is null.\n public DefaultMcpServerBuilder(IServiceCollection services)\n {\n Throw.IfNull(services);\n\n Services = services;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the tools capability configuration.\n/// See the schema for details.\n/// \npublic sealed class ToolsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the tool list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when tools are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their tool cache. This capability enables clients to stay synchronized with server-side \n /// changes to available tools.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// When used in conjunction with , both the tools from this handler\n /// and the tools from the collection will be combined to form the complete list of available tools.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the .\n /// The handler should implement logic to execute the requested tool and return appropriate results. \n /// It receives a containing information about the tool \n /// being called and its arguments, and should return a with the execution results.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets a collection of tools served by the server.\n /// \n /// \n /// Tools will specified via augment the and\n /// , if provided. ListTools requests will output information about every tool\n /// in and then also any tools output by , if it's\n /// non-. CallTool requests will first check for the tool\n /// being requested, and if the tool is not found in the , any specified \n /// will be invoked as a fallback.\n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? ToolCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ServerCapabilities.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a server may support.\n/// \n/// \n/// \n/// Server capabilities define the features and functionality available when clients connect.\n/// These capabilities are advertised to clients during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ServerCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the server supports.\n /// \n /// \n /// \n /// The dictionary allows servers to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Clients should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets a server's logging capability, supporting sending log messages to the client.\n /// \n [JsonPropertyName(\"logging\")]\n public LoggingCapability? Logging { get; set; }\n\n /// \n /// Gets or sets a server's prompts capability for serving predefined prompt templates that clients can discover and use.\n /// \n [JsonPropertyName(\"prompts\")]\n public PromptsCapability? Prompts { get; set; }\n\n /// \n /// Gets or sets a server's resources capability for serving predefined resources that clients can discover and use.\n /// \n [JsonPropertyName(\"resources\")]\n public ResourcesCapability? Resources { get; set; }\n\n /// \n /// Gets or sets a server's tools capability for listing tools that a client is able to invoke.\n /// \n [JsonPropertyName(\"tools\")]\n public ToolsCapability? Tools { get; set; }\n\n /// \n /// Gets or sets a server's completions capability for supporting argument auto-completion suggestions.\n /// \n [JsonPropertyName(\"completions\")]\n public CompletionsCapability? Completions { get; set; }\n\n /// Gets or sets notification handlers to register with the server.\n /// \n /// \n /// When constructed, the server will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The server will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the server to respond to client-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the server for the lifetime of the server.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Tool.cs", "using System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a tool that the server is capable of calling.\n/// \npublic sealed class Tool : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the tool.\n /// \n /// \n /// \n /// This description helps the AI model understand what the tool does and when to use it.\n /// It should be clear, concise, and accurately describe the tool's purpose and functionality.\n /// \n /// \n /// The description is typically presented to AI models to help them determine when\n /// and how to use the tool based on user requests.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a JSON Schema object defining the expected parameters for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema typically defines the properties (parameters) that the tool accepts, \n /// their types, and which ones are required. This helps AI models understand\n /// how to structure their calls to the tool.\n /// \n /// \n /// If not explicitly set, a default minimal schema of {\"type\":\"object\"} is used.\n /// \n /// \n [JsonPropertyName(\"inputSchema\")]\n public JsonElement InputSchema \n { \n get => field; \n set\n {\n if (!McpJsonUtilities.IsValidMcpToolSchema(value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool input JSON schema.\", nameof(InputSchema));\n }\n\n field = value;\n }\n\n } = McpJsonUtilities.DefaultMcpToolSchema;\n\n /// \n /// Gets or sets a JSON Schema object defining the expected structured outputs for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema should describe the shape of the data as returned in .\n /// \n /// \n [JsonPropertyName(\"outputSchema\")]\n public JsonElement? OutputSchema\n {\n get => field;\n set\n {\n if (value is not null && !McpJsonUtilities.IsValidMcpToolSchema(value.Value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool output JSON schema.\", nameof(OutputSchema));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets optional additional tool information and behavior hints.\n /// \n /// \n /// These annotations provide metadata about the tool's behavior, such as whether it's read-only,\n /// destructive, idempotent, or operates in an open world. They also can include a human-readable title.\n /// Note that these are hints and should not be relied upon for security decisions.\n /// \n [JsonPropertyName(\"annotations\")]\n public ToolAnnotations? Annotations { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingCapability.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Client;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to generate text or other content using an AI model.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to sampling requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to generate content\n/// using an AI model. The client must set a to process these requests.\n/// \n/// \npublic sealed class SamplingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to generate content\n /// using an AI model. The client must set this property for the sampling capability to work.\n /// \n /// \n /// The handler receives message parameters, a progress reporter for updates, and a \n /// cancellation token. It should return a containing the \n /// generated content.\n /// \n /// \n /// You can create a handler using the extension\n /// method with any implementation of .\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SamplingHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompletionsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the completions capability for providing auto-completion suggestions\n/// for prompt arguments and resource references.\n/// \n/// \n/// \n/// When enabled, this capability allows a Model Context Protocol server to provide \n/// auto-completion suggestions. This capability is advertised to clients during the initialize handshake.\n/// \n/// \n/// The primary function of this capability is to improve the user experience by offering\n/// contextual suggestions for argument values or resource identifiers based on partial input.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompletionsCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for completion requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler receives a reference type (e.g., \"ref/prompt\" or \"ref/resource\") and the current argument value,\n /// and should return appropriate completion suggestions.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as tools in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as tools that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to when the tool is invoked rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided when the tool is invoked rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerToolAttribute : Attribute\n{\n // Defaults based on the spec\n private const bool DestructiveDefault = true;\n private const bool IdempotentDefault = false;\n private const bool OpenWorldDefault = true;\n private const bool ReadOnlyDefault = false;\n\n // Nullable backing fields so we can distinguish\n internal bool? _destructive;\n internal bool? _idempotent;\n internal bool? _openWorld;\n internal bool? _readOnly;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerToolAttribute()\n {\n }\n\n /// Gets the name of the tool.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Destructive \n {\n get => _destructive ?? DestructiveDefault; \n set => _destructive = value; \n }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Idempotent \n {\n get => _idempotent ?? IdempotentDefault;\n set => _idempotent = value; \n }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool OpenWorld\n {\n get => _openWorld ?? OpenWorldDefault; \n set => _openWorld = value; \n }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool ReadOnly \n {\n get => _readOnly ?? ReadOnlyDefault; \n set => _readOnly = value; \n }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/UnconditionalSuppressMessageAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a\n/// single code artifact.\n/// \n/// \n/// is different than\n/// in that it doesn't have a\n/// . So it is always preserved in the compiled assembly.\n/// \n[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\ninternal sealed class UnconditionalSuppressMessageAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the \n /// class, specifying the category of the tool and the identifier for an analysis rule.\n /// \n /// The category for the attribute.\n /// The identifier of the analysis rule the attribute applies to.\n public UnconditionalSuppressMessageAttribute(string category, string checkId)\n {\n Category = category;\n CheckId = checkId;\n }\n\n /// \n /// Gets the category identifying the classification of the attribute.\n /// \n /// \n /// The property describes the tool or tool analysis category\n /// for which a message suppression attribute applies.\n /// \n public string Category { get; }\n\n /// \n /// Gets the identifier of the analysis tool rule to be suppressed.\n /// \n /// \n /// Concatenated together, the and \n /// properties form a unique check identifier.\n /// \n public string CheckId { get; }\n\n /// \n /// Gets or sets the scope of the code that is relevant for the attribute.\n /// \n /// \n /// The Scope property is an optional argument that specifies the metadata scope for which\n /// the attribute is relevant.\n /// \n public string? Scope { get; set; }\n\n /// \n /// Gets or sets a fully qualified path that represents the target of the attribute.\n /// \n /// \n /// The property is an optional argument identifying the analysis target\n /// of the attribute. An example value is \"System.IO.Stream.ctor():System.Void\".\n /// Because it is fully qualified, it can be long, particularly for targets such as parameters.\n /// The analysis tool user interface should be capable of automatically formatting the parameter.\n /// \n public string? Target { get; set; }\n\n /// \n /// Gets or sets an optional argument expanding on exclusion criteria.\n /// \n /// \n /// The property is an optional argument that specifies additional\n /// exclusion where the literal metadata target is not sufficiently precise. For example,\n /// the cannot be applied within a method,\n /// and it may be desirable to suppress a violation against a statement in the method that will\n /// give a rule violation, but not against all statements in the method.\n /// \n public string? MessageId { get; set; }\n\n /// \n /// Gets or sets the justification for suppressing the code analysis message.\n /// \n public string? Justification { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpServerTransportOptions.cs", "using Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\n/// \n/// Configuration options for .\n/// which implements the Streaming HTTP transport for the Model Context Protocol.\n/// See the protocol specification for details on the Streamable HTTP transport. \n/// \npublic class HttpServerTransportOptions\n{\n /// \n /// Gets or sets an optional asynchronous callback to configure per-session \n /// with access to the of the request that initiated the session.\n /// \n public Func? ConfigureSessionOptions { get; set; }\n\n /// \n /// Gets or sets an optional asynchronous callback for running new MCP sessions manually.\n /// This is useful for running logic before a sessions starts and after it completes.\n /// \n public Func? RunSessionHandler { get; set; }\n\n /// \n /// Gets or sets whether the server should run in a stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process.\n /// \n /// \n /// If , the \"/sse\" endpoint will be disabled, and client information will be round-tripped as part\n /// of the \"MCP-Session-Id\" header instead of stored in memory. Unsolicited server-to-client messages and all server-to-client\n /// requests are also unsupported, because any responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// Defaults to .\n /// \n public bool Stateless { get; set; }\n\n /// \n /// Gets or sets whether the server should use a single execution context for the entire session.\n /// If , handlers like tools get called with the \n /// belonging to the corresponding HTTP request which can change throughout the MCP session.\n /// If , handlers will get called with the same \n /// used to call and .\n /// \n /// \n /// Enabling a per-session can be useful for setting variables\n /// that persist for the entire session, but it prevents you from using IHttpContextAccessor in handlers.\n /// Defaults to .\n /// \n public bool PerSessionExecutionContext { get; set; }\n\n /// \n /// Gets or sets the duration of time the server will wait between any active requests before timing out an MCP session.\n /// \n /// \n /// This is checked in background every 5 seconds. A client trying to resume a session will receive a 404 status code\n /// and should restart their session. A client can keep their session open by keeping a GET request open.\n /// Defaults to 2 hours.\n /// \n public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromHours(2);\n\n /// \n /// Gets or sets maximum number of idle sessions to track in memory. This is used to limit the number of sessions that can be idle at once.\n /// \n /// \n /// Past this limit, the server will log a critical error and terminate the oldest idle sessions even if they have not reached\n /// their until the idle session count is below this limit. Clients that keep their session open by\n /// keeping a GET request open will not count towards this limit.\n /// Defaults to 100,000 sessions.\n /// \n public int MaxIdleSessionCount { get; set; } = 100_000;\n\n /// \n /// Used for testing the .\n /// \n public TimeProvider TimeProvider { get; set; } = TimeProvider.System;\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/PrintEnvTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class PrintEnvTool\n{\n private static readonly JsonSerializerOptions options = new()\n {\n WriteIndented = true\n };\n\n [McpServerTool(Name = \"printEnv\"), Description(\"Prints all environment variables, helpful for debugging MCP server configuration\")]\n public static string PrintEnv() =>\n JsonSerializer.Serialize(Environment.GetEnvironmentVariables(), options);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitationCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to provide server-requested additional information during interactions.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to elicitation requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to provide additional information\n/// during interactions. The client must set a to process these requests.\n/// \n/// \npublic sealed class ElicitationCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to provide additional\n /// information during interactions. The client must set this property for the elicitation capability to work.\n /// \n /// \n /// The handler receives message parameters and a cancellation token.\n /// It should return a containing the response to the elicitation request.\n /// \n /// \n [JsonIgnore]\n public Func>? ElicitationHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/NopProgress.cs", "namespace ModelContextProtocol;\n\n/// Provides an that's a nop.\ninternal sealed class NullProgress : IProgress\n{\n /// \n /// Gets the singleton instance of the class that performs no operations when progress is reported.\n /// \n /// \n /// Use this property when you need to provide an implementation \n /// but don't need to track or report actual progress.\n /// \n public static NullProgress Instance { get; } = new();\n\n /// \n public void Report(ProgressNotificationValue value)\n {\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the logging capability configuration for a Model Context Protocol server.\n/// \n/// \n/// This capability allows clients to set the logging level and receive log messages from the server.\n/// See the schema for details.\n/// \npublic sealed class LoggingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for set logging level requests from clients.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptMessage.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message within the Model Context Protocol (MCP) system, used for communication between clients and AI models.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be\n/// text, images, audio, or embedded resources.\n/// \n/// \n/// This class is similar to , but with enhanced support for embedding resources from the MCP server.\n/// It serves as a core data structure in the MCP message exchange flow, particularly in prompt formation and model responses.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent complete conversations or prompt sequences. They can be converted to and from \n/// objects using the extension methods and\n/// .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptMessage\n{\n /// \n /// Gets or sets the content of the message, which can be text, image, audio, or an embedded resource.\n /// \n /// \n /// The object contains all the message payload, whether it's simple text,\n /// base64-encoded binary data (for images/audio), or a reference to an embedded resource.\n /// The property indicates the specific content type.\n /// \n [JsonPropertyName(\"content\")]\n public ContentBlock Content { get; set; } = new TextContentBlock { Text = \"\" };\n\n /// \n /// Gets or sets the role of the message sender, specifying whether it's from a \"user\" or an \"assistant\".\n /// \n /// \n /// In the Model Context Protocol, each message must have a clear role assignment to maintain\n /// the conversation flow. User messages represent queries or inputs from users, while assistant\n /// messages represent responses generated by AI models.\n /// \n [JsonPropertyName(\"role\")]\n public Role Role { get; set; } = Role.User;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client capability that enables root resource discovery in the Model Context Protocol.\n/// \n/// \n/// \n/// When present in , it indicates that the client supports listing\n/// root URIs that serve as entry points for resource navigation.\n/// \n/// \n/// The roots capability establishes a mechanism for servers to discover and access the hierarchical \n/// structure of resources provided by a client. Root URIs represent top-level entry points from which\n/// servers can navigate to access specific resources.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsCapability\n{\n /// \n /// Gets or sets whether the client supports notifications for changes to the roots list.\n /// \n /// \n /// When set to , the client can notify servers when roots are added, \n /// removed, or modified, allowing servers to refresh their roots cache accordingly.\n /// This enables servers to stay synchronized with client-side changes to available roots.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client sends a request to retrieve available roots.\n /// The handler receives request parameters and should return a containing the collection of available roots.\n /// \n [JsonIgnore]\n public Func>? RootsHandler { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/StringSyntaxAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// Specifies the syntax used in a string.\n[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\ninternal sealed class StringSyntaxAttribute : Attribute\n{\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n public StringSyntaxAttribute(string syntax)\n {\n Syntax = syntax;\n Arguments = Array.Empty();\n }\n\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n /// Optional arguments associated with the specific syntax employed.\n public StringSyntaxAttribute(string syntax, params object?[] arguments)\n {\n Syntax = syntax;\n Arguments = arguments;\n }\n\n /// Gets the identifier of the syntax used.\n public string Syntax { get; }\n\n /// Optional arguments associated with the specific syntax employed.\n public object?[] Arguments { get; }\n\n /// The syntax identifier for strings containing composite formats for string formatting.\n public const string CompositeFormat = nameof(CompositeFormat);\n\n /// The syntax identifier for strings containing date format specifiers.\n public const string DateOnlyFormat = nameof(DateOnlyFormat);\n\n /// The syntax identifier for strings containing date and time format specifiers.\n public const string DateTimeFormat = nameof(DateTimeFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string EnumFormat = nameof(EnumFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string GuidFormat = nameof(GuidFormat);\n\n /// The syntax identifier for strings containing JavaScript Object Notation (JSON).\n public const string Json = nameof(Json);\n\n /// The syntax identifier for strings containing numeric format specifiers.\n public const string NumericFormat = nameof(NumericFormat);\n\n /// The syntax identifier for strings containing regular expressions.\n public const string Regex = nameof(Regex);\n\n /// The syntax identifier for strings containing time format specifiers.\n public const string TimeOnlyFormat = nameof(TimeOnlyFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string TimeSpanFormat = nameof(TimeSpanFormat);\n\n /// The syntax identifier for strings containing URIs.\n public const string Uri = nameof(Uri);\n\n /// The syntax identifier for strings containing XML.\n public const string Xml = nameof(Xml);\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices;\n\n[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]\ninternal sealed class CallerArgumentExpressionAttribute : Attribute\n{\n public CallerArgumentExpressionAttribute(string parameterName)\n {\n ParameterName = parameterName;\n }\n\n public string ParameterName { get; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/ResourceMetadataRequestContext.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Context for resource metadata request events.\n/// \npublic class ResourceMetadataRequestContext : HandleRequestContext\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The HTTP context.\n /// The authentication scheme.\n /// The authentication options.\n public ResourceMetadataRequestContext(\n HttpContext context,\n AuthenticationScheme scheme,\n McpAuthenticationOptions options)\n : base(context, scheme, options)\n {\n }\n\n /// \n /// Gets or sets the protected resource metadata for the current request.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpException.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents an exception that is thrown when an Model Context Protocol (MCP) error occurs.\n/// \n/// \n/// This exception is used to represent failures to do with protocol-level concerns, such as invalid JSON-RPC requests,\n/// invalid parameters, or internal errors. It is not intended to be used for application-level errors.\n/// or from a may be \n/// propagated to the remote endpoint; sensitive information should not be included. If sensitive details need\n/// to be included, a different exception type should be used.\n/// \npublic class McpException : Exception\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpException()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public McpException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n public McpException(string message, Exception? innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// A .\n public McpException(string message, McpErrorCode errorCode) : this(message, null, errorCode)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message, inner exception, and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n /// A .\n public McpException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)\n {\n ErrorCode = errorCode;\n }\n\n /// \n /// Gets the error code associated with this exception.\n /// \n /// \n /// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:\n /// \n /// -32700: Parse error - Invalid JSON received\n /// -32600: Invalid request - The JSON is not a valid Request object\n /// -32601: Method not found - The method does not exist or is not available\n /// -32602: Invalid params - Invalid method parameters\n /// -32603: Internal error - Internal JSON-RPC error\n /// \n /// \n public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresUnreferencedCode.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires dynamic access to code that is not referenced\n/// statically, for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when removing unreferenced\n/// code from an application.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresUnreferencedCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of unreferenced code.\n /// \n public RequiresUnreferencedCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of unreferenced code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires unreferenced code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresDynamicCodeAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires the ability to generate new code at runtime,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when compiling ahead of time.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresDynamicCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of dynamic code.\n /// \n public RequiresDynamicCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of dynamic code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires dynamic code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMembersAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that certain members on a specified are accessed dynamically,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which members are being accessed during the execution\n/// of a program.\n///\n/// This attribute is valid on members whose type is or .\n///\n/// When this attribute is applied to a location of type , the assumption is\n/// that the string represents a fully qualified type name.\n///\n/// When this attribute is applied to a class, interface, or struct, the members specified\n/// can be accessed dynamically on instances returned from calling\n/// on instances of that class, interface, or struct.\n///\n/// If the attribute is applied to a method it's treated as a special case and it implies\n/// the attribute should be applied to the \"this\" parameter of the method. As such the attribute\n/// should only be used on instance methods of types assignable to System.Type (or string, but no methods\n/// will use it there).\n/// \n[AttributeUsage(\n AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |\n AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |\n AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,\n Inherited = false)]\ninternal sealed class DynamicallyAccessedMembersAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified member types.\n /// \n /// The types of members dynamically accessed.\n public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)\n {\n MemberTypes = memberTypes;\n }\n\n /// \n /// Gets the which specifies the type\n /// of members dynamically accessed.\n /// \n public DynamicallyAccessedMemberTypes MemberTypes { get; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of tools created with\n/// . They provide control over naming, description,\n/// tool properties, and dependency injection integration.\n/// \n/// \n/// When creating tools programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerToolCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisfied from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Destructive { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Idempotent { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? OpenWorld { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? ReadOnly { get; set; }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerToolCreateOptions Clone() =>\n new McpServerToolCreateOptions\n {\n Services = Services,\n Name = Name,\n Description = Description,\n Title = Title,\n Destructive = Destructive,\n Idempotent = Idempotent,\n OpenWorld = OpenWorld,\n ReadOnly = ReadOnly,\n UseStructuredContent = UseStructuredContent,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationRedirectDelegate.cs", "\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a method that handles the OAuth authorization URL and returns the authorization code.\n/// \n/// The authorization URL that the user needs to visit.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// A task that represents the asynchronous operation. The task result contains the authorization code if successful, or null if the operation failed or was cancelled.\n/// \n/// \n/// This delegate provides SDK consumers with full control over how the OAuth authorization flow is handled.\n/// Implementers can choose to:\n/// \n/// \n/// Start a local HTTP server and open a browser (default behavior)\n/// Display the authorization URL to the user for manual handling\n/// Integrate with a custom UI or authentication flow\n/// Use a different redirect mechanism altogether\n/// \n/// \n/// The implementation should handle user interaction to visit the authorization URL and extract\n/// the authorization code from the callback. The authorization code is typically provided as\n/// a query parameter in the redirect URI callback.\n/// \n/// \npublic delegate Task AuthorizationRedirectDelegate(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken);"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IClientTransport.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a transport mechanism for Model Context Protocol (MCP) client-to-server communication.\n/// \n/// \n/// \n/// The interface abstracts the communication layer between MCP clients\n/// and servers, allowing different transport protocols to be used interchangeably.\n/// \n/// \n/// When creating an , is typically used, and is\n/// provided with the based on expected server configuration.\n/// \n/// \npublic interface IClientTransport\n{\n /// \n /// Gets a transport identifier, used for logging purposes.\n /// \n string Name { get; }\n\n /// \n /// Asynchronously establishes a transport session with an MCP server and returns a transport for the duplex message stream.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// Returns an interface for the duplex message stream.\n /// \n /// \n /// This method is responsible for initializing the connection to the server using the specific transport \n /// mechanism implemented by the derived class. The returned interface \n /// provides methods to send and receive messages over the established connection.\n /// \n /// \n /// The lifetime of the returned instance is typically managed by the \n /// that uses this transport. When the client is disposed, it will dispose\n /// the transport session as well.\n /// \n /// \n /// This method is used by to initialize the connection.\n /// \n /// \n /// The transport connection could not be established.\n Task ConnectAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of resources created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating resources programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerResourceCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the URI template of the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the from the attribute will be used. If that's not present,\n /// a URI template will be inferred from the member's signature.\n /// \n public string? UriTemplate { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the name from the attribute will be used. If that's not present, a name based on the members's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the member,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the MIME (media) type of the .\n /// \n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerResourceCreateOptions Clone() =>\n new McpServerResourceCreateOptions\n {\n Services = Services,\n UriTemplate = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of prompts created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating prompts programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerPromptCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerPromptCreateOptions Clone() =>\n new McpServerPromptCreateOptions\n {\n Services = Services,\n Name = Name,\n Title = Title,\n Description = Description,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/samples/QuickstartWeatherServer/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing QuickstartWeatherServer.Tools;\nusing System.Net.Http.Headers;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools();\n\nbuilder.Logging.AddConsole(options =>\n{\n options.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nbuilder.Services.AddSingleton(_ =>\n{\n var client = new HttpClient { BaseAddress = new Uri(\"https://api.weather.gov\") };\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n return client;\n});\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/EmptyResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an empty result object for operations that need to indicate successful completion \n/// but don't need to return any specific data.\n/// \npublic sealed class EmptyResult : Result\n{\n [JsonIgnore]\n internal static EmptyResult Instance { get; } = new();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method or property should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods or properties that should be exposed as resources in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods or properties become available as resources that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerResourceAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerResourceAttribute()\n {\n }\n\n /// Gets or sets the URI template of the resource.\n /// \n /// If , a URI will be derived from and the method's parameter names.\n /// This template may, but doesn't have to, include parameters; if it does, this \n /// will be considered a \"resource template\", and if it doesn't, it will be considered a \"direct resource\".\n /// The former will be listed with requests and the latter\n /// with requests.\n /// \n public string? UriTemplate { get; set; }\n\n /// Gets or sets the name of the resource.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the resource.\n public string? Title { get; set; }\n\n /// Gets or sets the MIME (media) type of the resource.\n public string? MimeType { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/TextResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents text-based contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when textual data needs to be exchanged through\n/// the Model Context Protocol. The text is stored directly in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for binary resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class TextResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the text of the item.\n /// \n [JsonPropertyName(\"text\")]\n public string Text { get; set; } = string.Empty;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/HttpTransportMode.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Specifies the transport mode for HTTP client connections.\n/// \npublic enum HttpTransportMode\n{\n /// \n /// Automatically detect the appropriate transport by trying Streamable HTTP first, then falling back to SSE if that fails.\n /// This is the recommended mode for maximum compatibility.\n /// \n AutoDetect,\n\n /// \n /// Use only the Streamable HTTP transport.\n /// \n StreamableHttp,\n\n /// \n /// Use only the HTTP with SSE transport.\n /// \n Sse\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ProtectedResourceMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the resource metadata for OAuth authorization as defined in RFC 9396.\n/// Defined by RFC 9728.\n/// \npublic sealed class ProtectedResourceMetadata\n{\n /// \n /// The resource URI.\n /// \n /// \n /// REQUIRED. The protected resource's resource identifier.\n /// \n [JsonPropertyName(\"resource\")]\n public required Uri Resource { get; set; }\n\n /// \n /// The list of authorization server URIs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of OAuth authorization server issuer identifiers\n /// for authorization servers that can be used with this protected resource.\n /// \n [JsonPropertyName(\"authorization_servers\")]\n public List AuthorizationServers { get; set; } = [];\n\n /// \n /// The supported bearer token methods.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the supported methods of sending an OAuth 2.0 bearer token\n /// to the protected resource. Defined values are [\"header\", \"body\", \"query\"].\n /// \n [JsonPropertyName(\"bearer_methods_supported\")]\n public List BearerMethodsSupported { get; set; } = [\"header\"];\n\n /// \n /// The supported scopes.\n /// \n /// \n /// RECOMMENDED. JSON array containing a list of scope values that are used in authorization\n /// requests to request access to this protected resource.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List ScopesSupported { get; set; } = [];\n\n /// \n /// URL of the protected resource's JSON Web Key (JWK) Set document.\n /// \n /// \n /// OPTIONAL. This contains public keys belonging to the protected resource, such as signing key(s)\n /// that the resource server uses to sign resource responses. This URL MUST use the https scheme.\n /// \n [JsonPropertyName(\"jwks_uri\")]\n public Uri? JwksUri { get; set; }\n\n /// \n /// List of the JWS signing algorithms supported by the protected resource for signing resource responses.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS signing algorithms (alg values) supported by the protected resource\n /// for signing resource responses. No default algorithms are implied if this entry is omitted. The value none MUST NOT be used.\n /// \n [JsonPropertyName(\"resource_signing_alg_values_supported\")]\n public List? ResourceSigningAlgValuesSupported { get; set; }\n\n /// \n /// Human-readable name of the protected resource intended for display to the end user.\n /// \n /// \n /// RECOMMENDED. It is recommended that protected resource metadata include this field.\n /// The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_name\")]\n public string? ResourceName { get; set; }\n\n /// \n /// The URI to the resource documentation.\n /// \n /// \n /// OPTIONAL. URL of a page containing human-readable information that developers might want or need to know\n /// when using the protected resource.\n /// \n [JsonPropertyName(\"resource_documentation\")]\n public Uri? ResourceDocumentation { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's requirements.\n /// \n /// \n /// OPTIONAL. Information about how the client can use the data provided by the protected resource.\n /// \n [JsonPropertyName(\"resource_policy_uri\")]\n public Uri? ResourcePolicyUri { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's terms of service.\n /// \n /// \n /// OPTIONAL. The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_tos_uri\")]\n public Uri? ResourceTosUri { get; set; }\n\n /// \n /// Boolean value indicating protected resource support for mutual-TLS client certificate-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"tls_client_certificate_bound_access_tokens\")]\n public bool? TlsClientCertificateBoundAccessTokens { get; set; }\n\n /// \n /// List of the authorization details type values supported by the resource server.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the authorization details type values supported by the resource server\n /// when the authorization_details request parameter is used.\n /// \n [JsonPropertyName(\"authorization_details_types_supported\")]\n public List? AuthorizationDetailsTypesSupported { get; set; }\n\n /// \n /// List of the JWS algorithm values supported by the resource server for validating DPoP proof JWTs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS alg values supported by the resource server\n /// for validating Demonstrating Proof of Possession (DPoP) proof JWTs.\n /// \n [JsonPropertyName(\"dpop_signing_alg_values_supported\")]\n public List? DpopSigningAlgValuesSupported { get; set; }\n\n /// \n /// Boolean value specifying whether the protected resource always requires the use of DPoP-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"dpop_bound_access_tokens_required\")]\n public bool? DpopBoundAccessTokensRequired { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ClientOAuthOptions.cs", "namespace ModelContextProtocol.Authentication;\n\n/// \n/// Provides configuration options for the .\n/// \npublic sealed class ClientOAuthOptions\n{\n /// \n /// Gets or sets the OAuth redirect URI.\n /// \n public required Uri RedirectUri { get; set; }\n\n /// \n /// Gets or sets the OAuth client ID. If not provided, the client will attempt to register dynamically.\n /// \n public string? ClientId { get; set; }\n\n /// \n /// Gets or sets the OAuth client secret.\n /// \n /// \n /// This is optional for public clients or when using PKCE without client authentication.\n /// \n public string? ClientSecret { get; set; }\n\n /// \n /// Gets or sets the OAuth scopes to request.\n /// \n /// \n /// \n /// When specified, these scopes will be used instead of the scopes advertised by the protected resource.\n /// If not specified, the provider will use the scopes from the protected resource metadata.\n /// \n /// \n /// Common OAuth scopes include \"openid\", \"profile\", \"email\", etc.\n /// \n /// \n public IEnumerable? Scopes { get; set; }\n\n /// \n /// Gets or sets the authorization redirect delegate for handling the OAuth authorization flow.\n /// \n /// \n /// \n /// This delegate is responsible for handling the OAuth authorization URL and obtaining the authorization code.\n /// If not specified, a default implementation will be used that prompts the user to enter the code manually.\n /// \n /// \n /// Custom implementations might open a browser, start an HTTP listener, or use other mechanisms to capture\n /// the authorization code from the OAuth redirect.\n /// \n /// \n public AuthorizationRedirectDelegate? AuthorizationRedirectDelegate { get; set; }\n\n /// \n /// Gets or sets the authorization server selector function.\n /// \n /// \n /// \n /// This function is used to select which authorization server to use when multiple servers are available.\n /// If not specified, the first available server will be selected.\n /// \n /// \n /// The function receives a list of available authorization server URIs and should return the selected server,\n /// or null if no suitable server is found.\n /// \n /// \n public Func, Uri?>? AuthServerSelector { get; set; }\n\n /// \n /// Gets or sets the client name to use during dynamic client registration.\n /// \n /// \n /// This is a human-readable name for the client that may be displayed to users during authorization.\n /// Only used when a is not specified.\n /// \n public string? ClientName { get; set; }\n\n /// \n /// Gets or sets the client URI to use during dynamic client registration.\n /// \n /// \n /// This should be a URL pointing to the client's home page or information page.\n /// Only used when a is not specified.\n /// \n public Uri? ClientUri { get; set; }\n\n /// \n /// Gets or sets additional parameters to include in the query string of the OAuth authorization request\n /// providing extra information or fulfilling specific requirements of the OAuth provider.\n /// \n /// \n /// \n /// Parameters specified cannot override or append to any automatically set parameters like the \"redirect_uri\"\n /// which should instead be configured via .\n /// \n /// \n public IDictionary AdditionalAuthorizationParameters { get; set; } = new Dictionary();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as prompts in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as prompts that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerPromptAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPromptAttribute()\n {\n }\n\n /// Gets the name of the prompt.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the prompt.\n public string? Title { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServer.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) server that connects to and communicates with an MCP client.\n/// \npublic interface IMcpServer : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the client.\n /// \n /// \n /// \n /// These capabilities are established during the initialization handshake and indicate\n /// which features the client supports, such as sampling, roots, and other\n /// protocol-specific functionality.\n /// \n /// \n /// Server implementations can check these capabilities to determine which features\n /// are available when interacting with the client.\n /// \n /// \n ClientCapabilities? ClientCapabilities { get; }\n\n /// \n /// Gets the version and implementation information of the connected client.\n /// \n /// \n /// \n /// This property contains identification information about the client that has connected to this server,\n /// including its name and version. This information is provided by the client during initialization.\n /// \n /// \n /// Server implementations can use this information for logging, tracking client versions, \n /// or implementing client-specific behaviors.\n /// \n /// \n Implementation? ClientInfo { get; }\n\n /// \n /// Gets the options used to construct this server.\n /// \n /// \n /// These options define the server's capabilities, protocol version, and other configuration\n /// settings that were used to initialize the server.\n /// \n McpServerOptions ServerOptions { get; }\n\n /// \n /// Gets the service provider for the server.\n /// \n IServiceProvider? Services { get; }\n\n /// Gets the last logging level set by the client, or if it's never been set.\n LoggingLevel? LoggingLevel { get; }\n\n /// \n /// Runs the server, listening for and handling client requests.\n /// \n Task RunAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Completion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a completion object in the server's response to a request.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Completion\n{\n /// \n /// Gets or sets an array of completion values (auto-suggestions) for the requested input.\n /// \n /// \n /// This collection contains the actual text strings to be presented to users as completion suggestions.\n /// The array will be empty if no suggestions are available for the current input.\n /// Per the specification, this should not exceed 100 items.\n /// \n [JsonPropertyName(\"values\")]\n public IList Values { get; set; } = [];\n\n /// \n /// Gets or sets the total number of completion options available.\n /// \n /// \n /// This can exceed the number of values actually sent in the response.\n /// \n [JsonPropertyName(\"total\")]\n public int? Total { get; set; }\n\n /// \n /// Gets or sets an indicator as to whether there are additional completion options beyond \n /// those provided in the current response, even if the exact total is unknown.\n /// \n [JsonPropertyName(\"hasMore\")]\n public bool? HasMore { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationServerMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the metadata about an OAuth authorization server.\n/// \ninternal sealed class AuthorizationServerMetadata\n{\n /// \n /// The authorization endpoint URI.\n /// \n [JsonPropertyName(\"authorization_endpoint\")]\n public Uri AuthorizationEndpoint { get; set; } = null!;\n\n /// \n /// The token endpoint URI.\n /// \n [JsonPropertyName(\"token_endpoint\")]\n public Uri TokenEndpoint { get; set; } = null!;\n\n /// \n /// The registration endpoint URI.\n /// \n [JsonPropertyName(\"registration_endpoint\")]\n public Uri? RegistrationEndpoint { get; set; }\n\n /// \n /// The revocation endpoint URI.\n /// \n [JsonPropertyName(\"revocation_endpoint\")]\n public Uri? RevocationEndpoint { get; set; }\n\n /// \n /// The response types supported by the authorization server.\n /// \n [JsonPropertyName(\"response_types_supported\")]\n public List? ResponseTypesSupported { get; set; }\n\n /// \n /// The grant types supported by the authorization server.\n /// \n [JsonPropertyName(\"grant_types_supported\")]\n public List? GrantTypesSupported { get; set; }\n\n /// \n /// The token endpoint authentication methods supported by the authorization server.\n /// \n [JsonPropertyName(\"token_endpoint_auth_methods_supported\")]\n public List? TokenEndpointAuthMethodsSupported { get; set; }\n\n /// \n /// The code challenge methods supported by the authorization server.\n /// \n [JsonPropertyName(\"code_challenge_methods_supported\")]\n public List? CodeChallengeMethodsSupported { get; set; }\n\n /// \n /// The issuer URI of the authorization server.\n /// \n [JsonPropertyName(\"issuer\")]\n public Uri? Issuer { get; set; }\n\n /// \n /// The scopes supported by the authorization server.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List? ScopesSupported { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the client's response to an elicitation request.\n/// \npublic sealed class ElicitResult : Result\n{\n /// \n /// Gets or sets the user action in response to the elicitation.\n /// \n /// \n /// \n /// \n /// \"accept\"\n /// User submitted the form/confirmed the action\n /// \n /// \n /// \"decline\"\n /// User explicitly declined the action\n /// \n /// \n /// \"cancel\"\n /// User dismissed without making an explicit choice\n /// \n /// \n /// \n [JsonPropertyName(\"action\")]\n public string Action { get; set; } = \"cancel\";\n\n /// \n /// Gets or sets the submitted form data.\n /// \n /// \n /// \n /// This is typically omitted if the action is \"cancel\" or \"decline\".\n /// \n /// \n /// Values in the dictionary should be of types , ,\n /// , or .\n /// \n /// \n [JsonPropertyName(\"content\")]\n public IDictionary? Content { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/ForceYielding.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading;\n\n/// \n/// await default(ForceYielding) to provide the same behavior as\n/// await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding).\n/// \ninternal readonly struct ForceYielding : INotifyCompletion, ICriticalNotifyCompletion\n{\n public ForceYielding GetAwaiter() => this;\n\n public bool IsCompleted => false;\n public void OnCompleted(Action continuation) => ThreadPool.QueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void UnsafeOnCompleted(Action continuation) => ThreadPool.UnsafeQueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void GetResult() { }\n}\n#endif"], ["/csharp-sdk/samples/AspNetCoreSseServer/Program.cs", "using OpenTelemetry;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\nusing TestServerWithHosting.Tools;\nusing TestServerWithHosting.Resources;\n\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Services.AddMcpServer()\n .WithHttpTransport()\n .WithTools()\n .WithTools()\n .WithResources();\n\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithMetrics(b => b.AddMeter(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithLogging()\n .UseOtlpExporter();\n\nvar app = builder.Build();\n\napp.MapMcp();\n\napp.Run();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from \n/// a client to ask a server for auto-completion suggestions.\n/// \n/// \n/// \n/// is used in the Model Context Protocol completion workflow\n/// to provide intelligent suggestions for partial inputs related to resources, prompts, or other referenceable entities.\n/// The completion mechanism in MCP allows clients to request suggestions based on partial inputs.\n/// The server will respond with a containing matching values.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteRequestParams : RequestParams\n{\n /// \n /// Gets or sets the reference's information.\n /// \n [JsonPropertyName(\"ref\")]\n public required Reference Ref { get; init; }\n\n /// \n /// Gets or sets the argument information for the completion request, specifying what is being completed\n /// and the current partial input.\n /// \n [JsonPropertyName(\"argument\")]\n public required Argument Argument { get; init; }\n\n /// \n /// Gets or sets additional, optional context for completions.\n /// \n [JsonPropertyName(\"context\")]\n public CompleteContext? Context { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingLevel.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Indicates the severity of a log message.\n/// \n/// \n/// These map to syslog message severities, as specified in RFC-5424.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum LoggingLevel\n{\n /// Detailed debug information, typically only valuable to developers.\n [JsonStringEnumMemberName(\"debug\")]\n Debug,\n\n /// Normal operational messages that require no action.\n [JsonStringEnumMemberName(\"info\")]\n Info,\n\n /// Normal but significant events that might deserve attention.\n [JsonStringEnumMemberName(\"notice\")]\n Notice,\n\n /// Warning conditions that don't represent an error but indicate potential issues.\n [JsonStringEnumMemberName(\"warning\")]\n Warning,\n\n /// Error conditions that should be addressed but don't require immediate action.\n [JsonStringEnumMemberName(\"error\")]\n Error,\n\n /// Critical conditions that require immediate attention.\n [JsonStringEnumMemberName(\"critical\")]\n Critical,\n\n /// Action must be taken immediately to address the condition.\n [JsonStringEnumMemberName(\"alert\")]\n Alert,\n\n /// System is unusable and requires immediate attention.\n [JsonStringEnumMemberName(\"emergency\")]\n Emergency\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for paginated requests.\n/// \n/// \n/// See the schema for details\n/// \npublic abstract class PaginatedRequestParams : RequestParams\n{\n /// Prevent external derivations.\n private protected PaginatedRequestParams()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the current pagination position.\n /// \n /// \n /// If provided, the server should return results starting after this cursor.\n /// This value should be obtained from the \n /// property of a previous request's response.\n /// \n [JsonPropertyName(\"cursor\")]\n public string? Cursor { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides configuration options for the MCP server.\n/// \npublic sealed class McpServerOptions\n{\n /// \n /// Gets or sets information about this server implementation, including its name and version.\n /// \n /// \n /// This information is sent to the client during initialization to identify the server.\n /// It's displayed in client logs and can be used for debugging and compatibility checks.\n /// \n public Implementation? ServerInfo { get; set; }\n\n /// \n /// Gets or sets server capabilities to advertise to the client.\n /// \n /// \n /// These determine which features will be available when a client connects.\n /// Capabilities can include \"tools\", \"prompts\", \"resources\", \"logging\", and other \n /// protocol-specific functionality.\n /// \n public ServerCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version supported by this server, using a date-based versioning scheme.\n /// \n /// \n /// The protocol version defines which features and message formats this server supports.\n /// This uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// If , the server will advertize to the client the version requested\n /// by the client if that version is known to be supported, and otherwise will advertize the latest\n /// version supported by the server.\n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout used for the client-server initialization handshake sequence.\n /// \n /// \n /// This timeout determines how long the server will wait for client responses during\n /// the initialization protocol handshake. If the client doesn't respond within this timeframe,\n /// the initialization process will be aborted.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n\n /// \n /// Gets or sets optional server instructions to send to clients.\n /// \n /// \n /// These instructions are sent to clients during the initialization handshake and provide\n /// guidance on how to effectively use the server's capabilities. They can include details\n /// about available tools, expected input formats, limitations, or other helpful information.\n /// Client applications typically use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n public string? ServerInstructions { get; set; }\n\n /// \n /// Gets or sets whether to create a new service provider scope for each handled request.\n /// \n /// \n /// The default is . When , each invocation of a request\n /// handler will be invoked within a new service scope.\n /// \n public bool ScopeRequests { get; set; } = true;\n\n /// \n /// Gets or sets preexisting knowledge about the client including its name and version to help support\n /// stateless Streamable HTTP servers that encode this knowledge in the mcp-session-id header.\n /// \n /// \n /// \n /// When not specified, this information is sourced from the client's initialize request.\n /// \n /// \n public Implementation? KnownClientInfo { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationEvents.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Represents the authentication events for Model Context Protocol.\n/// \npublic class McpAuthenticationEvents\n{\n /// \n /// Gets or sets the function that is invoked when resource metadata is requested.\n /// \n /// \n /// This function is called when a resource metadata request is made to the protected resource metadata endpoint.\n /// The implementer should set the property\n /// to provide the appropriate metadata for the current request.\n /// \n public Func OnResourceMetadataRequest { get; set; } = context => Task.CompletedTask;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Argument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument used in completion requests to provide context for auto-completion functionality.\n/// \n/// \n/// This class is used when requesting completion suggestions for a particular field or parameter.\n/// See the schema for details.\n/// \npublic sealed class Argument\n{\n /// \n /// Gets or sets the name of the argument being completed.\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the current partial text value for which completion suggestions are requested.\n /// \n /// \n /// This represents the text that has been entered so far and for which completion\n /// options should be generated.\n /// \n [JsonPropertyName(\"value\")]\n public string Value { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// The server will respond with a containing the result of the tool invocation.\n/// See the schema for details.\n/// \npublic sealed class CallToolRequestParams : RequestParams\n{\n /// Gets or sets the name of the tool to invoke.\n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets optional arguments to pass to the tool when invoking it on the server.\n /// \n /// \n /// This dictionary contains the parameter values to be passed to the tool. Each key-value pair represents \n /// a parameter name and its corresponding argument value.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// request from a server to sample an LLM via the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageRequestParams : RequestParams\n{\n /// \n /// Gets or sets an indication as to which server contexts should be included in the prompt.\n /// \n /// \n /// The client may ignore this request.\n /// \n [JsonPropertyName(\"includeContext\")]\n public ContextInclusion? IncludeContext { get; init; }\n\n /// \n /// Gets or sets the maximum number of tokens to generate in the LLM response, as requested by the server.\n /// \n /// \n /// A token is generally a word or part of a word in the text. Setting this value helps control \n /// response length and computation time. The client may choose to sample fewer tokens than requested.\n /// \n [JsonPropertyName(\"maxTokens\")]\n public int? MaxTokens { get; init; }\n\n /// \n /// Gets or sets the messages requested by the server to be included in the prompt.\n /// \n [JsonPropertyName(\"messages\")]\n public required IReadOnlyList Messages { get; init; }\n\n /// \n /// Gets or sets optional metadata to pass through to the LLM provider.\n /// \n /// \n /// The format of this metadata is provider-specific and can include model-specific settings or\n /// configuration that isn't covered by standard parameters. This allows for passing custom parameters \n /// that are specific to certain AI models or providers.\n /// \n [JsonPropertyName(\"metadata\")]\n public JsonElement? Metadata { get; init; }\n\n /// \n /// Gets or sets the server's preferences for which model to select.\n /// \n /// \n /// \n /// The client may ignore these preferences.\n /// \n /// \n /// These preferences help the client make an appropriate model selection based on the server's priorities\n /// for cost, speed, intelligence, and specific model hints.\n /// \n /// \n /// When multiple dimensions are specified (cost, speed, intelligence), the client should balance these\n /// based on their relative values. If specific model hints are provided, the client should evaluate them\n /// in order and prioritize them over numeric priorities.\n /// \n /// \n [JsonPropertyName(\"modelPreferences\")]\n public ModelPreferences? ModelPreferences { get; init; }\n\n /// \n /// Gets or sets optional sequences of characters that signal the LLM to stop generating text when encountered.\n /// \n /// \n /// \n /// When the model generates any of these sequences during sampling, text generation stops immediately,\n /// even if the maximum token limit hasn't been reached. This is useful for controlling generation \n /// endings or preventing the model from continuing beyond certain points.\n /// \n /// \n /// Stop sequences are typically case-sensitive, and typically the LLM will only stop generation when a produced\n /// sequence exactly matches one of the provided sequences. Common uses include ending markers like \"END\", punctuation\n /// like \".\", or special delimiter sequences like \"###\".\n /// \n /// \n [JsonPropertyName(\"stopSequences\")]\n public IReadOnlyList? StopSequences { get; init; }\n\n /// \n /// Gets or sets an optional system prompt the server wants to use for sampling.\n /// \n /// \n /// The client may modify or omit this prompt.\n /// \n [JsonPropertyName(\"systemPrompt\")]\n public string? SystemPrompt { get; init; }\n\n /// \n /// Gets or sets the temperature to use for sampling, as requested by the server.\n /// \n [JsonPropertyName(\"temperature\")]\n public float? Temperature { get; init; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/AddTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AddTool\n{\n [McpServerTool(Name = \"add\"), Description(\"Adds two numbers.\")]\n public static string Add(int a, int b) => $\"The sum of {a} and {b} is {a + b}\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a prompt provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting prompt.\n/// See the schema for details.\n/// \npublic sealed class GetPromptRequestParams : RequestParams\n{\n /// \n /// Gets or sets the name of the prompt.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets arguments to use for templating the prompt when retrieving it from the server.\n /// \n /// \n /// Typically, these arguments are used to replace placeholders in prompt templates. The keys in this dictionary\n /// should match the names defined in the prompt's list. However, the server may\n /// choose to use these arguments in any way it deems appropriate to generate the prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads that support cursor-based pagination.\n/// \n/// \n/// \n/// Pagination allows API responses to be broken into smaller, manageable chunks when\n/// there are potentially many results to return or when dynamically-computed results\n/// may incur measurable latency.\n/// \n/// \n/// Classes that inherit from implement cursor-based pagination,\n/// where the property serves as an opaque token pointing to the next \n/// set of results.\n/// \n/// \npublic abstract class PaginatedResult : Result\n{\n private protected PaginatedResult()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the pagination position after the last returned result.\n /// \n /// \n /// When a paginated result has more data available, the \n /// property will contain a non- token that can be used in subsequent requests\n /// to fetch the next page. When there are no more results to return, the property\n /// will be .\n /// \n public string? NextCursor { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional context information for completion requests.\n/// \n/// \n/// This context provides information that helps the server generate more relevant \n/// completion suggestions, such as previously resolved variables in a template.\n/// \npublic sealed class CompleteContext\n{\n /// \n /// Gets or sets previously-resolved variables in a URI template or prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/UserIdClaim.cs", "namespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed record UserIdClaim(string Type, string Value, string Issuer);\n"], ["/csharp-sdk/samples/EverythingServer/Tools/TinyImageTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class TinyImageTool\n{\n [McpServerTool(Name = \"getTinyImage\"), Description(\"Get a tiny image from the server\")]\n public static IEnumerable GetTinyImage() => [\n new TextContent(\"This is a tiny image:\"),\n new DataContent(MCP_TINY_IMAGE),\n new TextContent(\"The image above is the MCP tiny image.\")\n ];\n\n internal const string MCP_TINY_IMAGE =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAKsGlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgOfe9JDQEiIgJfQmSCeAlBBaAAXpYCMkAUKJMRBU7MriClZURLCs6KqIgo0idizYFsWC3QVZBNR1sWDDlXeBQ9jdd9575805c+a7c+efmf+e/z9nLgCdKZDJMlF1gCxpjjwyyI8dn5DIJvUABRiY0kBdIMyWcSMiwgCTUft3+dgGyJC9YzuU69/f/1fREImzhQBIBMbJomxhFsbHMe0TyuQ5ALg9mN9kbo5siK9gzJRjDWL8ZIhTR7hviJOHGY8fjomO5GGsDUCmCQTyVACaKeZn5wpTsTw0f4ztpSKJFGPsGbyzsmaLMMbqgiUWI8N4KD8n+S95Uv+WM1mZUyBIVfLIXoaF7C/JlmUK5v+fn+N/S1amYrSGOaa0NHlwJGaxvpAHGbNDlSxNnhI+yhLRcPwwpymCY0ZZmM1LHGWRwD9UuTZzStgop0gC+co8OfzoURZnB0SNsnx2pLJWipzHHWWBfKyuIiNG6U8T85X589Ki40Y5VxI7ZZSzM6JCx2J4Sr9cEansXywN8hurG6jce1b2X/Yr4SvX5qRFByv3LhjrXyzljuXMjlf2JhL7B4zFxCjjZTl+ylqyzAhlvDgzSOnPzo1Srs3BDuTY2gjlN0wXhESMMoRBELAhBjIhB+QggECQgBTEOeJ5Q2cUeLNl8+WS1LQcNhe7ZWI2Xyq0m8B2tHd0Bhi6syNH4j1r+C4irGtjvhWVAF4nBgcHT475Qm4BHEkCoNaO+SxnAKh3A1w5JVTIc0d8Q9cJCEAFNWCCDhiACViCLTiCK3iCLwRACIRDNCTATBBCGmRhnc+FhbAMCqAI1sNmKIOdsBv2wyE4CvVwCs7DZbgOt+AePIZ26IJX0AcfYQBBEBJCRxiIDmKImCE2iCPCQbyRACQMiUQSkCQkFZEiCmQhsgIpQoqRMmQXUokcQU4g55GrSCvyEOlAepF3yFcUh9JQJqqPmqMTUQ7KRUPRaHQGmorOQfPQfHQtWopWoAfROvQ8eh29h7ajr9B+HOBUcCycEc4Wx8HxcOG4RFwKTo5bjCvEleAqcNW4Rlwz7g6uHfca9wVPxDPwbLwt3hMfjI/BC/Fz8Ivxq/Fl+P34OvxF/B18B74P/51AJ+gRbAgeBD4hnpBKmEsoIJQQ9hJqCZcI9whdhI9EIpFFtCC6EYOJCcR04gLiauJ2Yg3xHLGV2EnsJ5FIOiQbkhcpnCQg5ZAKSFtJB0lnSbdJXaTPZBWyIdmRHEhOJEvJy8kl5APkM+Tb5G7yAEWdYkbxoIRTRJT5lHWUPZRGyk1KF2WAqkG1oHpRo6np1GXUUmo19RL1CfW9ioqKsYq7ylQVicpSlVKVwypXVDpUvtA0adY0Hm06TUFbS9tHO0d7SHtPp9PN6b70RHoOfS29kn6B/oz+WZWhaqfKVxWpLlEtV61Tva36Ro2iZqbGVZuplqdWonZM7abaa3WKurk6T12gvli9XP2E+n31fg2GhoNGuEaWxmqNAxpXNXo0SZrmmgGaIs18zd2aFzQ7GTiGCYPHEDJWMPYwLjG6mESmBZPPTGcWMQ8xW5h9WppazlqxWvO0yrVOa7WzcCxzFp+VyVrHOspqY30dpz+OO048btW46nG3x33SHq/tqy3WLtSu0b6n/VWHrROgk6GzQade56kuXtdad6ruXN0dupd0X49njvccLxxfOP7o+Ed6qJ61XqTeAr3dejf0+vUN9IP0Zfpb9S/ovzZgGfgapBtsMjhj0GvIMPQ2lBhuMjxr+JKtxeayM9ml7IvsPiM9o2AjhdEuoxajAWML4xjj5cY1xk9NqCYckxSTTSZNJn2mhqaTTReaVpk+MqOYcczSzLaYNZt9MrcwjzNfaV5v3mOhbcG3yLOosnhiSbf0sZxjWWF514poxbHKsNpudcsatXaxTrMut75pg9q42khsttu0TiBMcJ8gnVAx4b4tzZZrm2tbZdthx7ILs1tuV2/3ZqLpxMSJGyY2T/xu72Kfab/H/rGDpkOIw3KHRod3jtaOQsdyx7tOdKdApyVODU5vnW2cxc47nB+4MFwmu6x0aXL509XNVe5a7drrZuqW5LbN7T6HyYngrOZccSe4+7kvcT/l/sXD1SPH46jHH562nhmeBzx7JllMEk/aM6nTy9hL4LXLq92b7Z3k/ZN3u4+Rj8Cnwue5r4mvyHevbzfXipvOPch942fvJ/er9fvE8+At4p3zx/kH+Rf6twRoBsQElAU8CzQOTA2sCuwLcglaEHQumBAcGrwh+D5fny/kV/L7QtxCFoVcDKWFRoWWhT4Psw6ThzVORieHTN44+ckUsynSKfXhEM4P3xj+NMIiYk7EyanEqRFTy6e+iHSIXBjZHMWImhV1IOpjtF/0uujHMZYxipimWLXY6bGVsZ/i/OOK49rjJ8Yvir+eoJsgSWhIJCXGJu5N7J8WMG3ztK7pLtMLprfNsJgxb8bVmbozM2eenqU2SzDrWBIhKS7pQNI3QbigQtCfzE/eltwn5Am3CF+JfEWbRL1iL3GxuDvFK6U4pSfVK3Vjam+aT1pJ2msJT1ImeZsenL4z/VNGeMa+jMHMuMyaLHJWUtYJqaY0Q3pxtsHsebNbZTayAln7HI85m+f0yUPle7OR7BnZDTlMbDi6obBU/KDoyPXOLc/9PDd27rF5GvOk827Mt56/an53XmDezwvwC4QLmhYaLVy2sGMRd9Guxcji5MVNS0yW5C/pWhq0dP8y6rKMZb8st19evPzDirgVjfn6+UvzO38I+qGqQLVAXnB/pefKnT/if5T82LLKadXWVd8LRYXXiuyLSoq+rRauvrbGYU3pmsG1KWtb1rmu27GeuF66vm2Dz4b9xRrFecWdGydvrNvE3lS46cPmWZuvljiX7NxC3aLY0l4aVtqw1XTr+q3fytLK7pX7ldds09u2atun7aLtt3f47qjeqb+zaOfXnyQ/PdgVtKuuwryiZDdxd+7uF3ti9zT/zPm5cq/u3qK9f+6T7mvfH7n/YqVbZeUBvQPrqtAqRVXvwekHbx3yP9RQbVu9q4ZVU3QYDisOvzySdKTtaOjRpmOcY9XHzY5vq2XUFtYhdfPr+urT6tsbEhpaT4ScaGr0bKw9aXdy3ymjU+WntU6vO0M9k39m8Gze2f5zsnOvz6ee72ya1fT4QvyFuxenXmy5FHrpyuXAyxeauc1nr3hdOXXV4+qJa5xr9dddr9fdcLlR+4vLL7Utri11N91uNtzyv9XYOqn1zG2f2+fv+N+5fJd/9/q9Kfda22LaHtyffr/9gehBz8PMh28f5T4aeLz0CeFJ4VP1pyXP9J5V/Gr1a027a/vpDv+OG8+jnj/uFHa++i37t29d+S/oL0q6Dbsrexx7TvUG9t56Oe1l1yvZq4HXBb9r/L7tjeWb43/4/nGjL76v66387eC71e913u/74PyhqT+i/9nHrI8Dnwo/63ze/4Xzpflr3NfugbnfSN9K/7T6s/F76Pcng1mDgzKBXDA8CuAwRVNSAN7tA6AnADCwGYI6bWSmHhZk5D9gmOA/8cjcPSyuANWYGRqNeOcADmNqvhRAzRdgaCyK9gXUyUmpo/Pv8Kw+JAbYv8K0HECi2x6tebQU/iEjc/xf+v6nBWXWv9l/AV0EC6JTIblRAAAAeGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAJAAAAABAAAAkAAAAAEAAqACAAQAAAABAAAAFKADAAQAAAABAAAAFAAAAAAXNii1AAAACXBIWXMAABYlAAAWJQFJUiTwAAAB82lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOllSZXNvbHV0aW9uPjE0NDwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+MTQ0PC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KReh49gAAAjRJREFUOBGFlD2vMUEUx2clvoNCcW8hCqFAo1dKhEQpvsF9KrWEBh/ALbQ0KkInBI3SWyGPCCJEQliXgsTLefaca/bBWjvJzs6cOf/fnDkzOQJIjWm06/XKBEGgD8c6nU5VIWgBtQDPZPWtJE8O63a7LBgMMo/Hw0ql0jPjcY4RvmqXy4XMjUYDUwLtdhtmsxnYbDbI5/O0djqdFFKmsEiGZ9jP9gem0yn0ej2Yz+fg9XpfycimAD7DttstQTDKfr8Po9GIIg6Hw1Cr1RTgB+A72GAwgMPhQLBMJgNSXsFqtUI2myUo18pA6QJogefsPrLBX4QdCVatViklw+EQRFGEj88P2O12pEUGATmsXq+TaLPZ0AXgMRF2vMEqlQoJTSYTpNNpApvNZliv1/+BHDaZTAi2Wq1A3Ig0xmMej7+RcZjdbodUKkWAaDQK+GHjHPnImB88JrZIJAKFQgH2+z2BOczhcMiwRCIBgUAA+NN5BP6mj2DYff35gk6nA61WCzBn2JxO5wPM7/fLz4vD0E+OECfn8xl/0Gw2KbLxeAyLxQIsFgt8p75pDSO7h/HbpUWpewCike9WLpfB7XaDy+WCYrFI/slk8i0MnRRAUt46hPMI4vE4+Hw+ec7t9/44VgWigEeby+UgFArJWjUYOqhWG6x50rpcSfR6PVUfNOgEVRlTX0HhrZBKz4MZjUYWi8VoA+lc9H/VaRZYjBKrtXR8tlwumcFgeMWRbZpA9ORQWfVm8A/FsrLaxebd5wAAAABJRU5ErkJggg==\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/IBaseMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// Provides a base interface for metadata with name (identifier) and title (display name) properties.\npublic interface IBaseMetadata\n{\n /// \n /// Gets or sets the unique identifier for this item.\n /// \n [JsonPropertyName(\"name\")]\n string Name { get; set; }\n\n /// \n /// Gets or sets a title.\n /// \n /// \n /// This is intended for UI and end-user contexts. It is optimized to be human-readable and easily understood,\n /// even by those unfamiliar with domain-specific terminology.\n /// If not provided, may be used for display (except for tools, where , if present, \n /// should be given precedence over using ).\n /// \n [JsonPropertyName(\"title\")]\n string? Title { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolAnnotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional properties describing a to clients.\n/// \n/// \n/// All properties in are hints.\n/// They are not guaranteed to provide a faithful description of tool behavior (including descriptive properties like `title`).\n/// Clients should never make tool use decisions based on received from untrusted servers.\n/// \npublic sealed class ToolAnnotations\n{\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"destructiveHint\")]\n public bool? DestructiveHint { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"idempotentHint\")]\n public bool? IdempotentHint { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"openWorldHint\")]\n public bool? OpenWorldHint { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"readOnlyHint\")]\n public bool? ReadOnlyHint { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Resource.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource that the server is capable of reading.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Resource : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource. Clients can use this information to filter or prioritize resources for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Result.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads.\n/// \npublic abstract class Result\n{\n /// Prevent external derivations.\n private protected Result()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for notification parameters.\n/// \npublic abstract class NotificationParams\n{\n /// Prevent external derivations.\n private protected NotificationParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessageWithId.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC message used in the Model Context Protocol (MCP) and that includes an ID.\n/// \n/// \n/// In the JSON-RPC protocol, messages with an ID require a response from the receiver.\n/// This includes request messages (which expect a matching response) and response messages\n/// (which include the ID of the original request they're responding to).\n/// The ID is used to correlate requests with their responses, allowing asynchronous\n/// communication where multiple requests can be sent without waiting for responses.\n/// \npublic abstract class JsonRpcMessageWithId : JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessageWithId()\n {\n }\n\n /// \n /// Gets the message identifier.\n /// \n /// \n /// Each ID is expected to be unique within the context of a given session.\n /// \n [JsonPropertyName(\"id\")]\n public RequestId Id { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/ProgressNotificationValue.cs", "namespace ModelContextProtocol;\n\n/// Provides a progress value that can be sent using .\npublic sealed class ProgressNotificationValue\n{\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// \n /// This value typically represents either a percentage (0-100) or the number of items processed so far (when used with the property).\n /// \n /// \n /// When reporting progress, this value should increase monotonically as the operation proceeds.\n /// Values are typically between 0 and 100 when representing percentages, or can be any positive number\n /// when representing completed items in combination with the property.\n /// \n /// \n public required float Progress { get; init; }\n\n /// Gets or sets the total number of items to process (or total progress required), if known.\n public float? Total { get; init; }\n\n /// Gets or sets an optional message describing the current progress.\n public string? Message { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a resource provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting resource data.\n/// See the schema for details.\n/// \npublic sealed class ReadResourceRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource, Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides configuration options for creating instances.\n/// \n/// \n/// These options are typically passed to when creating a client.\n/// They define client capabilities, protocol version, and other client-specific settings.\n/// \npublic sealed class McpClientOptions\n{\n /// \n /// Gets or sets information about this client implementation, including its name and version.\n /// \n /// \n /// \n /// This information is sent to the server during initialization to identify the client.\n /// It's often displayed in server logs and can be used for debugging and compatibility checks.\n /// \n /// \n /// When not specified, information sourced from the current process will be used.\n /// \n /// \n public Implementation? ClientInfo { get; set; }\n\n /// \n /// Gets or sets the client capabilities to advertise to the server.\n /// \n public ClientCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version to request from the server, using a date-based versioning scheme.\n /// \n /// \n /// \n /// The protocol version is a key part of the initialization handshake. The client and server must \n /// agree on a compatible protocol version to communicate successfully.\n /// \n /// \n /// If non-, this version will be sent to the server, and the handshake\n /// will fail if the version in the server's response does not match this version.\n /// If , the client will request the latest version supported by the server\n /// but will allow any supported version that the server advertizes in its response.\n /// \n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout for the client-server initialization handshake sequence.\n /// \n /// \n /// \n /// This timeout determines how long the client will wait for the server to respond during\n /// the initialization protocol handshake. If the server doesn't respond within this timeframe,\n /// an exception will be thrown.\n /// \n /// \n /// Setting an appropriate timeout prevents the client from hanging indefinitely when\n /// connecting to unresponsive servers.\n /// \n /// The default value is 60 seconds.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n}\n"], ["/csharp-sdk/samples/EverythingServer/Prompts/SimplePromptType.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class SimplePromptType\n{\n [McpServerPrompt(Name = \"simple_prompt\"), Description(\"A prompt without arguments\")]\n public static string SimplePrompt() => \"This is a simple prompt without arguments\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration request for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationRequest\n{\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public required string[] RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the human-readable name of the client.\n /// \n [JsonPropertyName(\"client_name\")]\n public string? ClientName { get; init; }\n\n /// \n /// Gets or sets the URL of the client's home page.\n /// \n [JsonPropertyName(\"client_uri\")]\n public string? ClientUri { get; init; }\n\n /// \n /// Gets or sets the scope values that the client will use.\n /// \n [JsonPropertyName(\"scope\")]\n public string? Scope { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationDefaults.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Default values used by MCP authentication.\n/// \npublic static class McpAuthenticationDefaults\n{\n /// \n /// The default value used for authentication scheme name.\n /// \n public const string AuthenticationScheme = \"McpAuth\";\n\n /// \n /// The default value used for authentication scheme display name.\n /// \n public const string DisplayName = \"MCP Authentication\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationResponse.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration response for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationResponse\n{\n /// \n /// Gets or sets the client identifier.\n /// \n [JsonPropertyName(\"client_id\")]\n public required string ClientId { get; init; }\n\n /// \n /// Gets or sets the client secret.\n /// \n [JsonPropertyName(\"client_secret\")]\n public string? ClientSecret { get; init; }\n\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public string[]? RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the client ID issued timestamp.\n /// \n [JsonPropertyName(\"client_id_issued_at\")]\n public long? ClientIdIssuedAt { get; init; }\n\n /// \n /// Gets or sets the client secret expiration time.\n /// \n [JsonPropertyName(\"client_secret_expires_at\")]\n public long? ClientSecretExpiresAt { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol/IMcpServerBuilder.cs", "using ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides a builder for configuring instances.\n/// \n/// \n/// \n/// The interface provides a fluent API for configuring Model Context Protocol (MCP) servers\n/// when using dependency injection. It exposes methods for registering tools, prompts, custom request handlers,\n/// and server transports, allowing for comprehensive server configuration through a chain of method calls.\n/// \n/// \n/// The builder is obtained from the extension\n/// method and provides access to the underlying service collection via the property.\n/// \n/// \npublic interface IMcpServerBuilder\n{\n /// \n /// Gets the associated service collection.\n /// \n IServiceCollection Services { get; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class EchoTool\n{\n [McpServerTool(Name = \"echo\"), Description(\"Echoes the message back to the client.\")]\n public static string Echo(string message) => $\"Echo: {message}\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionId.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed class StatelessSessionId\n{\n [JsonPropertyName(\"clientInfo\")]\n public Implementation? ClientInfo { get; init; }\n\n [JsonPropertyName(\"userIdClaim\")]\n public UserIdClaim? UserIdClaim { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptResult.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// \n/// For integration with AI client libraries, can be converted to\n/// a collection of objects using the extension method.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class GetPromptResult : Result\n{\n /// \n /// Gets or sets an optional description for the prompt.\n /// \n /// \n /// \n /// This description provides contextual information about the prompt's purpose and use cases.\n /// It helps developers understand what the prompt is designed for and how it should be used.\n /// \n /// \n /// When returned from a server in response to a request,\n /// this description can be used by client applications to provide context about the prompt or to\n /// display in user interfaces.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets the prompt that the server offers.\n /// \n [JsonPropertyName(\"messages\")]\n public IList Messages { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's response to a request, \n/// containing suggested values for a given argument.\n/// \n/// \n/// \n/// is returned by the server in response to a \n/// request from the client. It provides suggested completions or valid values for a specific argument in a tool or resource reference.\n/// \n/// \n/// The result contains a object with suggested values, pagination information,\n/// and the total number of available completions. This is similar to auto-completion functionality in code editors.\n/// \n/// \n/// Clients typically use this to implement auto-suggestion features when users are inputting parameters\n/// for tool calls or resource references.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteResult : Result\n{\n /// \n /// Gets or sets the completion object containing the suggested values and pagination information.\n /// \n /// \n /// If no completions are available for the given input, the \n /// collection will be empty.\n /// \n [JsonPropertyName(\"completion\")]\n public Completion Completion { get; set; } = new Completion();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common request methods used in the MCP protocol.\n/// \npublic static class RequestMethods\n{\n /// \n /// The name of the request method sent from the client to request a list of the server's tools.\n /// \n public const string ToolsList = \"tools/list\";\n\n /// \n /// The name of the request method sent from the client to request that the server invoke a specific tool.\n /// \n public const string ToolsCall = \"tools/call\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's prompts.\n /// \n public const string PromptsList = \"prompts/list\";\n\n /// \n /// The name of the request method sent by the client to get a prompt provided by the server.\n /// \n public const string PromptsGet = \"prompts/get\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resources.\n /// \n public const string ResourcesList = \"resources/list\";\n\n /// \n /// The name of the request method sent from the client to read a specific server resource.\n /// \n public const string ResourcesRead = \"resources/read\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resource templates.\n /// \n public const string ResourcesTemplatesList = \"resources/templates/list\";\n\n /// \n /// The name of the request method sent from the client to request \n /// notifications from the server whenever a particular resource changes.\n /// \n public const string ResourcesSubscribe = \"resources/subscribe\";\n\n /// \n /// The name of the request method sent from the client to request unsubscribing from \n /// notifications from the server.\n /// \n public const string ResourcesUnsubscribe = \"resources/unsubscribe\";\n\n /// \n /// The name of the request method sent from the server to request a list of the client's roots.\n /// \n public const string RootsList = \"roots/list\";\n\n /// \n /// The name of the request method sent by either endpoint to check that the connected endpoint is still alive.\n /// \n public const string Ping = \"ping\";\n\n /// \n /// The name of the request method sent from the client to the server to adjust the logging level.\n /// \n /// \n /// This request allows clients to control which log messages they receive from the server\n /// by setting a minimum severity threshold. After processing this request, the server will\n /// send log messages with severity at or above the specified level to the client as\n /// notifications.\n /// \n public const string LoggingSetLevel = \"logging/setLevel\";\n\n /// \n /// The name of the request method sent from the client to the server to ask for completion suggestions.\n /// \n /// \n /// This is used to provide autocompletion-like functionality for arguments in a resource reference or a prompt template.\n /// The client provides a reference (resource or prompt), argument name, and partial value, and the server \n /// responds with matching completion options.\n /// \n public const string CompletionComplete = \"completion/complete\";\n\n /// \n /// The name of the request method sent from the server to sample an large language model (LLM) via the client.\n /// \n /// \n /// This request allows servers to utilize an LLM available on the client side to generate text or image responses\n /// based on provided messages. It is part of the sampling capability in the Model Context Protocol and enables servers to access\n /// client-side AI models without needing direct API access to those models.\n /// \n public const string SamplingCreateMessage = \"sampling/createMessage\";\n\n /// \n /// The name of the request method sent from the client to the server to elicit additional information from the user via the client.\n /// \n /// \n /// This request is used when the server needs more information from the client to proceed with a task or interaction.\n /// Servers can request structured data from users, with optional JSON schemas to validate responses.\n /// \n public const string ElicitationCreate = \"elicitation/create\";\n\n /// \n /// The name of the request method sent from the client to the server when it first connects, asking it initialize.\n /// \n /// \n /// The initialize request is the first request sent by the client to the server. It provides client information\n /// and capabilities to the server during connection establishment. The server responds with its own capabilities\n /// and information, establishing the protocol version and available features for the session.\n /// \n public const string Initialize = \"initialize\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcErrorDetail.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents detailed error information for JSON-RPC error responses.\n/// \n/// \n/// This class is used as part of the message to provide structured \n/// error information when a request cannot be fulfilled. The JSON-RPC 2.0 specification defines\n/// a standard format for error responses that includes a numeric code, a human-readable message,\n/// and optional additional data.\n/// \npublic sealed class JsonRpcErrorDetail\n{\n /// \n /// Gets an integer error code according to the JSON-RPC specification.\n /// \n [JsonPropertyName(\"code\")]\n public required int Code { get; init; }\n\n /// \n /// Gets a short description of the error.\n /// \n /// \n /// This is expected to be a brief, human-readable explanation of what went wrong.\n /// For standard error codes, it's recommended to use the descriptions defined \n /// in the JSON-RPC 2.0 specification.\n /// \n [JsonPropertyName(\"message\")]\n public required string Message { get; init; }\n\n /// \n /// Gets optional additional error data.\n /// \n /// \n /// This property can contain any additional information that might help the client\n /// understand or resolve the error. Common examples include validation errors,\n /// stack traces (in development environments), or contextual information about\n /// the error condition.\n /// \n [JsonPropertyName(\"data\")]\n public object? Data { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ReadResourceResult : Result\n{\n /// \n /// Gets or sets a list of objects that this resource contains.\n /// \n /// \n /// This property contains the actual content of the requested resource, which can be\n /// either text-based () or binary ().\n /// The type of content included depends on the resource being accessed.\n /// \n [JsonPropertyName(\"contents\")]\n public IList Contents { get; set; } = [];\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/IsExternalInit.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Reserved to be used by the compiler for tracking metadata.\n /// This class should not be used by developers in source code.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n internal static class IsExternalInit;\n}\n#else\n// The compiler emits a reference to the internal copy of this type in the non-.NET builds,\n// so we must include a forward to be compatible.\n[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExternalInit))]\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingMessageNotificationParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a log message is generated.\n/// \n/// \n/// \n/// Logging notifications allow servers to communicate diagnostic information to clients with varying severity levels.\n/// Clients can filter these messages based on the and properties.\n/// \n/// \n/// If no request has been sent from the client, the server may decide which\n/// messages to send automatically.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class LoggingMessageNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the severity of this log message.\n /// \n [JsonPropertyName(\"level\")]\n public LoggingLevel Level { get; init; }\n\n /// \n /// Gets or sets an optional name of the logger issuing this message.\n /// \n /// \n /// \n /// typically represents a category or component in the server's logging system.\n /// The logger name is useful for filtering and routing log messages in client applications.\n /// \n /// \n /// When implementing custom servers, choose clear, hierarchical logger names to help\n /// clients understand the source of log messages.\n /// \n /// \n [JsonPropertyName(\"logger\")]\n public string? Logger { get; init; }\n\n /// \n /// Gets or sets the data to be logged, such as a string message.\n /// \n [JsonPropertyName(\"data\")]\n public JsonElement? Data { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/UnsubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Sent from the client to cancel resource update notifications from the server for a specific resource.\n/// \n/// \n/// \n/// After a client has subscribed to resource updates using , \n/// this message can be sent to stop receiving notifications for a specific resource. \n/// This is useful for conserving resources and network bandwidth when \n/// the client no longer needs to track changes to a particular resource.\n/// \n/// \n/// The unsubscribe operation is idempotent, meaning it can be called multiple times \n/// for the same resource without causing errors, even if there is no active subscription.\n/// \n/// \npublic sealed class UnsubscribeRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to unsubscribe from. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Implementation.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides the name and version of an MCP implementation.\n/// \n/// \n/// \n/// The class is used to identify MCP clients and servers during the initialization handshake.\n/// It provides version and name information that can be used for compatibility checks, logging, and debugging.\n/// \n/// \n/// Both clients and servers provide this information during connection establishment.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class Implementation : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the version of the implementation.\n /// \n /// \n /// The version is used during client-server handshake to identify implementation versions,\n /// which can be important for troubleshooting compatibility issues or when reporting bugs.\n /// \n [JsonPropertyName(\"version\")]\n public required string Version { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a from the server.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageResult : Result\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the name of the model that generated the message.\n /// \n /// \n /// \n /// This should contain the specific model identifier such as \"claude-3-5-sonnet-20241022\" or \"o3-mini\".\n /// \n /// \n /// This property allows the server to know which model was used to generate the response,\n /// enabling appropriate handling based on the model's capabilities and characteristics.\n /// \n /// \n [JsonPropertyName(\"model\")]\n public required string Model { get; init; }\n\n /// \n /// Gets or sets the reason why message generation (sampling) stopped, if known.\n /// \n /// \n /// Common values include:\n /// \n /// endTurnThe model naturally completed its response.\n /// maxTokensThe response was truncated due to reaching token limits.\n /// stopSequenceA specific stop sequence was encountered during generation.\n /// \n /// \n [JsonPropertyName(\"stopReason\")]\n public string? StopReason { get; init; }\n\n /// \n /// Gets or sets the role of the user who generated the message.\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Root.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a root URI and its metadata in the Model Context Protocol.\n/// \n/// \n/// Root URIs serve as entry points for resource navigation, typically representing\n/// top-level directories or container resources that can be accessed and traversed.\n/// Roots provide a hierarchical structure for organizing and accessing resources within the protocol.\n/// Each root has a URI that uniquely identifies it and optional metadata like a human-readable name.\n/// \npublic sealed class Root\n{\n /// \n /// Gets or sets the URI of the root.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for the root.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n\n /// \n /// Gets or sets additional metadata for the root.\n /// \n /// \n /// This is reserved by the protocol for future use.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonElement? Meta { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Annotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents annotations that can be attached to content, resources, and resource templates.\n/// \n/// \n/// Annotations enable filtering and prioritization of content for different audiences.\n/// See the schema for details.\n/// \npublic sealed class Annotations\n{\n /// \n /// Gets or sets the intended audience for this content as an array of values.\n /// \n [JsonPropertyName(\"audience\")]\n public IList? Audience { get; init; }\n\n /// \n /// Gets or sets a value indicating how important this data is for operating the server.\n /// \n /// \n /// The value is a floating-point number between 0 and 1, where 0 represents the lowest priority\n /// 1 represents highest priority.\n /// \n [JsonPropertyName(\"priority\")]\n public float? Priority { get; init; }\n\n /// \n /// Gets or sets the moment the resource was last modified.\n /// \n /// \n /// The corresponding JSON should be an ISO 8601 formatted string (e.g., \\\"2025-01-12T15:00:58Z\\\").\n /// Examples: last activity timestamp in an open file, timestamp when the resource was attached, etc.\n /// \n [JsonPropertyName(\"lastModified\")]\n public DateTimeOffset? LastModified { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCollection.cs", "namespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their URI templates.\npublic sealed class McpServerResourceCollection()\n : McpServerPrimitiveCollection(UriTemplate.UriTemplateComparer.Instance);"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request sent by a client to a server during the protocol handshake.\n/// \n/// \n/// \n/// The is the first message sent in the Model Context Protocol\n/// communication flow. It establishes the connection between client and server, negotiates the protocol\n/// version, and declares the client's capabilities.\n/// \n/// \n/// After sending this request, the client should wait for an response\n/// before sending an notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the client wants to use.\n /// \n /// \n /// \n /// Protocol version is specified using a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// The client and server must agree on a protocol version to communicate successfully.\n /// \n /// \n /// During initialization, the server will check if it supports this requested version. If there's a \n /// mismatch, the server will reject the connection with a version mismatch error.\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the client's capabilities.\n /// \n /// \n /// Capabilities define the features the client supports, such as \"sampling\" or \"roots\".\n /// \n [JsonPropertyName(\"capabilities\")]\n public ClientCapabilities? Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the client implementation, including its name and version.\n /// \n /// \n /// This information is required during the initialization handshake to identify the client.\n /// Servers may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"clientInfo\")]\n public required Implementation ClientInfo { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptArgument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument that a prompt can accept for templating and customization.\n/// \n/// \n/// \n/// The class defines metadata for arguments that can be provided\n/// to a prompt. These arguments are used to customize or parameterize prompts when they are \n/// retrieved using requests.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptArgument : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the argument's purpose and expected values.\n /// \n /// \n /// This description helps developers understand what information should be provided\n /// for this argument and how it will affect the generated prompt.\n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets an indication as to whether this argument must be provided when requesting the prompt.\n /// \n /// \n /// When set to , the client must include this argument when making a request.\n /// If a required argument is missing, the server should respond with an error.\n /// \n [JsonPropertyName(\"required\")]\n public bool? Required { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelPreferences.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's preferences for model selection, requested of the client during sampling.\n/// \n/// \n/// \n/// Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n/// rarely straightforward. Different models excel in different areas—some are\n/// faster but less capable, others are more capable but more expensive, and so\n/// on. This class allows servers to express their priorities across multiple\n/// dimensions to help clients make an appropriate selection for their use case.\n/// \n/// \n/// These preferences are always advisory. The client may ignore them. It is also\n/// up to the client to decide how to interpret these preferences and how to\n/// balance them against other considerations.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelPreferences\n{\n /// \n /// Gets or sets how much to prioritize cost when selecting a model.\n /// \n /// \n /// A value of 0 means cost is not important, while a value of 1 means cost is the most important factor.\n /// \n [JsonPropertyName(\"costPriority\")]\n public float? CostPriority { get; init; }\n\n /// \n /// Gets or sets optional hints to use for model selection.\n /// \n [JsonPropertyName(\"hints\")]\n public IReadOnlyList? Hints { get; init; }\n\n /// \n /// Gets or sets how much to prioritize sampling speed (latency) when selecting a model.\n /// \n /// \n /// A value of 0 means speed is not important, while a value of 1 means speed is the most important factor.\n /// \n [JsonPropertyName(\"speedPriority\")]\n public float? SpeedPriority { get; init; }\n\n /// \n /// Gets or sets how much to prioritize intelligence and capabilities when selecting a model.\n /// \n /// \n /// A value of 0 means intelligence is not important, while a value of 1 means intelligence is the most important factor.\n /// \n [JsonPropertyName(\"intelligencePriority\")]\n public float? IntelligencePriority { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CancelledNotificationParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification indicating that a request has been cancelled by the client,\n/// and that any associated processing should cease immediately.\n/// \n/// \n/// This class is typically used in conjunction with the \n/// method identifier. When a client sends this notification, the server should attempt to\n/// cancel any ongoing operations associated with the specified request ID.\n/// \npublic sealed class CancelledNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the ID of the request to cancel.\n /// \n /// \n /// This must match the ID of an in-flight request that the sender wishes to cancel.\n /// \n [JsonPropertyName(\"requestId\")]\n public RequestId RequestId { get; set; }\n\n /// \n /// Gets or sets an optional string describing the reason for the cancellation request.\n /// \n [JsonPropertyName(\"reason\")]\n public string? Reason { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/BlobResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the binary contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when binary data needs to be exchanged through\n/// the Model Context Protocol. The binary data is represented as a base64-encoded string\n/// in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for text-based resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class BlobResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the base64-encoded string representing the binary data of the item.\n /// \n [JsonPropertyName(\"blob\")]\n public string Blob { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common notification methods used in the MCP protocol.\n/// \npublic static class NotificationMethods\n{\n /// \n /// The name of notification sent by a server when the list of available tools changes.\n /// \n /// \n /// This notification informs clients that the set of available tools has been modified.\n /// Changes may include tools being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their tool list by calling the appropriate \n /// method to get the updated list of tools.\n /// \n public const string ToolListChangedNotification = \"notifications/tools/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available prompts changes.\n /// \n /// \n /// This notification informs clients that the set of available prompts has been modified.\n /// Changes may include prompts being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their prompt list by calling the appropriate \n /// method to get the updated list of prompts.\n /// \n public const string PromptListChangedNotification = \"notifications/prompts/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available resources changes.\n /// \n /// \n /// This notification informs clients that the set of available resources has been modified.\n /// Changes may include resources being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their resource list by calling the appropriate \n /// method to get the updated list of resources.\n /// \n public const string ResourceListChangedNotification = \"notifications/resources/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a resource is updated.\n /// \n /// \n /// This notification is used to inform clients about changes to a specific resource they have subscribed to.\n /// When a resource is updated, the server sends this notification to all clients that have subscribed to that resource.\n /// \n public const string ResourceUpdatedNotification = \"notifications/resources/updated\";\n\n /// \n /// The name of the notification sent by the client when roots have been updated.\n /// \n /// \n /// \n /// This notification informs the server that the client's \"roots\" have changed. \n /// Roots define the boundaries of where servers can operate within the filesystem, \n /// allowing them to understand which directories and files they have access to. Servers \n /// can request the list of roots from supporting clients and receive notifications when that list changes.\n /// \n /// \n /// After receiving this notification, servers may refresh their knowledge of roots by calling the appropriate \n /// method to get the updated list of roots from the client.\n /// \n /// \n public const string RootsListChangedNotification = \"notifications/roots/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a log message is generated.\n /// \n /// \n /// \n /// This notification is used by the server to send log messages to clients. Log messages can include\n /// different severity levels, such as debug, info, warning, or error, and an optional logger name to\n /// identify the source component.\n /// \n /// \n /// The minimum logging level that triggers notifications can be controlled by clients using the\n /// request. If no level has been set by a client, \n /// the server may determine which messages to send based on its own configuration.\n /// \n /// \n public const string LoggingMessageNotification = \"notifications/message\";\n\n /// \n /// The name of the notification sent from the client to the server after initialization has finished.\n /// \n /// \n /// \n /// This notification is sent by the client after it has received and processed the server's response to the \n /// request. It signals that the client is ready to begin normal operation \n /// and that the initialization phase is complete.\n /// \n /// \n /// After receiving this notification, the server can begin sending notifications and processing\n /// further requests from the client.\n /// \n /// \n public const string InitializedNotification = \"notifications/initialized\";\n\n /// \n /// The name of the notification sent to inform the receiver of a progress update for a long-running request.\n /// \n /// \n /// \n /// This notification provides updates on the progress of long-running operations. It includes\n /// a progress token that associates the notification with a specific request, the current progress value,\n /// and optionally, a total value and a descriptive message.\n /// \n /// \n /// Progress notifications may be sent by either the client or the server, depending on the context.\n /// Progress notifications enable clients to display progress indicators for operations that might take\n /// significant time to complete, such as large file uploads, complex computations, or resource-intensive\n /// processing tasks.\n /// \n /// \n public const string ProgressNotification = \"notifications/progress\";\n\n /// \n /// The name of the notification sent to indicate that a previously-issued request should be canceled.\n /// \n /// \n /// \n /// From the issuer's perspective, the request should still be in-flight. However, due to communication latency,\n /// it is always possible that this notification may arrive after the request has already finished.\n /// \n /// \n /// This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n /// \n /// \n /// A client must not attempt to cancel its `initialize` request.\n /// \n /// \n public const string CancelledNotification = \"notifications/cancelled\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IMcpClient.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) client that connects to and communicates with an MCP server.\n/// \npublic interface IMcpClient : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the connected server.\n /// \n /// The client is not connected.\n ServerCapabilities ServerCapabilities { get; }\n\n /// \n /// Gets the implementation information of the connected server.\n /// \n /// \n /// \n /// This property provides identification details about the connected server, including its name and version.\n /// It is populated during the initialization handshake and is available after a successful connection.\n /// \n /// \n /// This information can be useful for logging, debugging, compatibility checks, and displaying server\n /// information to users.\n /// \n /// \n /// The client is not connected.\n Implementation ServerInfo { get; }\n\n /// \n /// Gets any instructions describing how to use the connected server and its features.\n /// \n /// \n /// \n /// This property contains instructions provided by the server during initialization that explain\n /// how to effectively use its capabilities. These instructions can include details about available\n /// tools, expected input formats, limitations, or any other helpful information.\n /// \n /// \n /// This can be used by clients to improve an LLM's understanding of available tools, prompts, and resources. \n /// It can be thought of like a \"hint\" to the model and may be added to a system prompt.\n /// \n /// \n string? ServerInstructions { get; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/TokenContainer.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a token response from the OAuth server.\n/// \ninternal sealed class TokenContainer\n{\n /// \n /// Gets or sets the access token.\n /// \n [JsonPropertyName(\"access_token\")]\n public string AccessToken { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the refresh token.\n /// \n [JsonPropertyName(\"refresh_token\")]\n public string? RefreshToken { get; set; }\n\n /// \n /// Gets or sets the number of seconds until the access token expires.\n /// \n [JsonPropertyName(\"expires_in\")]\n public int ExpiresIn { get; set; }\n\n /// \n /// Gets or sets the extended expiration time in seconds.\n /// \n [JsonPropertyName(\"ext_expires_in\")]\n public int ExtExpiresIn { get; set; }\n\n /// \n /// Gets or sets the token type (typically \"Bearer\").\n /// \n [JsonPropertyName(\"token_type\")]\n public string TokenType { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the scope of the access token.\n /// \n [JsonPropertyName(\"scope\")]\n public string Scope { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the timestamp when the token was obtained.\n /// \n [JsonIgnore]\n public DateTimeOffset ObtainedAt { get; set; }\n\n /// \n /// Gets the timestamp when the token expires, calculated from ObtainedAt and ExpiresIn.\n /// \n [JsonIgnore]\n public DateTimeOffset ExpiresAt => ObtainedAt.AddSeconds(ExpiresIn);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing members that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing members that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithResourcesFromAssembly, it enables automatic registration of resources without explicitly listing each\n/// resource class. The attribute is not necessary when a reference to the type is provided directly to a method\n/// like McpServerBuilderExtensions.WithResources.\n/// \n/// \n/// Within a class marked with this attribute, individual members that should be exposed as\n/// resources must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerResourceTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelHint.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides hints to use for model selection.\n/// \n/// \n/// \n/// When multiple hints are specified in , they are evaluated in order,\n/// with the first match taking precedence. Clients should prioritize these hints over numeric priorities.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelHint\n{\n /// \n /// Gets or sets a hint for a model name.\n /// \n /// \n /// The specified string can be a partial or full model name. Clients may also \n /// map hints to equivalent models from different providers. Clients make the final model\n /// selection based on these preferences and their available models.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a request from the server,\n/// containing available roots.\n/// \n/// \n/// \n/// This result is returned when a server sends a request to discover \n/// available roots on the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListRootsResult : Result\n{\n /// \n /// Gets or sets the list of root URIs provided by the client.\n /// \n /// \n /// This collection contains all available root URIs and their associated metadata.\n /// Each root serves as an entry point for resource navigation in the Model Context Protocol.\n /// \n [JsonPropertyName(\"roots\")]\n public required IReadOnlyList Roots { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceUpdatedNotificationParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a subscribed resource changes.\n/// \n/// \n/// \n/// When a client subscribes to resource updates using , the server will\n/// send notifications with this payload whenever the subscribed resource is modified. These notifications\n/// allow clients to maintain synchronized state without needing to poll the server for changes.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceUpdatedNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the URI of the resource that was updated.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Prompt.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a prompt that the server offers.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Prompt : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets an optional description of what this prompt provides.\n /// \n /// \n /// \n /// This description helps developers understand the purpose and use cases for the prompt.\n /// It should explain what the prompt is designed to accomplish and any important context.\n /// \n /// \n /// The description is typically used in documentation, UI displays, and for providing context\n /// to client applications that may need to choose between multiple available prompts.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a list of arguments that this prompt accepts for templating and customization.\n /// \n /// \n /// \n /// This list defines the arguments that can be provided when requesting the prompt.\n /// Each argument specifies metadata like name, description, and whether it's required.\n /// \n /// \n /// When a client makes a request, it can provide values for these arguments\n /// which will be substituted into the prompt template or otherwise used to render the prompt.\n /// \n /// \n [JsonPropertyName(\"arguments\")]\n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available prompts.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available prompts on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many prompts.\n/// The server can provide the property to indicate there are more\n/// prompts available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListPromptsResult : PaginatedResult\n{\n /// \n /// A list of prompts or prompt templates that the server offers.\n /// \n [JsonPropertyName(\"prompts\")]\n public IList Prompts { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client,\n/// containing available resource templates.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover \n/// available resource templates on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resource templates.\n/// The server can provide the property to indicate there are more\n/// resource templates available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourceTemplatesResult : PaginatedResult\n{\n /// \n /// Gets or sets a list of resource templates that the server offers.\n /// \n /// \n /// This collection contains all the resource templates returned in the current page of results.\n /// Each provides metadata about resources available on the server,\n /// including URI templates, names, descriptions, and MIME types.\n /// \n [JsonPropertyName(\"resourceTemplates\")]\n public IList ResourceTemplates { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to request real-time notifications from the server whenever a particular resource changes.\n/// \n/// \n/// \n/// The subscription mechanism allows clients to be notified about changes to specific resources\n/// identified by their URI. When a subscribed resource changes, the server sends a notification\n/// to the client with the updated resource information.\n/// \n/// \n/// Subscriptions remain active until explicitly canceled using \n/// or until the connection is terminated.\n/// \n/// \n/// The server may refuse or limit subscriptions based on its capabilities or resource constraints.\n/// \n/// \npublic sealed class SubscribeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the URI of the resource to subscribe to.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolResult.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// \n/// Any errors that originate from the tool should be reported inside the result\n/// object, with set to true, rather than as a .\n/// \n/// \n/// However, any errors in finding the tool, an error indicating that the\n/// server does not support tool calls, or any other exceptional conditions,\n/// should be reported as an MCP error response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CallToolResult : Result\n{\n /// \n /// Gets or sets the response content from the tool call.\n /// \n [JsonPropertyName(\"content\")]\n public IList Content { get; set; } = [];\n\n /// \n /// Gets or sets an optional JSON object representing the structured result of the tool call.\n /// \n [JsonPropertyName(\"structuredContent\")]\n public JsonNode? StructuredContent { get; set; }\n\n /// \n /// Gets or sets an indication of whether the tool call was unsuccessful.\n /// \n /// \n /// When set to , it signifies that the tool execution failed.\n /// Tool errors are reported with this property set to and details in the \n /// property, rather than as protocol-level errors. This allows LLMs to see that an error occurred\n /// and potentially self-correct in subsequent requests.\n /// \n [JsonPropertyName(\"isError\")]\n public bool? IsError { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SetLevelRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to enable or adjust logging.\n/// \n/// \n/// This request allows clients to configure the level of logging information they want to receive from the server.\n/// The server will send notifications for log events at the specified level and all higher (more severe) levels.\n/// \npublic sealed class SetLevelRequestParams : RequestParams\n{\n /// \n /// Gets or sets the level of logging that the client wants to receive from the server. \n /// \n [JsonPropertyName(\"level\")]\n public required LoggingLevel Level { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingMessage.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued to or received from an LLM API within the Model Context Protocol.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be text or images.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent prompts or queries for LLM sampling. They form the core data structure for text generation requests\n/// within the Model Context Protocol.\n/// \n/// \n/// While similar to , the is focused on direct LLM sampling\n/// operations rather than the enhanced resource embedding capabilities provided by .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class SamplingMessage\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the role of the message sender, indicating whether it's from a \"user\" or an \"assistant\".\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request sent to the server during connection establishment.\n/// \n/// \n/// \n/// The is sent by the server in response to an \n/// message from the client. It contains information about the server, its capabilities, and the protocol version\n/// that will be used for the session.\n/// \n/// \n/// After receiving this response, the client should send an \n/// notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeResult : Result\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the server will use for this session.\n /// \n /// \n /// \n /// This is the protocol version the server has agreed to use, which should match the client's \n /// requested version. If there's a mismatch, the client should throw an exception to prevent \n /// communication issues due to incompatible protocol versions.\n /// \n /// \n /// The protocol uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the server's capabilities.\n /// \n /// \n /// This defines the features the server supports, such as \"tools\", \"prompts\", \"resources\", or \"logging\", \n /// and other protocol-specific functionality.\n /// \n [JsonPropertyName(\"capabilities\")]\n public required ServerCapabilities Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the server implementation, including its name and version.\n /// \n /// \n /// This information identifies the server during the initialization handshake.\n /// Clients may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"serverInfo\")]\n public required Implementation ServerInfo { get; init; }\n\n /// \n /// Gets or sets optional instructions for using the server and its features.\n /// \n /// \n /// \n /// These instructions provide guidance to clients on how to effectively use the server's capabilities.\n /// They can include details about available tools, expected input formats, limitations,\n /// or any other information that helps clients interact with the server properly.\n /// \n /// \n /// Client applications often use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n /// \n [JsonPropertyName(\"instructions\")]\n public string? Instructions { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcNotification.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification message in the JSON-RPC protocol.\n/// \n/// \n/// Notifications are messages that do not require a response and are not matched with a response message.\n/// They are useful for one-way communication, such as log notifications and progress updates.\n/// Unlike requests, notifications do not include an ID field, since there will be no response to match with it.\n/// \npublic sealed class JsonRpcNotification : JsonRpcMessage\n{\n /// \n /// Gets or sets the name of the notification method.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Gets or sets optional parameters for the notification.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionIdJsonContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\n[JsonSerializable(typeof(StatelessSessionId))]\ninternal sealed partial class StatelessSessionIdJsonContext : JsonSerializerContext;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcResponse.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A successful response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Response messages are sent in reply to a request message and contain the result of the method execution.\n/// Each response includes the same ID as the original request, allowing the sender to match responses\n/// with their corresponding requests.\n/// \n/// \n/// This class represents a successful response with a result. For error responses, see .\n/// \n/// \npublic sealed class JsonRpcResponse : JsonRpcMessageWithId\n{\n /// \n /// Gets the result of the method invocation.\n /// \n /// \n /// This property contains the result data returned by the server in response to the JSON-RPC method request.\n /// \n [JsonPropertyName(\"result\")]\n public required JsonNode? Result { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/RequiredMemberAttribute.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Specifies that a type has required members or that a member is required.\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\n [EditorBrowsable(EditorBrowsableState.Never)]\n internal sealed class RequiredMemberAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContextInclusion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Specifies the context inclusion options for a request in the Model Context Protocol (MCP).\n/// \n/// \n/// See the schema for details.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum ContextInclusion\n{\n /// \n /// Indicates that no context should be included.\n /// \n [JsonStringEnumMemberName(\"none\")]\n None,\n\n /// \n /// Indicates that context from the server that sent the request should be included.\n /// \n [JsonStringEnumMemberName(\"thisServer\")]\n ThisServer,\n\n /// \n /// Indicates that context from all servers that the client is connected to should be included.\n /// \n [JsonStringEnumMemberName(\"allServers\")]\n AllServers\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Role.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the type of role in the Model Context Protocol conversation.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum Role\n{\n /// \n /// Corresponds to a human user in the conversation.\n /// \n [JsonStringEnumMemberName(\"user\")]\n User,\n\n /// \n /// Corresponds to the AI assistant in the conversation.\n /// \n [JsonStringEnumMemberName(\"assistant\")]\n Assistant\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available resources.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available resources on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resources.\n/// The server can provide the property to indicate there are more\n/// resources available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourcesResult : PaginatedResult\n{\n /// \n /// A list of resources that the server offers.\n /// \n [JsonPropertyName(\"resources\")]\n public IList Resources { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcError.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an error response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Error responses are sent when a request cannot be fulfilled or encounters an error during processing.\n/// Like successful responses, error messages include the same ID as the original request, allowing the\n/// sender to match errors with their corresponding requests.\n/// \n/// \n/// Each error response contains a structured error detail object with a numeric code, descriptive message,\n/// and optional additional data to provide more context about the error.\n/// \n/// \npublic sealed class JsonRpcError : JsonRpcMessageWithId\n{\n /// \n /// Gets detailed error information for the failed request, containing an error code, \n /// message, and optional additional data\n /// \n [JsonPropertyName(\"error\")]\n public required JsonRpcErrorDetail Error { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available tools.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available tools on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many tools.\n/// The server can provide the property to indicate there are more\n/// tools available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListToolsResult : PaginatedResult\n{\n /// \n /// The server's response to a tools/list request from the client.\n /// \n [JsonPropertyName(\"tools\")]\n public IList Tools { get; set; } = [];\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMemberTypes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Specifies the types of members that are dynamically accessed.\n///\n/// This enumeration has a attribute that allows a\n/// bitwise combination of its member values.\n/// \n[Flags]\ninternal enum DynamicallyAccessedMemberTypes\n{\n /// \n /// Specifies no members.\n /// \n None = 0,\n\n /// \n /// Specifies the default, parameterless public constructor.\n /// \n PublicParameterlessConstructor = 0x0001,\n\n /// \n /// Specifies all public constructors.\n /// \n PublicConstructors = 0x0002 | PublicParameterlessConstructor,\n\n /// \n /// Specifies all non-public constructors.\n /// \n NonPublicConstructors = 0x0004,\n\n /// \n /// Specifies all public methods.\n /// \n PublicMethods = 0x0008,\n\n /// \n /// Specifies all non-public methods.\n /// \n NonPublicMethods = 0x0010,\n\n /// \n /// Specifies all public fields.\n /// \n PublicFields = 0x0020,\n\n /// \n /// Specifies all non-public fields.\n /// \n NonPublicFields = 0x0040,\n\n /// \n /// Specifies all public nested types.\n /// \n PublicNestedTypes = 0x0080,\n\n /// \n /// Specifies all non-public nested types.\n /// \n NonPublicNestedTypes = 0x0100,\n\n /// \n /// Specifies all public properties.\n /// \n PublicProperties = 0x0200,\n\n /// \n /// Specifies all non-public properties.\n /// \n NonPublicProperties = 0x0400,\n\n /// \n /// Specifies all public events.\n /// \n PublicEvents = 0x0800,\n\n /// \n /// Specifies all non-public events.\n /// \n NonPublicEvents = 0x1000,\n\n /// \n /// Specifies all interfaces implemented by the type.\n /// \n Interfaces = 0x2000,\n\n /// \n /// Specifies all non-public constructors, including those inherited from base classes.\n /// \n NonPublicConstructorsWithInherited = NonPublicConstructors | 0x4000,\n\n /// \n /// Specifies all non-public methods, including those inherited from base classes.\n /// \n NonPublicMethodsWithInherited = NonPublicMethods | 0x8000,\n\n /// \n /// Specifies all non-public fields, including those inherited from base classes.\n /// \n NonPublicFieldsWithInherited = NonPublicFields | 0x10000,\n\n /// \n /// Specifies all non-public nested types, including those inherited from base classes.\n /// \n NonPublicNestedTypesWithInherited = NonPublicNestedTypes | 0x20000,\n\n /// \n /// Specifies all non-public properties, including those inherited from base classes.\n /// \n NonPublicPropertiesWithInherited = NonPublicProperties | 0x40000,\n\n /// \n /// Specifies all non-public events, including those inherited from base classes.\n /// \n NonPublicEventsWithInherited = NonPublicEvents | 0x80000,\n\n /// \n /// Specifies all public constructors, including those inherited from base classes.\n /// \n PublicConstructorsWithInherited = PublicConstructors | 0x100000,\n\n /// \n /// Specifies all public nested types, including those inherited from base classes.\n /// \n PublicNestedTypesWithInherited = PublicNestedTypes | 0x200000,\n\n /// \n /// Specifies all constructors, including those inherited from base classes.\n /// \n AllConstructors = PublicConstructorsWithInherited | NonPublicConstructorsWithInherited,\n\n /// \n /// Specifies all methods, including those inherited from base classes.\n /// \n AllMethods = PublicMethods | NonPublicMethodsWithInherited,\n\n /// \n /// Specifies all fields, including those inherited from base classes.\n /// \n AllFields = PublicFields | NonPublicFieldsWithInherited,\n\n /// \n /// Specifies all nested types, including those inherited from base classes.\n /// \n AllNestedTypes = PublicNestedTypesWithInherited | NonPublicNestedTypesWithInherited,\n\n /// \n /// Specifies all properties, including those inherited from base classes.\n /// \n AllProperties = PublicProperties | NonPublicPropertiesWithInherited,\n\n /// \n /// Specifies all events, including those inherited from base classes.\n /// \n AllEvents = PublicEvents | NonPublicEventsWithInherited,\n\n /// \n /// Specifies all members.\n /// \n All = ~None\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServerPrimitive.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Represents an MCP server primitive, like a tool or a prompt.\n/// \npublic interface IMcpServerPrimitive\n{\n /// Gets the unique identifier of the primitive.\n string Id { get; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpErrorCode.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents standard JSON-RPC error codes as defined in the MCP specification.\n/// \npublic enum McpErrorCode\n{\n /// \n /// Indicates that the JSON received could not be parsed.\n /// \n /// \n /// This error occurs when the input contains malformed JSON or incorrect syntax.\n /// \n ParseError = -32700,\n\n /// \n /// Indicates that the JSON payload does not conform to the expected Request object structure.\n /// \n /// \n /// The request is considered invalid if it lacks required fields or fails to follow the JSON-RPC protocol.\n /// \n InvalidRequest = -32600,\n\n /// \n /// Indicates that the requested method does not exist or is not available on the server.\n /// \n /// \n /// This error is returned when the method name specified in the request cannot be found.\n /// \n MethodNotFound = -32601,\n\n /// \n /// Indicates that one or more parameters provided in the request are invalid.\n /// \n /// \n /// This error is returned when the parameters do not match the expected method signature or constraints.\n /// This includes cases where required parameters are missing or not understood, such as when a name for\n /// a tool or prompt is not recognized.\n /// \n InvalidParams = -32602,\n\n /// \n /// Indicates that an internal error occurred while processing the request.\n /// \n /// \n /// This error is used when the endpoint encounters an unexpected condition that prevents it from fulfilling the request.\n /// \n InternalError = -32603,\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PingResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request in the Model Context Protocol.\n/// \n/// \n/// \n/// The is returned in response to a request, \n/// which is used to verify that the connection between client and server is still alive and responsive. \n/// Since this is a simple connectivity check, the result is an empty object containing no data.\n/// \n/// \n/// Ping requests can be initiated by either the client or the server to check if the other party\n/// is still responsive.\n/// \n/// \npublic sealed class PingResult : Result;"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParamsMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides metadata related to the request that provides additional protocol-level information.\n/// \n/// \n/// This class contains properties that are used by the Model Context Protocol\n/// for features like progress tracking and other protocol-specific capabilities.\n/// \npublic sealed class RequestParamsMetadata\n{\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n /// \n /// The receiver is not obligated to provide these notifications.\n /// \n [JsonPropertyName(\"progressToken\")]\n public ProgressToken? ProgressToken { get; set; } = default!;\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/SetsRequiredMembersAttribute.cs", "#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]\n internal sealed class SetsRequiredMembersAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithToolsFromAssembly, it enables automatic registration of tools without explicitly listing each tool\n/// class. The attribute is not necessary when a reference to the type is provided directly to a method like WithTools.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// tools must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerToolTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithPromptsFromAssembly, it enables automatic registration of prompts without explicitly listing each prompt class.\n/// The attribute is not necessary when a reference to the type is provided directly to a method like WithPrompts.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// prompts must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerPromptTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the client to the server, informing it that the list of roots has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of tools it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ToolListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptListChangedNotification .cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of prompts it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of resources it can read from has changed. \n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of tools available from the server.\n/// \n/// \n/// The server responds with a containing the available tools.\n/// See the schema for details.\n/// \npublic sealed class ListToolsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resources available from the server.\n/// \n/// \n/// The server responds with a containing the available resources.\n/// See the schema for details.\n/// \npublic sealed class ListResourcesRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a server to request\n/// a list of roots available from the client.\n/// \n/// \n/// The client responds with a containing the client's roots.\n/// See the schema for details.\n/// \npublic sealed class ListRootsRequestParams : RequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of prompts available from the server.\n/// \n/// \n/// The server responds with a containing the available prompts.\n/// See the schema for details.\n/// \npublic sealed class ListPromptsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// sent from the client to the server after initialization has finished.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class InitializedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resource templates available from the server.\n/// \n/// \n/// The server responds with a containing the available resource templates.\n/// See the schema for details.\n/// \npublic sealed class ListResourceTemplatesRequestParams : PaginatedRequestParams;"]], "task_instance_info": {"created_time": "2025-08-20 18:38:49", "created_task_model": "DeepSeek-R1", "class_skeleton": "internal\nstatic\nclass\nTextReaderExtensions\n{\npublic static ValueTask ReadLineAsync (this TextReader reader, CancellationToken cancellationToken) {}\n}", "code_description": "This code segment functions to: Extend asynchronous line reading capabilities with cancellation support, handling both specialized and general stream reader implementations by integrating cancellation token validation before initiating read operations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\npublic static async ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n{\n cancellationToken.ThrowIfCancellationRequested();\n var line = await reader.ReadLineAsync().ConfigureAwait(false);\n cancellationToken.ThrowIfCancellationRequested();\n return line;\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-39-33"}, "editdistance_info": {"edit_distance": 34.2105, "calculate_time": "2025-08-20 18:39:33", "true_code_clean": "internal static class TextReaderExtensions\n{\n public static ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n {\n if (reader is CancellableStreamReader cancellableReader)\n {\n return cancellableReader.ReadLineAsync(cancellationToken)!;\n }\n cancellationToken.ThrowIfCancellationRequested();\n return new ValueTask(reader.ReadLineAsync());\n }\n}", "predict_code_clean": "public static async ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n{\n cancellationToken.ThrowIfCancellationRequested();\n var line = await reader.ReadLineAsync().ConfigureAwait(false);\n cancellationToken.ThrowIfCancellationRequested();\n return line;\n}"}} {"repo_name": "csharp-sdk", "file_name": "/csharp-sdk/src/ModelContextProtocol.Core/NotificationHandlers.cs", "inference_info": {"prefix_code": "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol;\n\n/// Provides thread-safe storage for notification handlers.\ninternal sealed class NotificationHandlers\n{\n /// A dictionary of linked lists of registrations, indexed by the notification method.\n private readonly Dictionary _handlers = [];\n\n /// Gets the object to be used for all synchronization.\n private object SyncObj => _handlers;\n\n /// \n /// Registers a collection of notification handlers at once.\n /// \n /// \n /// A collection of notification method names paired with their corresponding handler functions.\n /// Each key in the collection is a notification method name, and each value is a handler function\n /// that will be invoked when a notification with that method name is received.\n /// \n /// \n /// \n /// This method is typically used during client or server initialization to register\n /// all notification handlers provided in capabilities.\n /// \n /// \n /// Registrations completed with this method are permanent and non-removable.\n /// This differs from handlers registered with which can be temporary.\n /// \n /// \n /// When multiple handlers are registered for the same method, all handlers will be invoked\n /// in reverse order of registration (newest first) when a notification is received.\n /// \n /// \n /// The registered handlers will be invoked by when a notification\n /// with the corresponding method name is received.\n /// \n /// \n public void RegisterRange(IEnumerable>> handlers)\n {\n foreach (var entry in handlers)\n {\n _ = Register(entry.Key, entry.Value, temporary: false);\n }\n }\n\n /// \n /// Adds a notification handler as part of configuring the endpoint.\n /// \n /// The notification method for which the handler is being registered.\n /// The handler being registered.\n /// \n /// if the registration can be removed later; if it cannot.\n /// If , the registration will be permanent: calling \n /// on the returned instance will not unregister the handler.\n /// \n /// \n /// An that when disposed will unregister the handler if is .\n /// \n /// \n /// Multiple handlers can be registered for the same method. When a notification for that method is received,\n /// all registered handlers will be invoked in reverse order of registration (newest first).\n /// \n public IAsyncDisposable Register(\n string method, Func handler, bool temporary = true)\n {\n // Create the new registration instance.\n Registration reg = new(this, method, handler, temporary);\n\n // Store the registration into the dictionary. If there's not currently a registration for the method,\n // then this registration instance just becomes the single value. If there is currently a registration,\n // then this new registration becomes the new head of the linked list, and the old head becomes the next\n // item in the list.\n lock (SyncObj)\n {\n if (_handlers.TryGetValue(method, out var existingHandlerHead))\n {\n reg.Next = existingHandlerHead;\n existingHandlerHead.Prev = reg;\n }\n\n _handlers[method] = reg;\n }\n\n // Return the new registration. It must be disposed of when no longer used, or it will end up being\n // leaked into the list. This is the same as with CancellationToken.Register.\n return reg;\n }\n\n /// \n /// Invokes all registered handlers for the specified notification method.\n /// \n /// The notification method name to invoke handlers for.\n /// The notification object to pass to each handler.\n /// A token that can be used to cancel the operation.\n /// \n /// Handlers are invoked in reverse order of registration (newest first).\n /// If any handler throws an exception, all handlers will still be invoked, and an \n /// containing all exceptions will be thrown after all handlers have been invoked.\n /// \n public async Task InvokeHandlers(string method, JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // If there are no handlers registered for this method, we're done.\n Registration? reg;\n lock (SyncObj)\n {\n if (!_handlers.TryGetValue(method, out reg))\n {\n return;\n }\n }\n\n // Invoke each handler in the list. We guarantee that we'll try to invoke\n // any handlers that were in the list when the list was fetched from the dictionary,\n // which is why DisposeAsync doesn't modify the Prev/Next of the registration being\n // disposed; if those were nulled out, we'd be unable to walk around it in the list\n // if we happened to be on that item when it was disposed.\n List? exceptions = null;\n while (reg is not null)\n {\n try\n {\n await reg.InvokeAsync(notification, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e)\n {\n (exceptions ??= []).Add(e);\n }\n\n lock (SyncObj)\n {\n reg = reg.Next;\n }\n }\n\n if (exceptions is not null)\n {\n throw new AggregateException(exceptions);\n }\n }\n\n /// Provides storage for a handler registration.\n ", "suffix_code": "\n}\n", "middle_code": "private sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable) : IAsyncDisposable\n {\n private static readonly AsyncLocal s_invokingAncestor = new();\n private readonly NotificationHandlers _handlers = handlers;\n private readonly string _method = method;\n private readonly Func _handler = handler;\n private readonly bool _temporary = unregisterable;\n private TaskCompletionSource? _disposeTcs;\n private int _refCount = 1;\n private bool _disposedCalled = false;\n public Registration? Next;\n public Registration? Prev;\n public async ValueTask DisposeAsync()\n {\n if (!_temporary)\n {\n return;\n }\n lock (_handlers.SyncObj)\n {\n if (!_disposedCalled)\n {\n _disposedCalled = true;\n if (_handlers._handlers.TryGetValue(_method, out var handlers) && handlers == this)\n {\n if (Next is not null)\n {\n _handlers._handlers[_method] = Next;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n if (Prev is not null)\n {\n Prev.Next = Next;\n }\n if (Next is not null)\n {\n Next.Prev = Prev;\n }\n if (--_refCount != 0)\n {\n Debug.Assert(_disposeTcs is null);\n _disposeTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);\n }\n }\n }\n if (_disposeTcs is not null && s_invokingAncestor.Value == 0)\n {\n await _disposeTcs.Task.ConfigureAwait(false);\n }\n }\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n if (!_temporary)\n {\n return _handler(notification, cancellationToken);\n }\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n lock (_handlers.SyncObj)\n {\n Debug.Assert(_refCount != 0 || _disposedCalled, $\"Expected {nameof(_disposedCalled)} == true when {nameof(_refCount)} == 0\");\n if (_disposedCalled)\n {\n return;\n }\n Debug.Assert(_refCount > 0);\n _refCount++;\n }\n s_invokingAncestor.Value++;\n try\n {\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n s_invokingAncestor.Value--;\n lock (_handlers.SyncObj)\n {\n _refCount--;\n if (_refCount == 0)\n {\n Debug.Assert(_disposedCalled);\n Debug.Assert(_disposeTcs is not null);\n bool completed = _disposeTcs!.TrySetResult(true);\n Debug.Assert(completed);\n }\n }\n }\n }\n }", "code_description": null, "fill_type": "CLASS_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/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/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.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/Common/Polyfills/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/dd75c45c123055baacd7aa4418f425f412797a29/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs\n// and then modified to build on netstandard2.0.\n\n#if !NET\nusing System.Buffers;\nusing System.Diagnostics;\nusing System.Globalization;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Provides a handler used by the language compiler to process interpolated strings into instances.\n internal ref struct DefaultInterpolatedStringHandler\n {\n // Implementation note:\n // As this type lives in CompilerServices and is only intended to be targeted by the compiler,\n // public APIs eschew argument validation logic in a variety of places, e.g. allowing a null input\n // when one isn't expected to produce a NullReferenceException rather than an ArgumentNullException.\n\n /// Expected average length of formatted data used for an individual interpolation expression result.\n /// \n /// This is inherited from string.Format, and could be changed based on further data.\n /// string.Format actually uses `format.Length + args.Length * 8`, but format.Length\n /// includes the format items themselves, e.g. \"{0}\", and since it's rare to have double-digit\n /// numbers of items, we bump the 8 up to 11 to account for the three extra characters in \"{d}\",\n /// since the compiler-provided base length won't include the equivalent character count.\n /// \n private const int GuessedLengthPerHole = 11;\n /// Minimum size array to rent from the pool.\n /// Same as stack-allocation size used today by string.Format.\n private const int MinimumArrayPoolLength = 256;\n\n /// Optional provider to pass to IFormattable.ToString or ISpanFormattable.TryFormat calls.\n private readonly IFormatProvider? _provider;\n /// Array rented from the array pool and used to back .\n private char[]? _arrayToReturnToPool;\n /// The span to write into.\n private Span _chars;\n /// Position at which to write the next character.\n private int _pos;\n /// Whether provides an ICustomFormatter.\n /// \n /// Custom formatters are very rare. We want to support them, but it's ok if we make them more expensive\n /// in order to make them as pay-for-play as possible. So, we avoid adding another reference type field\n /// to reduce the size of the handler and to reduce required zero'ing, by only storing whether the provider\n /// provides a formatter, rather than actually storing the formatter. This in turn means, if there is a\n /// formatter, we pay for the extra interface call on each AppendFormatted that needs it.\n /// \n private readonly bool _hasCustomFormatter;\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount)\n {\n _provider = null;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = false;\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider)\n {\n _provider = provider;\n _chars = _arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount));\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Creates a handler used to translate an interpolated string into a .\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n /// An object that supplies culture-specific formatting information.\n /// A buffer temporarily transferred to the handler for use as part of its formatting. Contents may be overwritten.\n /// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.\n public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer)\n {\n _provider = provider;\n _chars = initialBuffer;\n _arrayToReturnToPool = null;\n _pos = 0;\n _hasCustomFormatter = provider is not null && HasCustomFormatter(provider);\n }\n\n /// Derives a default length with which to seed the handler.\n /// The number of constant characters outside of interpolation expressions in the interpolated string.\n /// The number of interpolation expressions in the interpolated string.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // becomes a constant when inputs are constant\n internal static int GetDefaultLength(int literalLength, int formattedCount) =>\n Math.Max(MinimumArrayPoolLength, literalLength + (formattedCount * GuessedLengthPerHole));\n\n /// Gets the built .\n /// The built string.\n public override string ToString() => Text.ToString();\n\n /// Gets the built and clears the handler.\n /// The built string.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after\n /// is called on any one of them.\n /// \n public string ToStringAndClear()\n {\n string result = Text.ToString();\n Clear();\n return result;\n }\n\n /// Clears the handler.\n /// \n /// This releases any resources used by the handler. The method should be invoked only\n /// once and as the last thing performed on the handler. Subsequent use is erroneous, ill-defined,\n /// and may destabilize the process, as may using any other copies of the handler after \n /// is called on any one of them.\n /// \n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Clear()\n {\n char[]? toReturn = _arrayToReturnToPool;\n\n // Defensive clear\n _arrayToReturnToPool = null;\n _chars = default;\n _pos = 0;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n /// Gets a span of the characters appended to the handler.\n public ReadOnlySpan Text => _chars.Slice(0, _pos);\n\n /// Writes the specified string to the handler.\n /// The string to write.\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void AppendLiteral(string value)\n {\n if (value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopyString(value);\n }\n }\n\n #region AppendFormatted\n // Design note:\n // The compiler requires a AppendFormatted overload for anything that might be within an interpolation expression;\n // if it can't find an appropriate overload, for handlers in general it'll simply fail to compile.\n // (For target-typing to string where it uses DefaultInterpolatedStringHandler implicitly, it'll instead fall back to\n // its other mechanisms, e.g. using string.Format. This fallback has the benefit that if we miss a case,\n // interpolated strings will still work, but it has the downside that a developer generally won't know\n // if the fallback is happening and they're paying more.)\n //\n // At a minimum, then, we would need an overload that accepts:\n // (object value, int alignment = 0, string? format = null)\n // Such an overload would provide the same expressiveness as string.Format. However, this has several\n // shortcomings:\n // - Every value type in an interpolation expression would be boxed.\n // - ReadOnlySpan could not be used in interpolation expressions.\n // - Every AppendFormatted call would have three arguments at the call site, bloating the IL further.\n // - Every invocation would be more expensive, due to lack of specialization, every call needing to account\n // for alignment and format, etc.\n //\n // To address that, we could just have overloads for T and ReadOnlySpan:\n // (T)\n // (T, int alignment)\n // (T, string? format)\n // (T, int alignment, string? format)\n // (ReadOnlySpan)\n // (ReadOnlySpan, int alignment)\n // (ReadOnlySpan, string? format)\n // (ReadOnlySpan, int alignment, string? format)\n // but this also has shortcomings:\n // - Some expressions that would have worked with an object overload will now force a fallback to string.Format\n // (or fail to compile if the handler is used in places where the fallback isn't provided), because the compiler\n // can't always target type to T, e.g. `b switch { true => 1, false => null }` where `b` is a bool can successfully\n // be passed as an argument of type `object` but not of type `T`.\n // - Reference types get no benefit from going through the generic code paths, and actually incur some overheads\n // from doing so.\n // - Nullable value types also pay a heavy price, in particular around interface checks that would generally evaporate\n // at compile time for value types but don't (currently) if the Nullable goes through the same code paths\n // (see https://github.com/dotnet/runtime/issues/50915).\n //\n // We could try to take a more elaborate approach for DefaultInterpolatedStringHandler, since it is the most common handler\n // and we want to minimize overheads both at runtime and in IL size, e.g. have a complete set of overloads for each of:\n // (T, ...) where T : struct\n // (T?, ...) where T : struct\n // (object, ...)\n // (ReadOnlySpan, ...)\n // (string, ...)\n // but this also has shortcomings, most importantly:\n // - If you have an unconstrained T that happens to be a value type, it'll now end up getting boxed to use the object overload.\n // This also necessitates the T? overload, since nullable value types don't meet a T : struct constraint, so without those\n // they'd all map to the object overloads as well.\n // - Any reference type with an implicit cast to ROS will fail to compile due to ambiguities between the overloads. string\n // is one such type, hence needing dedicated overloads for it that can be bound to more tightly.\n //\n // A middle ground we've settled on, which is likely to be the right approach for most other handlers as well, would be the set:\n // (T, ...) with no constraint\n // (ReadOnlySpan) and (ReadOnlySpan, int)\n // (object, int alignment = 0, string? format = null)\n // (string) and (string, int)\n // This would address most of the concerns, at the expense of:\n // - Most reference types going through the generic code paths and so being a bit more expensive.\n // - Nullable types being more expensive until https://github.com/dotnet/runtime/issues/50915 is addressed.\n // We could choose to add a T? where T : struct set of overloads if necessary.\n // Strings don't require their own overloads here, but as they're expected to be very common and as we can\n // optimize them in several ways (can copy the contents directly, don't need to do any interface checks, don't\n // need to pay the shared generic overheads, etc.) we can add overloads specifically to optimize for them.\n //\n // Hole values are formatted according to the following policy:\n // 1. If an IFormatProvider was supplied and it provides an ICustomFormatter, use ICustomFormatter.Format (even if the value is null).\n // 2. If the type implements ISpanFormattable, use ISpanFormattable.TryFormat.\n // 3. If the type implements IFormattable, use IFormattable.ToString.\n // 4. Otherwise, use object.ToString.\n // This matches the behavior of string.Format, StringBuilder.AppendFormat, etc. The only overloads for which this doesn't\n // apply is ReadOnlySpan, which isn't supported by either string.Format nor StringBuilder.AppendFormat, but more\n // importantly which can't be boxed to be passed to ICustomFormatter.Format.\n\n #region AppendFormatted T\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The type of the value to write.\n public void AppendFormatted(T value)\n {\n // This method could delegate to AppendFormatted with a null format, but explicitly passing\n // default as the format to TryFormat helps to improve code quality in some cases when TryFormat is inlined,\n // e.g. for Int32 it enables the JIT to eliminate code in the inlined method based on a length check on the format.\n\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n return;\n }\n\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format: null, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n public void AppendFormatted(T value, string? format)\n {\n // If there's a custom formatter, always use it.\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format);\n return;\n }\n\n // Check first for IFormattable, even though we'll prefer to use ISpanFormattable, as the latter\n // requires the former. For value types, it won't matter as the type checks devolve into\n // JIT-time constants. For reference types, they're more likely to implement IFormattable\n // than they are to implement ISpanFormattable: if they don't implement either, we save an\n // interface check over first checking for ISpanFormattable and then for IFormattable, and\n // if it only implements IFormattable, we come out even: only if it implements both do we\n // end up paying for an extra interface check.\n string? s;\n if (value is IFormattable)\n {\n s = ((IFormattable)value).ToString(format, _provider); // constrained call avoiding boxing for value types\n }\n else\n {\n s = value?.ToString();\n }\n\n if (s is not null)\n {\n AppendLiteral(s);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment)\n {\n int startingPos = _pos;\n AppendFormatted(value);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// The format string.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The type of the value to write.\n public void AppendFormatted(T value, int alignment, string? format)\n {\n int startingPos = _pos;\n AppendFormatted(value, format);\n if (alignment != 0)\n {\n AppendOrInsertAlignmentIfNeeded(startingPos, alignment);\n }\n }\n #endregion\n\n #region AppendFormatted ReadOnlySpan\n /// Writes the specified character span to the handler.\n /// The span to write.\n public void AppendFormatted(scoped ReadOnlySpan value)\n {\n // Fast path for when the value fits in the current buffer\n if (value.TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n GrowThenCopySpan(value);\n }\n }\n\n /// Writes the specified string of chars to the handler.\n /// The span to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(scoped ReadOnlySpan value, int alignment = 0, string? format = null)\n {\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingRequired = alignment - value.Length;\n if (paddingRequired <= 0)\n {\n // The value is as large or larger than the required amount of padding,\n // so just write the value.\n AppendFormatted(value);\n return;\n }\n\n // Write the value along with the appropriate padding.\n EnsureCapacityForAdditionalChars(value.Length + paddingRequired);\n if (leftAlign)\n {\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n }\n else\n {\n _chars.Slice(_pos, paddingRequired).Fill(' ');\n _pos += paddingRequired;\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n #endregion\n\n #region AppendFormatted string\n /// Writes the specified value to the handler.\n /// The value to write.\n public void AppendFormatted(string? value)\n {\n // Fast-path for no custom formatter and a non-null string that fits in the current destination buffer.\n if (!_hasCustomFormatter &&\n value is not null &&\n value.AsSpan().TryCopyTo(_chars.Slice(_pos)))\n {\n _pos += value.Length;\n }\n else\n {\n AppendFormattedSlow(value);\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// \n /// Slow path to handle a custom formatter, potentially null value,\n /// or a string that doesn't fit in the current buffer.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendFormattedSlow(string? value)\n {\n if (_hasCustomFormatter)\n {\n AppendCustomFormatter(value, format: null);\n }\n else if (value is not null)\n {\n EnsureCapacityForAdditionalChars(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n }\n\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>\n // Format is meaningless for strings and doesn't make sense for someone to specify. We have the overload\n // simply to disambiguate between ROS and object, just in case someone does specify a format, as\n // string is implicitly convertible to both. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n\n #region AppendFormatted object\n /// Writes the specified value to the handler.\n /// The value to write.\n /// Minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n /// The format string.\n public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>\n // This overload is expected to be used rarely, only if either a) something strongly typed as object is\n // formatted with both an alignment and a format, or b) the compiler is unable to target type to T. It\n // exists purely to help make cases from (b) compile. Just delegate to the T-based implementation.\n AppendFormatted(value, alignment, format);\n #endregion\n #endregion\n\n /// Gets whether the provider provides a custom formatter.\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // only used in a few hot path call sites\n internal static bool HasCustomFormatter(IFormatProvider provider)\n {\n Debug.Assert(provider is not null);\n Debug.Assert(provider is not CultureInfo || provider.GetFormat(typeof(ICustomFormatter)) is null, \"Expected CultureInfo to not provide a custom formatter\");\n return\n provider!.GetType() != typeof(CultureInfo) && // optimization to avoid GetFormat in the majority case\n provider.GetFormat(typeof(ICustomFormatter)) != null;\n }\n\n /// Formats the value using the custom formatter from the provider.\n /// The value to write.\n /// The format string.\n /// The type of the value to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void AppendCustomFormatter(T value, string? format)\n {\n // This case is very rare, but we need to handle it prior to the other checks in case\n // a provider was used that supplied an ICustomFormatter which wanted to intercept the particular value.\n // We do the cast here rather than in the ctor, even though this could be executed multiple times per\n // formatting, to make the cast pay for play.\n Debug.Assert(_hasCustomFormatter);\n Debug.Assert(_provider != null);\n\n ICustomFormatter? formatter = (ICustomFormatter?)_provider!.GetFormat(typeof(ICustomFormatter));\n Debug.Assert(formatter != null, \"An incorrectly written provider said it implemented ICustomFormatter, and then didn't\");\n\n if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted)\n {\n AppendLiteral(customFormatted);\n }\n }\n\n /// Handles adding any padding required for aligning a formatted value in an interpolation expression.\n /// The position at which the written value started.\n /// Non-zero minimum number of characters that should be written for this value. If the value is negative, it indicates left-aligned and the required minimum is the absolute value.\n private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)\n {\n Debug.Assert(startingPos >= 0 && startingPos <= _pos);\n Debug.Assert(alignment != 0);\n\n int charsWritten = _pos - startingPos;\n\n bool leftAlign = false;\n if (alignment < 0)\n {\n leftAlign = true;\n alignment = -alignment;\n }\n\n int paddingNeeded = alignment - charsWritten;\n if (paddingNeeded > 0)\n {\n EnsureCapacityForAdditionalChars(paddingNeeded);\n\n if (leftAlign)\n {\n _chars.Slice(_pos, paddingNeeded).Fill(' ');\n }\n else\n {\n _chars.Slice(startingPos, charsWritten).CopyTo(_chars.Slice(startingPos + paddingNeeded));\n _chars.Slice(startingPos, paddingNeeded).Fill(' ');\n }\n\n _pos += paddingNeeded;\n }\n }\n\n /// Ensures has the capacity to store beyond .\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private void EnsureCapacityForAdditionalChars(int additionalChars)\n {\n if (_chars.Length - _pos < additionalChars)\n {\n Grow(additionalChars);\n }\n }\n\n /// Fallback for fast path in when there's not enough space in the destination.\n /// The string to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopyString(string value)\n {\n Grow(value.Length);\n value.AsSpan().CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Fallback for for when not enough space exists in the current buffer.\n /// The span to write.\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowThenCopySpan(scoped ReadOnlySpan value)\n {\n Grow(value.Length);\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n /// Grows to have the capacity to store at least beyond .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow(int additionalChars)\n {\n // This method is called when the remaining space (_chars.Length - _pos) is\n // insufficient to store a specific number of additional characters. Thus, we\n // need to grow to at least that new total. GrowCore will handle growing by more\n // than that if possible.\n Debug.Assert(additionalChars > _chars.Length - _pos);\n GrowCore((uint)_pos + (uint)additionalChars);\n }\n\n /// Grows the size of .\n [MethodImpl(MethodImplOptions.NoInlining)] // keep consumers as streamlined as possible\n private void Grow()\n {\n // This method is called when the remaining space in _chars isn't sufficient to continue\n // the operation. Thus, we need at least one character beyond _chars.Length. GrowCore\n // will handle growing by more than that if possible.\n GrowCore((uint)_chars.Length + 1);\n }\n\n /// Grow the size of to at least the specified .\n [MethodImpl(MethodImplOptions.AggressiveInlining)] // but reuse this grow logic directly in both of the above grow routines\n private void GrowCore(uint requiredMinCapacity)\n {\n // We want the max of how much space we actually required and doubling our capacity (without going beyond the max allowed length). We\n // also want to avoid asking for small arrays, to reduce the number of times we need to grow, and since we're working with unsigned\n // ints that could technically overflow if someone tried to, for example, append a huge string to a huge string, we also clamp to int.MaxValue.\n // Even if the array creation fails in such a case, we may later fail in ToStringAndClear.\n\n const int StringMaxLength = 0x3FFFFFDF;\n uint newCapacity = Math.Max(requiredMinCapacity, Math.Min((uint)_chars.Length * 2, StringMaxLength));\n int arraySize = (int)Clamp(newCapacity, MinimumArrayPoolLength, int.MaxValue);\n\n char[] newArray = ArrayPool.Shared.Rent(arraySize);\n _chars.Slice(0, _pos).CopyTo(newArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = newArray;\n\n if (toReturn is not null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n private static uint Clamp(uint value, uint min, uint max)\n {\n Debug.Assert(min <= max);\n\n if (value < min)\n {\n return min;\n }\n else if (value > max)\n {\n return max;\n }\n\n return value;\n }\n }\n}\n#endif"], ["/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/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/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/Client/McpClientExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class contains extension methods that simplify common operations with an MCP client,\n/// such as pinging a server, listing and working with tools, prompts, and resources, and\n/// managing subscriptions to resources.\n/// \n/// \npublic static class McpClientExtensions\n{\n /// \n /// Sends a ping request to verify server connectivity.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A task that completes when the ping is successful.\n /// \n /// \n /// This method is used to check if the MCP server is online and responding to requests.\n /// It can be useful for health checking, ensuring the connection is established, or verifying \n /// that the client has proper authorization to communicate with the server.\n /// \n /// \n /// The ping operation is lightweight and does not require any parameters. A successful completion\n /// of the task indicates that the server is operational and accessible.\n /// \n /// \n /// is .\n /// Thrown when the server cannot be reached or returns an error response.\n public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.Ping,\n parameters: null,\n McpJsonUtilities.JsonContext.Default.Object!,\n McpJsonUtilities.JsonContext.Default.Object,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Retrieves a list of available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available tools as instances.\n /// \n /// \n /// This method fetches all available tools from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of tools and that responds with paginated responses, consider using \n /// instead, as it streams tools as they arrive rather than loading them all at once.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// \n /// \n /// // Get all tools available on the server\n /// var tools = await mcpClient.ListToolsAsync();\n /// \n /// // Use tools with an AI client\n /// ChatOptions chatOptions = new()\n /// {\n /// Tools = [.. tools]\n /// };\n /// \n /// await foreach (var update in chatClient.GetStreamingResponseAsync(userMessage, chatOptions))\n /// {\n /// Console.Write(update);\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n List? tools = null;\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n tools ??= new List(toolResults.Tools.Count);\n foreach (var tool in toolResults.Tools)\n {\n tools.Add(new McpClientTool(client, tool, serializerOptions));\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n\n return tools;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available tools from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The serializer options governing tool parameter serialization. If null, the default options will be used.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available tools as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve tools from the server, which allows processing tools\n /// as they arrive rather than waiting for all tools to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with tools split across multiple responses.\n /// \n /// \n /// The serializer options provided are flowed to each and will be used\n /// when invoking tools in order to serialize any parameters.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available tools.\n /// \n /// \n /// \n /// \n /// // Enumerate all tools available on the server\n /// await foreach (var tool in client.EnumerateToolsAsync())\n /// {\n /// Console.WriteLine($\"Tool: {tool.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateToolsAsync(\n this IMcpClient client,\n JsonSerializerOptions? serializerOptions = null,\n [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n string? cursor = null;\n do\n {\n var toolResults = await client.SendRequestAsync(\n RequestMethods.ToolsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var tool in toolResults.Tools)\n {\n yield return new McpClientTool(client, tool, serializerOptions);\n }\n\n cursor = toolResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available prompts as instances.\n /// \n /// \n /// This method fetches all available prompts from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of prompts and that responds with paginated responses, consider using \n /// instead, as it streams prompts as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListPromptsAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? prompts = null;\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n prompts ??= new List(promptResults.Prompts.Count);\n foreach (var prompt in promptResults.Prompts)\n {\n prompts.Add(new McpClientPrompt(client, prompt));\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n\n return prompts;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available prompts from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available prompts as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve prompts from the server, which allows processing prompts\n /// as they arrive rather than waiting for all prompts to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with prompts split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available prompts.\n /// \n /// \n /// \n /// \n /// // Enumerate all prompts available on the server\n /// await foreach (var prompt in client.EnumeratePromptsAsync())\n /// {\n /// Console.WriteLine($\"Prompt: {prompt.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumeratePromptsAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var promptResults = await client.SendRequestAsync(\n RequestMethods.PromptsList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var prompt in promptResults.Prompts)\n {\n yield return new(client, prompt);\n }\n\n cursor = promptResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a specific prompt from the MCP server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the prompt to retrieve.\n /// Optional arguments for the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to create the specified prompt with the provided arguments.\n /// The server will process the arguments and return a prompt containing messages or other content.\n /// \n /// \n /// Arguments are serialized into JSON and passed to the server, where they may be used to customize the \n /// prompt's behavior or content. Each prompt may have different argument requirements.\n /// \n /// \n /// The returned contains a collection of objects,\n /// which can be converted to objects using the method.\n /// \n /// \n /// Thrown when the prompt does not exist, when required arguments are missing, or when the server encounters an error processing the prompt.\n /// is .\n public static ValueTask GetPromptAsync(\n this IMcpClient client,\n string name,\n IReadOnlyDictionary? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(name);\n\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n return client.SendRequestAsync(\n RequestMethods.PromptsGet,\n new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },\n McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,\n McpJsonUtilities.JsonContext.Default.GetPromptResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Retrieves a list of available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resource templates as instances.\n /// \n /// \n /// This method fetches all available resource templates from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resource templates and that responds with paginated responses, consider using \n /// instead, as it streams templates as they arrive rather than loading them all at once.\n /// \n /// \n /// is .\n public static async ValueTask> ListResourceTemplatesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resourceTemplates = null;\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resourceTemplates ??= new List(templateResults.ResourceTemplates.Count);\n foreach (var template in templateResults.ResourceTemplates)\n {\n resourceTemplates.Add(new McpClientResourceTemplate(client, template));\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n\n return resourceTemplates;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resource templates from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resource templates as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resource templates from the server, which allows processing templates\n /// as they arrive rather than waiting for all templates to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with templates split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resource templates.\n /// \n /// \n /// \n /// \n /// // Enumerate all resource templates available on the server\n /// await foreach (var template in client.EnumerateResourceTemplatesAsync())\n /// {\n /// Console.WriteLine($\"Template: {template.Name}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourceTemplatesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var templateResults = await client.SendRequestAsync(\n RequestMethods.ResourcesTemplatesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var templateResult in templateResults.ResourceTemplates)\n {\n yield return new McpClientResourceTemplate(client, templateResult);\n }\n\n cursor = templateResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Retrieves a list of available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// A list of all available resources as instances.\n /// \n /// \n /// This method fetches all available resources from the MCP server and returns them as a complete list.\n /// It automatically handles pagination with cursors if the server responds with only a portion per request.\n /// \n /// \n /// For servers with a large number of resources and that responds with paginated responses, consider using \n /// instead, as it streams resources as they arrive rather than loading them all at once.\n /// \n /// \n /// \n /// \n /// // Get all resources available on the server\n /// var resources = await client.ListResourcesAsync();\n /// \n /// // Display information about each resource\n /// foreach (var resource in resources)\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async ValueTask> ListResourcesAsync(\n this IMcpClient client, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n List? resources = null;\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n resources ??= new List(resourceResults.Resources.Count);\n foreach (var resource in resourceResults.Resources)\n {\n resources.Add(new McpClientResource(client, resource));\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n\n return resources;\n }\n\n /// \n /// Creates an enumerable for asynchronously enumerating all available resources from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The to monitor for cancellation requests. The default is .\n /// An asynchronous sequence of all available resources as instances.\n /// \n /// \n /// This method uses asynchronous enumeration to retrieve resources from the server, which allows processing resources\n /// as they arrive rather than waiting for all resources to be retrieved. The method automatically handles pagination\n /// with cursors if the server responds with resources split across multiple responses.\n /// \n /// \n /// Every iteration through the returned \n /// will result in re-querying the server and yielding the sequence of available resources.\n /// \n /// \n /// \n /// \n /// // Enumerate all resources available on the server\n /// await foreach (var resource in client.EnumerateResourcesAsync())\n /// {\n /// Console.WriteLine($\"Resource URI: {resource.Uri}\");\n /// }\n /// \n /// \n /// is .\n public static async IAsyncEnumerable EnumerateResourcesAsync(\n this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n string? cursor = null;\n do\n {\n var resourceResults = await client.SendRequestAsync(\n RequestMethods.ResourcesList,\n new() { Cursor = cursor },\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n\n foreach (var resource in resourceResults.Resources)\n {\n yield return new McpClientResource(client, resource);\n }\n\n cursor = resourceResults.NextCursor;\n }\n while (cursor is not null);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri of the resource.\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return ReadResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Reads a resource from the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The uri template of the resource.\n /// Arguments to use to format .\n /// The to monitor for cancellation requests. The default is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static ValueTask ReadResourceAsync(\n this IMcpClient client, string uriTemplate, IReadOnlyDictionary arguments, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uriTemplate);\n Throw.IfNull(arguments);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesRead,\n new() { Uri = UriTemplate.FormatUri(uriTemplate, arguments) },\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests completion suggestions for a prompt argument or resource reference.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The reference object specifying the type and optional URI or name.\n /// The name of the argument for which completions are requested.\n /// The current value of the argument, used to filter relevant completions.\n /// The to monitor for cancellation requests. The default is .\n /// A containing completion suggestions.\n /// \n /// \n /// This method allows clients to request auto-completion suggestions for arguments in a prompt template\n /// or for resource references.\n /// \n /// \n /// When working with prompt references, the server will return suggestions for the specified argument\n /// that match or begin with the current argument value. This is useful for implementing intelligent\n /// auto-completion in user interfaces.\n /// \n /// \n /// When working with resource references, the server will return suggestions relevant to the specified \n /// resource URI.\n /// \n /// \n /// is .\n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n /// The server returned an error response.\n public static ValueTask CompleteAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(reference);\n Throw.IfNullOrWhiteSpace(argumentName);\n\n return client.SendRequestAsync(\n RequestMethods.CompletionComplete,\n new()\n {\n Ref = reference,\n Argument = new Argument { Name = argumentName, Value = argumentValue }\n },\n McpJsonUtilities.JsonContext.Default.CompleteRequestParams,\n McpJsonUtilities.JsonContext.Default.CompleteResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesSubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Subscribes to a resource on the server to receive notifications when it changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to which to subscribe.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method allows the client to register interest in a specific resource identified by its URI.\n /// When the resource changes, the server will send notifications to the client, enabling real-time\n /// updates without polling.\n /// \n /// \n /// The subscription remains active until explicitly unsubscribed using \n /// or until the client disconnects from the server.\n /// \n /// \n /// To handle resource change notifications, register an event handler for the appropriate notification events,\n /// such as with .\n /// \n /// \n /// is .\n /// is .\n public static Task SubscribeToResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return SubscribeToResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n /// is empty or composed entirely of whitespace.\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(uri);\n\n return client.SendRequestAsync(\n RequestMethods.ResourcesUnsubscribe,\n new() { Uri = uri },\n McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The URI of the resource to unsubscribe from.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation.\n /// \n /// \n /// This method cancels a previous subscription to a resource, stopping the client from receiving\n /// notifications when that resource changes.\n /// \n /// \n /// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same\n /// resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// Due to the nature of the MCP protocol, it is possible the client may receive notifications after\n /// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.\n /// \n /// \n /// is .\n /// is .\n public static Task UnsubscribeFromResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(uri);\n\n return UnsubscribeFromResourceAsync(client, uri.ToString(), cancellationToken);\n }\n\n /// \n /// Invokes a tool on the server.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The name of the tool to call on the server..\n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// is .\n /// is .\n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// // Call a simple echo tool with a string argument\n /// var result = await client.CallToolAsync(\n /// \"echo\",\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public static ValueTask CallToolAsync(\n this IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNull(toolName);\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n if (progress is not null)\n {\n return SendRequestWithProgressAsync(client, toolName, arguments, progress, serializerOptions, cancellationToken);\n }\n\n return client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken);\n\n static async ValueTask SendRequestWithProgressAsync(\n IMcpClient client,\n string toolName,\n IReadOnlyDictionary? arguments,\n IProgress progress,\n JsonSerializerOptions serializerOptions,\n CancellationToken cancellationToken)\n {\n ProgressToken progressToken = new(Guid.NewGuid().ToString(\"N\"));\n\n await using var _ = client.RegisterNotificationHandler(NotificationMethods.ProgressNotification,\n (notification, cancellationToken) =>\n {\n if (JsonSerializer.Deserialize(notification.Params, McpJsonUtilities.JsonContext.Default.ProgressNotificationParams) is { } pn &&\n pn.ProgressToken == progressToken)\n {\n progress.Report(pn.Progress);\n }\n\n return default;\n }).ConfigureAwait(false);\n\n return await client.SendRequestAsync(\n RequestMethods.ToolsCall,\n new()\n {\n Name = toolName,\n Arguments = ToArgumentsDictionary(arguments, serializerOptions),\n ProgressToken = progressToken,\n },\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult,\n cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n }\n\n /// \n /// Converts the contents of a into a pair of\n /// and instances to use\n /// as inputs into a operation.\n /// \n /// \n /// The created pair of messages and options.\n /// is .\n internal static (IList Messages, ChatOptions? Options) ToChatClientArguments(\n this CreateMessageRequestParams requestParams)\n {\n Throw.IfNull(requestParams);\n\n ChatOptions? options = null;\n\n if (requestParams.MaxTokens is int maxTokens)\n {\n (options ??= new()).MaxOutputTokens = maxTokens;\n }\n\n if (requestParams.Temperature is float temperature)\n {\n (options ??= new()).Temperature = temperature;\n }\n\n if (requestParams.StopSequences is { } stopSequences)\n {\n (options ??= new()).StopSequences = stopSequences.ToArray();\n }\n\n List messages =\n (from sm in requestParams.Messages\n let aiContent = sm.Content.ToAIContent()\n where aiContent is not null\n select new ChatMessage(sm.Role == Role.Assistant ? ChatRole.Assistant : ChatRole.User, [aiContent]))\n .ToList();\n\n return (messages, options);\n }\n\n /// Converts the contents of a into a .\n /// The whose contents should be extracted.\n /// The created .\n /// is .\n internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chatResponse)\n {\n Throw.IfNull(chatResponse);\n\n // The ChatResponse can include multiple messages, of varying modalities, but CreateMessageResult supports\n // only either a single blob of text or a single image. Heuristically, we'll use an image if there is one\n // in any of the response messages, or we'll use all the text from them concatenated, otherwise.\n\n ChatMessage? lastMessage = chatResponse.Messages.LastOrDefault();\n\n ContentBlock? content = null;\n if (lastMessage is not null)\n {\n foreach (var lmc in lastMessage.Contents)\n {\n if (lmc is DataContent dc && (dc.HasTopLevelMediaType(\"image\") || dc.HasTopLevelMediaType(\"audio\")))\n {\n content = dc.ToContent();\n }\n }\n }\n\n return new()\n {\n Content = content ?? new TextContentBlock { Text = lastMessage?.Text ?? string.Empty },\n Model = chatResponse.ModelId ?? \"unknown\",\n Role = lastMessage?.Role == ChatRole.User ? Role.User : Role.Assistant,\n StopReason = chatResponse.FinishReason == ChatFinishReason.Length ? \"maxTokens\" : \"endTurn\",\n };\n }\n\n /// \n /// Creates a sampling handler for use with that will\n /// satisfy sampling requests using the specified .\n /// \n /// The with which to satisfy sampling requests.\n /// The created handler delegate that can be assigned to .\n /// \n /// \n /// This method creates a function that converts MCP message requests into chat client calls, enabling\n /// an MCP client to generate text or other content using an actual AI model via the provided chat client.\n /// \n /// \n /// The handler can process text messages, image messages, and resource messages as defined in the\n /// Model Context Protocol.\n /// \n /// \n /// is .\n public static Func, CancellationToken, ValueTask> CreateSamplingHandler(\n this IChatClient chatClient)\n {\n Throw.IfNull(chatClient);\n\n return async (requestParams, progress, cancellationToken) =>\n {\n Throw.IfNull(requestParams);\n\n var (messages, options) = requestParams.ToChatClientArguments();\n var progressToken = requestParams.ProgressToken;\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false))\n {\n updates.Add(update);\n\n if (progressToken is not null)\n {\n progress.Report(new()\n {\n Progress = updates.Count,\n });\n }\n }\n\n return updates.ToChatResponse().ToCreateMessageResult();\n };\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// , , and \n /// level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LoggingLevel level, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n\n return client.SendRequestAsync(\n RequestMethods.LoggingSetLevel,\n new() { Level = level },\n McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult,\n cancellationToken: cancellationToken).AsTask();\n }\n\n /// \n /// Sets the logging level for the server to control which log messages are sent to the client.\n /// \n /// The client instance used to communicate with the MCP server.\n /// The minimum severity level of log messages to receive from the server.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation.\n /// \n /// \n /// After this request is processed, the server will send log messages at or above the specified\n /// logging level as notifications to the client. For example, if is set,\n /// the client will receive , , \n /// and level messages.\n /// \n /// \n /// To receive all log messages, set the level to .\n /// \n /// \n /// Log messages are delivered as notifications to the client and can be captured by registering\n /// appropriate event handlers with the client implementation, such as with .\n /// \n /// \n /// is .\n public static Task SetLoggingLevel(this IMcpClient client, LogLevel level, CancellationToken cancellationToken = default) =>\n SetLoggingLevel(client, McpServer.ToLoggingLevel(level), cancellationToken);\n\n /// Convers a dictionary with values to a dictionary with values.\n private static Dictionary? ToArgumentsDictionary(\n IReadOnlyDictionary? arguments, JsonSerializerOptions options)\n {\n var typeInfo = options.GetTypeInfo();\n\n Dictionary? result = null;\n if (arguments is not null)\n {\n result = new(arguments.Count);\n foreach (var kvp in arguments)\n {\n result.Add(kvp.Key, kvp.Value is JsonElement je ? je : JsonSerializer.SerializeToElement(kvp.Value, typeInfo));\n }\n }\n\n return result;\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/Server/AIFunctionMcpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed partial class AIFunctionMcpServerTool : McpServerTool\n{\n private readonly ILogger _logger;\n private readonly bool _structuredOutputRequiresWrapping;\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n \n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n object? target,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerToolCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options)\n {\n Throw.IfNull(function);\n\n Tool tool = new()\n {\n Name = options?.Name ?? function.Name,\n Description = options?.Description ?? function.Description,\n InputSchema = function.JsonSchema,\n OutputSchema = CreateOutputSchema(function, options, out bool structuredOutputRequiresWrapping),\n };\n\n if (options is not null)\n {\n if (options.Title is not null ||\n options.Idempotent is not null ||\n options.Destructive is not null ||\n options.OpenWorld is not null ||\n options.ReadOnly is not null)\n {\n tool.Title = options.Title;\n\n tool.Annotations = new()\n {\n Title = options.Title,\n IdempotentHint = options.Idempotent,\n DestructiveHint = options.Destructive,\n OpenWorldHint = options.OpenWorld,\n ReadOnlyHint = options.ReadOnly,\n };\n }\n }\n\n return new AIFunctionMcpServerTool(function, tool, options?.Services, structuredOutputRequiresWrapping);\n }\n\n private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpServerToolCreateOptions? options)\n {\n McpServerToolCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } toolAttr)\n {\n newOptions.Name ??= toolAttr.Name;\n newOptions.Title ??= toolAttr.Title;\n\n if (toolAttr._destructive is bool destructive)\n {\n newOptions.Destructive ??= destructive;\n }\n\n if (toolAttr._idempotent is bool idempotent)\n {\n newOptions.Idempotent ??= idempotent;\n }\n\n if (toolAttr._openWorld is bool openWorld)\n {\n newOptions.OpenWorld ??= openWorld;\n }\n\n if (toolAttr._readOnly is bool readOnly)\n {\n newOptions.ReadOnly ??= readOnly;\n }\n\n newOptions.UseStructuredContent = toolAttr.UseStructuredContent;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this tool.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerTool(AIFunction function, Tool tool, IServiceProvider? serviceProvider, bool structuredOutputRequiresWrapping)\n {\n AIFunction = function;\n ProtocolTool = tool;\n _logger = serviceProvider?.GetService()?.CreateLogger() ?? (ILogger)NullLogger.Instance;\n _structuredOutputRequiresWrapping = structuredOutputRequiresWrapping;\n }\n\n /// \n public override Tool ProtocolTool { get; }\n\n /// \n public override async ValueTask InvokeAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result;\n try\n {\n result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception e) when (e is not OperationCanceledException)\n {\n ToolCallError(request.Params?.Name ?? string.Empty, e);\n\n string errorMessage = e is McpException ?\n $\"An error occurred invoking '{request.Params?.Name}': {e.Message}\" :\n $\"An error occurred invoking '{request.Params?.Name}'.\";\n\n return new()\n {\n IsError = true,\n Content = [new TextContentBlock { Text = errorMessage }],\n };\n }\n\n JsonNode? structuredContent = CreateStructuredResponse(result);\n return result switch\n {\n AIContent aiContent => new()\n {\n Content = [aiContent.ToContent()],\n StructuredContent = structuredContent,\n IsError = aiContent is ErrorContent\n },\n\n null => new()\n {\n Content = [],\n StructuredContent = structuredContent,\n },\n \n string text => new()\n {\n Content = [new TextContentBlock { Text = text }],\n StructuredContent = structuredContent,\n },\n \n ContentBlock content => new()\n {\n Content = [content],\n StructuredContent = structuredContent,\n },\n \n IEnumerable texts => new()\n {\n Content = [.. texts.Select(x => new TextContentBlock { Text = x ?? string.Empty })],\n StructuredContent = structuredContent,\n },\n \n IEnumerable contentItems => ConvertAIContentEnumerableToCallToolResult(contentItems, structuredContent),\n \n IEnumerable contents => new()\n {\n Content = [.. contents],\n StructuredContent = structuredContent,\n },\n \n CallToolResult callToolResponse => callToolResponse,\n\n _ => new()\n {\n Content = [new TextContentBlock { Text = JsonSerializer.Serialize(result, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))) }],\n StructuredContent = structuredContent,\n },\n };\n }\n\n /// Creates a name to use based on the supplied method and naming policy.\n internal static string DeriveName(MethodInfo method, JsonNamingPolicy? policy = null)\n {\n string name = method.Name;\n\n // Remove any \"Async\" suffix if the method is an async method and if the method name isn't just \"Async\".\n const string AsyncSuffix = \"Async\";\n if (IsAsyncMethod(method) &&\n name.EndsWith(AsyncSuffix, StringComparison.Ordinal) &&\n name.Length > AsyncSuffix.Length)\n {\n name = name.Substring(0, name.Length - AsyncSuffix.Length);\n }\n\n // Replace anything other than ASCII letters or digits with underscores, trim off any leading or trailing underscores.\n name = NonAsciiLetterDigitsRegex().Replace(name, \"_\").Trim('_');\n\n // If after all our transformations the name is empty, just use the original method name.\n if (name.Length == 0)\n {\n name = method.Name;\n }\n\n // Case the name based on the provided naming policy.\n return (policy ?? JsonNamingPolicy.SnakeCaseLower).ConvertName(name) ?? name;\n\n static bool IsAsyncMethod(MethodInfo method)\n {\n Type t = method.ReturnType;\n\n if (t == typeof(Task) || t == typeof(ValueTask))\n {\n return true;\n }\n\n if (t.IsGenericType)\n {\n t = t.GetGenericTypeDefinition();\n if (t == typeof(Task<>) || t == typeof(ValueTask<>) || t == typeof(IAsyncEnumerable<>))\n {\n return true;\n }\n }\n\n return false;\n }\n }\n\n /// Regex that flags runs of characters other than ASCII digits or letters.\n#if NET\n [GeneratedRegex(\"[^0-9A-Za-z]+\")]\n private static partial Regex NonAsciiLetterDigitsRegex();\n#else\n private static Regex NonAsciiLetterDigitsRegex() => _nonAsciiLetterDigits;\n private static readonly Regex _nonAsciiLetterDigits = new(\"[^0-9A-Za-z]+\", RegexOptions.Compiled);\n#endif\n\n private static JsonElement? CreateOutputSchema(AIFunction function, McpServerToolCreateOptions? toolCreateOptions, out bool structuredOutputRequiresWrapping)\n {\n structuredOutputRequiresWrapping = false;\n\n if (toolCreateOptions?.UseStructuredContent is not true)\n {\n return null;\n }\n\n if (function.ReturnJsonSchema is not JsonElement outputSchema)\n {\n return null;\n }\n\n if (outputSchema.ValueKind is not JsonValueKind.Object ||\n !outputSchema.TryGetProperty(\"type\", out JsonElement typeProperty) ||\n typeProperty.ValueKind is not JsonValueKind.String ||\n typeProperty.GetString() is not \"object\")\n {\n // If the output schema is not an object, need to modify to be a valid MCP output schema.\n JsonNode? schemaNode = JsonSerializer.SerializeToNode(outputSchema, McpJsonUtilities.JsonContext.Default.JsonElement);\n\n if (schemaNode is JsonObject objSchema &&\n objSchema.TryGetPropertyValue(\"type\", out JsonNode? typeNode) &&\n typeNode is JsonArray { Count: 2 } typeArray && typeArray.Any(type => (string?)type is \"object\") && typeArray.Any(type => (string?)type is \"null\"))\n {\n // For schemas that are of type [\"object\", \"null\"], replace with just \"object\" to be conformant.\n objSchema[\"type\"] = \"object\";\n }\n else\n {\n // For anything else, wrap the schema in an envelope with a \"result\" property.\n schemaNode = new JsonObject\n {\n [\"type\"] = \"object\",\n [\"properties\"] = new JsonObject\n {\n [\"result\"] = schemaNode\n },\n [\"required\"] = new JsonArray { (JsonNode)\"result\" }\n };\n\n structuredOutputRequiresWrapping = true;\n }\n\n outputSchema = JsonSerializer.Deserialize(schemaNode, McpJsonUtilities.JsonContext.Default.JsonElement);\n }\n\n return outputSchema;\n }\n\n private JsonNode? CreateStructuredResponse(object? aiFunctionResult)\n {\n if (ProtocolTool.OutputSchema is null)\n {\n // Only provide structured responses if the tool has an output schema defined.\n return null;\n }\n\n JsonNode? nodeResult = aiFunctionResult switch\n {\n JsonNode node => node,\n JsonElement jsonElement => JsonSerializer.SerializeToNode(jsonElement, McpJsonUtilities.JsonContext.Default.JsonElement),\n _ => JsonSerializer.SerializeToNode(aiFunctionResult, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))),\n };\n\n if (_structuredOutputRequiresWrapping)\n {\n return new JsonObject\n {\n [\"result\"] = nodeResult\n };\n }\n\n return nodeResult;\n }\n\n private static CallToolResult ConvertAIContentEnumerableToCallToolResult(IEnumerable contentItems, JsonNode? structuredContent)\n {\n List contentList = [];\n bool allErrorContent = true;\n bool hasAny = false;\n\n foreach (var item in contentItems)\n {\n contentList.Add(item.ToContent());\n hasAny = true;\n\n if (allErrorContent && item is not ErrorContent)\n {\n allErrorContent = false;\n }\n }\n\n return new()\n {\n Content = contentList,\n StructuredContent = structuredContent,\n IsError = allErrorContent && hasAny\n };\n }\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"\\\"{ToolName}\\\" threw an unhandled exception.\")]\n private partial void ToolCallError(string toolName, Exception exception);\n}"], ["/csharp-sdk/src/ModelContextProtocol/McpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring MCP servers via dependency injection.\n/// \npublic static partial class McpServerBuilderExtensions\n{\n #region WithTools\n private const string WithToolsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithTools)} and {nameof(WithToolsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithTools)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The tool type.\n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n public static IMcpServerBuilder WithTools<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TToolType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var toolMethod in typeof(TToolType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, static r => CreateTarget(r.Services, typeof(TToolType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable tools)\n {\n Throw.IfNull(builder);\n Throw.IfNull(tools);\n\n foreach (var tool in tools)\n {\n if (tool is not null)\n {\n builder.Services.AddSingleton(tool);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with -attributed methods to add as tools to the server.\n /// The serializer options governing tool parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the tool.\n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, IEnumerable toolTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(toolTypes);\n\n foreach (var toolType in toolTypes)\n {\n if (toolType is not null)\n {\n foreach (var toolMethod in toolType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (toolMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(toolMethod.IsStatic ?\n services => McpServerTool.Create(toolMethod, options: new() { Services = services , SerializerOptions = serializerOptions }) :\n services => McpServerTool.Create(toolMethod, r => CreateTarget(r.Services, toolType), new() { Services = services , SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as tools to the server.\n /// \n /// The builder instance.\n /// The serializer options governing tool parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the tool.\n /// \n /// \n /// Tools registered through this method can be discovered by clients using the list_tools request\n /// and invoked using the call_tool request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithToolsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithToolsFromAssembly(this IMcpServerBuilder builder, Assembly? toolAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n toolAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithTools(\n from t in toolAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithPrompts\n private const string WithPromptsRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithPrompts)} and {nameof(WithPromptsFromAssembly)} methods require dynamic lookup of method metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithPrompts)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The prompt type.\n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n public static IMcpServerBuilder WithPrompts<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods |\n DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TPromptType>(\n this IMcpServerBuilder builder,\n JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n foreach (var promptMethod in typeof(TPromptType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, static r => CreateTarget(r.Services, typeof(TPromptType)), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable prompts)\n {\n Throw.IfNull(builder);\n Throw.IfNull(prompts);\n\n foreach (var prompt in prompts)\n {\n if (prompt is not null)\n {\n builder.Services.AddSingleton(prompt);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as prompts to the server.\n /// The serializer options governing prompt parameter marshalling.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the prompt.\n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPrompts(this IMcpServerBuilder builder, IEnumerable promptTypes, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n Throw.IfNull(promptTypes);\n\n foreach (var promptType in promptTypes)\n {\n if (promptType is not null)\n {\n foreach (var promptMethod in promptType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (promptMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(promptMethod.IsStatic ?\n services => McpServerPrompt.Create(promptMethod, options: new() { Services = services, SerializerOptions = serializerOptions }) :\n services => McpServerPrompt.Create(promptMethod, r => CreateTarget(r.Services, promptType), new() { Services = services, SerializerOptions = serializerOptions })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as prompts to the server.\n /// \n /// The builder instance.\n /// The serializer options governing prompt parameter marshalling.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all methods within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance methods. For instance methods, a new instance\n /// of the containing class will be constructed for each invocation of the prompt.\n /// \n /// \n /// Prompts registered through this method can be discovered by clients using the list_prompts request\n /// and invoked using the call_prompt request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithPromptsRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithPromptsFromAssembly(this IMcpServerBuilder builder, Assembly? promptAssembly = null, JsonSerializerOptions? serializerOptions = null)\n {\n Throw.IfNull(builder);\n\n promptAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithPrompts(\n from t in promptAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t,\n serializerOptions);\n }\n #endregion\n\n #region WithResources\n private const string WithResourcesRequiresUnreferencedCodeMessage =\n $\"The non-generic {nameof(WithResources)} and {nameof(WithResourcesFromAssembly)} methods require dynamic lookup of member metadata\" +\n $\"and may not work in Native AOT. Use the generic {nameof(WithResources)} method instead.\";\n\n /// Adds instances to the service collection backing .\n /// The resource type.\n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// type, where the members are attributed as , and adds an \n /// instance for each. For instance members, an instance will be constructed for each invocation of the resource.\n /// \n public static IMcpServerBuilder WithResources<[DynamicallyAccessedMembers(\n DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods |\n DynamicallyAccessedMemberTypes.PublicConstructors)] TResourceType>(\n this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n foreach (var resourceTemplateMethod in typeof(TResourceType).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, static r => CreateTarget(r.Services, typeof(TResourceType)), new() { Services = services })));\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// The instances to add to the server.\n /// The builder provided in .\n /// is .\n /// is .\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplates)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplates);\n\n foreach (var resourceTemplate in resourceTemplates)\n {\n if (resourceTemplate is not null)\n {\n builder.Services.AddSingleton(resourceTemplate);\n }\n }\n\n return builder;\n }\n\n /// Adds instances to the service collection backing .\n /// The builder instance.\n /// Types with marked methods to add as resources to the server.\n /// The builder provided in .\n /// is .\n /// is .\n /// \n /// This method discovers all instance and static methods (public and non-public) on the specified \n /// types, where the methods are attributed as , and adds an \n /// instance for each. For instance methods, an instance will be constructed for each invocation of the resource.\n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResources(this IMcpServerBuilder builder, IEnumerable resourceTemplateTypes)\n {\n Throw.IfNull(builder);\n Throw.IfNull(resourceTemplateTypes);\n\n foreach (var resourceTemplateType in resourceTemplateTypes)\n {\n if (resourceTemplateType is not null)\n {\n foreach (var resourceTemplateMethod in resourceTemplateType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))\n {\n if (resourceTemplateMethod.GetCustomAttribute() is not null)\n {\n builder.Services.AddSingleton((Func)(resourceTemplateMethod.IsStatic ?\n services => McpServerResource.Create(resourceTemplateMethod, options: new() { Services = services }) :\n services => McpServerResource.Create(resourceTemplateMethod, r => CreateTarget(r.Services, resourceTemplateType), new() { Services = services })));\n }\n }\n }\n }\n\n return builder;\n }\n\n /// \n /// Adds types marked with the attribute from the given assembly as resources to the server.\n /// \n /// The builder instance.\n /// The assembly to load the types from. If , the calling assembly will be used.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method scans the specified assembly (or the calling assembly if none is provided) for classes\n /// marked with the . It then discovers all members within those\n /// classes that are marked with the and registers them as s\n /// in the 's .\n /// \n /// \n /// The method automatically handles both static and instance members. For instance members, a new instance\n /// of the containing class will be constructed for each invocation of the resource.\n /// \n /// \n /// Resource templates registered through this method can be discovered by clients using the list_resourceTemplates request\n /// and invoked using the read_resource request.\n /// \n /// \n /// Note that this method performs reflection at runtime and may not work in Native AOT scenarios. For\n /// Native AOT compatibility, consider using the generic method instead.\n /// \n /// \n [RequiresUnreferencedCode(WithResourcesRequiresUnreferencedCodeMessage)]\n public static IMcpServerBuilder WithResourcesFromAssembly(this IMcpServerBuilder builder, Assembly? resourceAssembly = null)\n {\n Throw.IfNull(builder);\n\n resourceAssembly ??= Assembly.GetCallingAssembly();\n\n return builder.WithResources(\n from t in resourceAssembly.GetTypes()\n where t.GetCustomAttribute() is not null\n select t);\n }\n #endregion\n\n #region Handlers\n /// \n /// Configures a handler for listing resource templates available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource template list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is responsible for providing clients with information about available resource templates\n /// that can be used to construct resource URIs.\n /// \n /// \n /// Resource templates describe the structure of resource URIs that the server can handle. They include\n /// URI templates (according to RFC 6570) that clients can use to construct valid resource URIs.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// resource system where templates define the URI patterns and the read handler provides the actual content.\n /// \n /// \n public static IMcpServerBuilder WithListResourceTemplatesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourceTemplatesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list tools requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available tools. It should return all tools\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// tool collections.\n /// \n /// \n /// When tools are also defined using collection, both sets of tools\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// tools and dynamically generated tools.\n /// \n /// \n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and \n /// executes them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListToolsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListToolsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for calling tools available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes tool calls.\n /// The builder provided in .\n /// is .\n /// \n /// The call tool handler is responsible for executing custom tools and returning their results to clients.\n /// This method is typically paired with to provide a complete tools implementation,\n /// where advertises available tools and this handler executes them.\n /// \n public static IMcpServerBuilder WithCallToolHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CallToolHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing prompts available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler that processes list prompts requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is called when a client requests a list of available prompts. It should return all prompts\n /// that can be invoked through the server, including their names, descriptions, and parameter specifications.\n /// The handler can optionally support pagination via the cursor mechanism for large or dynamically-generated\n /// prompt collections.\n /// \n /// \n /// When prompts are also defined using collection, both sets of prompts\n /// will be combined in the response to clients. This allows for a mix of programmatically defined\n /// prompts and dynamically generated prompts.\n /// \n /// \n /// This method is typically paired with to provide a complete prompts implementation,\n /// where advertises available prompts and \n /// produces them when invoked by clients.\n /// \n /// \n public static IMcpServerBuilder WithListPromptsHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListPromptsHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for getting a prompt available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes prompt requests.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithGetPromptHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.GetPromptHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for listing resources available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource list requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where this handler advertises available resources and the read handler provides their content when requested.\n /// \n /// \n public static IMcpServerBuilder WithListResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ListResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for reading a resource available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes resource read requests.\n /// The builder provided in .\n /// is .\n /// \n /// This handler is typically paired with to provide a complete resources implementation,\n /// where the list handler advertises available resources and the read handler provides their content when requested.\n /// \n public static IMcpServerBuilder WithReadResourceHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.ReadResourceHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for auto-completion suggestions for prompt arguments or resource references available from the Model Context Protocol server.\n /// \n /// The builder instance.\n /// The handler function that processes completion requests.\n /// The builder provided in .\n /// is .\n /// \n /// The completion handler is invoked when clients request suggestions for argument values.\n /// This enables auto-complete functionality for both prompt arguments and resource references.\n /// \n public static IMcpServerBuilder WithCompleteHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.CompleteHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource subscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource subscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The subscribe handler is responsible for registering client interest in specific resources. When a resource\n /// changes, the server can notify all subscribed clients about the change.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. Resource subscriptions allow clients to maintain up-to-date information without\n /// needing to poll resources constantly.\n /// \n /// \n /// After registering a subscription, it's the server's responsibility to track which client is subscribed to which\n /// resources and to send appropriate notifications through the connection when resources change.\n /// \n /// \n public static IMcpServerBuilder WithSubscribeToResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SubscribeToResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for resource unsubscription requests.\n /// \n /// The builder instance.\n /// The handler function that processes resource unsubscription requests.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// The unsubscribe handler is responsible for removing client interest in specific resources. When a client\n /// no longer needs to receive notifications about resource changes, it can send an unsubscribe request.\n /// \n /// \n /// This handler is typically paired with to provide a complete\n /// subscription management system. The unsubscribe operation is idempotent, meaning it can be called multiple\n /// times for the same resource without causing errors, even if there is no active subscription.\n /// \n /// \n /// After removing a subscription, the server should stop sending notifications to the client about changes\n /// to the specified resource.\n /// \n /// \n public static IMcpServerBuilder WithUnsubscribeFromResourcesHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.UnsubscribeFromResourcesHandler = handler);\n return builder;\n }\n\n /// \n /// Configures a handler for processing logging level change requests from clients.\n /// \n /// The server builder instance.\n /// The handler that processes requests to change the logging level.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// When a client sends a logging/setLevel request, this handler will be invoked to process\n /// the requested level change. The server typically adjusts its internal logging level threshold\n /// and may begin sending log messages at or above the specified level to the client.\n /// \n /// \n /// Regardless of whether a handler is provided, an should itself handle\n /// such notifications by updating its property to return the\n /// most recently set level.\n /// \n /// \n public static IMcpServerBuilder WithSetLoggingLevelHandler(this IMcpServerBuilder builder, Func, CancellationToken, ValueTask> handler)\n {\n Throw.IfNull(builder);\n\n builder.Services.Configure(s => s.SetLoggingLevelHandler = handler);\n return builder;\n }\n #endregion\n\n #region Transports\n /// \n /// Adds a server transport that uses standard input (stdin) and standard output (stdout) for communication.\n /// \n /// The builder instance.\n /// The builder provided in .\n /// is .\n /// \n /// \n /// This method configures the server to communicate using the standard input and output streams,\n /// which is commonly used when the Model Context Protocol server is launched locally by a client process.\n /// \n /// \n /// When using this transport, the server runs as a single-session service that exits when the\n /// stdin stream is closed. This makes it suitable for scenarios where the server should terminate\n /// when the parent process disconnects.\n /// \n /// \n /// is .\n public static IMcpServerBuilder WithStdioServerTransport(this IMcpServerBuilder builder)\n {\n Throw.IfNull(builder);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(sp =>\n {\n var serverOptions = sp.GetRequiredService>();\n var loggerFactory = sp.GetService();\n return new StdioServerTransport(serverOptions.Value, loggerFactory);\n });\n\n return builder;\n }\n\n /// \n /// Adds a server transport that uses the specified input and output streams for communication.\n /// \n /// The builder instance.\n /// The input to use as standard input.\n /// The output to use as standard output.\n /// The builder provided in .\n /// is .\n /// is .\n /// is .\n public static IMcpServerBuilder WithStreamServerTransport(\n this IMcpServerBuilder builder,\n Stream inputStream,\n Stream outputStream)\n {\n Throw.IfNull(builder);\n Throw.IfNull(inputStream);\n Throw.IfNull(outputStream);\n\n AddSingleSessionServerDependencies(builder.Services);\n builder.Services.AddSingleton(new StreamServerTransport(inputStream, outputStream));\n\n return builder;\n }\n\n private static void AddSingleSessionServerDependencies(IServiceCollection services)\n {\n services.AddHostedService();\n services.TryAddSingleton(services =>\n {\n ITransport serverTransport = services.GetRequiredService();\n IOptions options = services.GetRequiredService>();\n ILoggerFactory? loggerFactory = services.GetService();\n return McpServerFactory.Create(serverTransport, options.Value, loggerFactory, services);\n });\n }\n #endregion\n\n #region Helpers\n /// Creates an instance of the target object.\n private static object CreateTarget(\n IServiceProvider? services,\n [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) =>\n services is not null ? ActivatorUtilities.CreateInstance(services, type) :\n Activator.CreateInstance(type)!;\n #endregion\n}\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/AIFunctionMcpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.Concurrent;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Reflection;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerResource : McpServerResource\n{\n private readonly Regex? _uriParser;\n private readonly string[] _templateVariableNames = [];\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n object? target,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerResourceCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n // These parameters are the ones and only ones to include in the schema. The schema\n // won't be consumed by anyone other than this instance, which will use it to determine\n // which properties should show up in the URI template.\n if (pi.Name is not null && GetConverter(pi.ParameterType) is { } converter)\n {\n return new()\n {\n ExcludeFromSchema = false,\n BindParameter = (pi, args) =>\n {\n if (args.TryGetValue(pi.Name!, out var value))\n {\n return\n value is null || pi.ParameterType.IsInstanceOfType(value) ? value :\n value is string stringValue ? converter(stringValue) :\n throw new ArgumentException($\"Parameter '{pi.Name}' is of type '{pi.ParameterType}', but value '{value}' is of type '{value.GetType()}'.\");\n }\n\n return\n pi.HasDefaultValue ? pi.DefaultValue :\n throw new ArgumentException($\"Missing a value for the required parameter '{pi.Name}'.\");\n },\n };\n }\n\n return default;\n },\n };\n\n private static readonly ConcurrentDictionary> s_convertersCache = [];\n\n private static Func? GetConverter(Type type)\n {\n Type key = type;\n\n if (s_convertersCache.TryGetValue(key, out var converter))\n {\n return converter;\n }\n\n if (Nullable.GetUnderlyingType(type) is { } underlyingType)\n {\n // We will have already screened out null values by the time the converter is used,\n // so we can parse just the underlying type.\n type = underlyingType;\n }\n\n if (type == typeof(string) || type == typeof(object)) converter = static s => s;\n if (type == typeof(bool)) converter = static s => bool.Parse(s);\n if (type == typeof(char)) converter = static s => char.Parse(s);\n if (type == typeof(byte)) converter = static s => byte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(sbyte)) converter = static s => sbyte.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ushort)) converter = static s => ushort.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(short)) converter = static s => short.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(uint)) converter = static s => uint.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(int)) converter = static s => int.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(ulong)) converter = static s => ulong.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(long)) converter = static s => long.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(float)) converter = static s => float.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(double)) converter = static s => double.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(decimal)) converter = static s => decimal.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeSpan)) converter = static s => TimeSpan.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTime)) converter = static s => DateTime.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateTimeOffset)) converter = static s => DateTimeOffset.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Uri)) converter = static s => new Uri(s, UriKind.RelativeOrAbsolute);\n if (type == typeof(Guid)) converter = static s => Guid.Parse(s);\n if (type == typeof(Version)) converter = static s => Version.Parse(s);\n#if NET\n if (type == typeof(Half)) converter = static s => Half.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(Int128)) converter = static s => Int128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UInt128)) converter = static s => UInt128.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(IntPtr)) converter = static s => IntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(UIntPtr)) converter = static s => UIntPtr.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(DateOnly)) converter = static s => DateOnly.Parse(s, CultureInfo.InvariantCulture);\n if (type == typeof(TimeOnly)) converter = static s => TimeOnly.Parse(s, CultureInfo.InvariantCulture);\n#endif\n if (type.IsEnum) converter = s => Enum.Parse(type, s);\n\n if (type.GetCustomAttribute() is TypeConverterAttribute tca &&\n Type.GetType(tca.ConverterTypeName, throwOnError: false) is { } converterType &&\n Activator.CreateInstance(converterType) is TypeConverter typeConverter &&\n typeConverter.CanConvertFrom(typeof(string)))\n {\n converter = s => typeConverter.ConvertFrom(null, CultureInfo.InvariantCulture, s);\n }\n\n if (converter is not null)\n {\n s_convertersCache.TryAdd(key, converter);\n }\n\n return converter;\n }\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerResource Create(AIFunction function, McpServerResourceCreateOptions? options)\n {\n Throw.IfNull(function);\n\n string name = options?.Name ?? function.Name;\n\n ResourceTemplate resource = new()\n {\n UriTemplate = options?.UriTemplate ?? DeriveUriTemplate(name, function),\n Name = name,\n Title = options?.Title,\n Description = options?.Description,\n MimeType = options?.MimeType ?? \"application/octet-stream\",\n };\n\n return new AIFunctionMcpServerResource(function, resource);\n }\n\n private static McpServerResourceCreateOptions DeriveOptions(MemberInfo member, McpServerResourceCreateOptions? options)\n {\n McpServerResourceCreateOptions newOptions = options?.Clone() ?? new();\n\n if (member.GetCustomAttribute() is { } resourceAttr)\n {\n newOptions.UriTemplate ??= resourceAttr.UriTemplate;\n newOptions.Name ??= resourceAttr.Name;\n newOptions.Title ??= resourceAttr.Title;\n newOptions.MimeType ??= resourceAttr.MimeType;\n }\n\n if (member.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Derives a name to be used as a resource name.\n private static string DeriveUriTemplate(string name, AIFunction function)\n {\n StringBuilder template = new();\n\n template.Append(\"resource://mcp/\").Append(Uri.EscapeDataString(name));\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n string separator = \"{?\";\n foreach (var prop in properties.EnumerateObject())\n {\n template.Append(separator).Append(prop.Name);\n separator = \",\";\n }\n\n if (separator == \",\")\n {\n template.Append('}');\n }\n }\n\n return template.ToString();\n }\n\n /// Gets the wrapped by this resource.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerResource(AIFunction function, ResourceTemplate resourceTemplate)\n {\n AIFunction = function;\n ProtocolResourceTemplate = resourceTemplate;\n ProtocolResource = resourceTemplate.AsResource();\n\n if (ProtocolResource is null)\n {\n _uriParser = UriTemplate.CreateParser(resourceTemplate.UriTemplate);\n _templateVariableNames = _uriParser.GetGroupNames().Where(n => n != \"0\").ToArray();\n }\n }\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// \n public override Resource? ProtocolResource { get; }\n\n /// \n public override async ValueTask ReadAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n Throw.IfNull(request.Params);\n Throw.IfNull(request.Params.Uri);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n // Check to see if this URI template matches the request URI. If it doesn't, return null.\n // For templates, use the Regex to parse. For static resources, we can just compare the URIs.\n Match? match = null;\n if (_uriParser is not null)\n {\n match = _uriParser.Match(request.Params.Uri);\n if (!match.Success)\n {\n return null;\n }\n }\n else if (!UriTemplate.UriTemplateComparer.Instance.Equals(request.Params.Uri, ProtocolResource!.Uri))\n {\n return null;\n }\n\n // Build up the arguments for the AIFunction call, including all of the name/value pairs from the URI.\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n // For templates, populate the arguments from the URI template.\n if (match is not null)\n {\n foreach (string varName in _templateVariableNames)\n {\n if (match.Groups[varName] is { Success: true } value)\n {\n arguments[varName] = Uri.UnescapeDataString(value.Value);\n }\n }\n }\n\n // Invoke the function.\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n // And process the result.\n return result switch\n {\n ReadResourceResult readResourceResult => readResourceResult,\n\n ResourceContents content => new()\n {\n Contents = [content],\n },\n\n TextContent tc => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = tc.Text }],\n },\n\n DataContent dc => new()\n {\n Contents = [new BlobResourceContents { Uri = request.Params!.Uri, MimeType = dc.MediaType, Blob = dc.Base64Data.ToString() }],\n },\n\n string text => new()\n {\n Contents = [new TextResourceContents { Uri = request.Params!.Uri, MimeType = ProtocolResourceTemplate.MimeType, Text = text }],\n },\n\n IEnumerable contents => new()\n {\n Contents = contents.ToList(),\n },\n\n IEnumerable aiContents => new()\n {\n Contents = aiContents.Select(\n ac => ac switch\n {\n TextContent tc => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = tc.Text\n },\n\n DataContent dc => new BlobResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = dc.MediaType,\n Blob = dc.Base64Data.ToString()\n },\n\n _ => throw new InvalidOperationException($\"Unsupported AIContent type '{ac.GetType()}' returned from resource function.\"),\n }).ToList(),\n },\n\n IEnumerable strings => new()\n {\n Contents = strings.Select(text => new TextResourceContents\n {\n Uri = request.Params!.Uri,\n MimeType = ProtocolResourceTemplate.MimeType,\n Text = text\n }).ToList(),\n },\n\n null => throw new InvalidOperationException(\"Null result returned from resource function.\"),\n\n _ => throw new InvalidOperationException($\"Unsupported result type '{result.GetType()}' returned from resource function.\"),\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpServerTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as\n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \npublic sealed class StreamableHttpServerTransport : ITransport\n{\n // For JsonRpcMessages without a RelatedTransport, we don't want to block just because the client didn't make a GET request to handle unsolicited messages.\n private readonly SseWriter _sseWriter = new(channelOptions: new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n FullMode = BoundedChannelFullMode.DropOldest,\n });\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n private readonly CancellationTokenSource _disposeCts = new();\n\n private int _getRequestStarted;\n\n /// \n public string? SessionId { get; set; }\n\n /// \n /// Configures whether the transport should be in stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process. Unsolicited server-to-client messages are not supported in this mode,\n /// so calling results in an .\n /// Server-to-client requests are also unsupported, because the responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// \n public bool Stateless { get; init; }\n\n /// \n /// Gets a value indicating whether the execution context should flow from the calls to \n /// to the corresponding emitted by the .\n /// \n /// \n /// Defaults to .\n /// \n public bool FlowExecutionContextFromRequests { get; init; }\n\n /// \n /// Gets or sets a callback to be invoked before handling the initialize request.\n /// \n public Func? OnInitRequestReceived { get; set; }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n internal ChannelWriter MessageWriter => _incomingChannel.Writer;\n\n /// \n /// Handles an optional SSE GET request a client using the Streamable HTTP transport might make by\n /// writing any unsolicited JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The response stream to write MCP JSON-RPC messages as SSE events to.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task HandleGetRequest(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"GET requests are not supported in stateless mode.\");\n }\n\n if (Interlocked.Exchange(ref _getRequestStarted, 1) == 1)\n {\n throw new InvalidOperationException(\"Session resumption is not yet supported. Please start a new session.\");\n }\n\n // We do not need to reference _disposeCts like in HandlePostRequest, because the session ending completes the _sseWriter gracefully.\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles a Streamable HTTP POST request processing both the request body and response body ensuring that\n /// and other correlated messages are sent back to the client directly in response\n /// to the that initiated the message.\n /// \n /// The duplex pipe facilitates the reading and writing of HTTP request and response data.\n /// This token allows for the operation to be canceled if needed.\n /// \n /// True, if data was written to the response body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async Task HandlePostRequest(IDuplexPipe httpBodies, CancellationToken cancellationToken)\n {\n using var postCts = CancellationTokenSource.CreateLinkedTokenSource(_disposeCts.Token, cancellationToken);\n await using var postTransport = new StreamableHttpPostTransport(this, httpBodies);\n return await postTransport.RunAsync(postCts.Token).ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (Stateless)\n {\n throw new InvalidOperationException(\"Unsolicited server to client messages are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n }\n finally\n {\n try\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n finally\n {\n _disposeCts.Dispose();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerExtensions.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides extension methods for interacting with an instance.\n/// \npublic static class McpServerExtensions\n{\n /// \n /// Requests to sample an LLM via the client using the specified request parameters.\n /// \n /// The server instance initiating the request.\n /// The parameters for the sampling request.\n /// The to monitor for cancellation requests.\n /// A task containing the sampling result from the client.\n /// is .\n /// The client does not support sampling.\n /// \n /// This method requires the client to support sampling capabilities.\n /// It allows detailed control over sampling parameters including messages, system prompt, temperature, \n /// and token limits.\n /// \n public static ValueTask SampleAsync(\n this IMcpServer server, CreateMessageRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.SamplingCreateMessage,\n request,\n McpJsonUtilities.JsonContext.Default.CreateMessageRequestParams,\n McpJsonUtilities.JsonContext.Default.CreateMessageResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests to sample an LLM via the client using the provided chat messages and options.\n /// \n /// The server initiating the request.\n /// The messages to send as part of the request.\n /// The options to use for the request, including model parameters and constraints.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the chat response from the model.\n /// is .\n /// is .\n /// The client does not support sampling.\n /// \n /// This method converts the provided chat messages into a format suitable for the sampling API,\n /// handling different content types such as text, images, and audio.\n /// \n public static async Task SampleAsync(\n this IMcpServer server,\n IEnumerable messages, ChatOptions? options = default, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n Throw.IfNull(messages);\n\n StringBuilder? systemPrompt = null;\n\n if (options?.Instructions is { } instructions)\n {\n (systemPrompt ??= new()).Append(instructions);\n }\n\n List samplingMessages = [];\n foreach (var message in messages)\n {\n if (message.Role == ChatRole.System)\n {\n if (systemPrompt is null)\n {\n systemPrompt = new();\n }\n else\n {\n systemPrompt.AppendLine();\n }\n\n systemPrompt.Append(message.Text);\n continue;\n }\n\n if (message.Role == ChatRole.User || message.Role == ChatRole.Assistant)\n {\n Role role = message.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n foreach (var content in message.Contents)\n {\n switch (content)\n {\n case TextContent textContent:\n samplingMessages.Add(new()\n {\n Role = role,\n Content = new TextContentBlock { Text = textContent.Text },\n });\n break;\n\n case DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") || dataContent.HasTopLevelMediaType(\"audio\"):\n samplingMessages.Add(new()\n {\n Role = role,\n Content = dataContent.HasTopLevelMediaType(\"image\") ?\n new ImageContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n } :\n new AudioContentBlock\n {\n MimeType = dataContent.MediaType,\n Data = dataContent.Base64Data.ToString(),\n },\n });\n break;\n }\n }\n }\n }\n\n ModelPreferences? modelPreferences = null;\n if (options?.ModelId is { } modelId)\n {\n modelPreferences = new() { Hints = [new() { Name = modelId }] };\n }\n\n var result = await server.SampleAsync(new()\n {\n Messages = samplingMessages,\n MaxTokens = options?.MaxOutputTokens,\n StopSequences = options?.StopSequences?.ToArray(),\n SystemPrompt = systemPrompt?.ToString(),\n Temperature = options?.Temperature,\n ModelPreferences = modelPreferences,\n }, cancellationToken).ConfigureAwait(false);\n\n AIContent? responseContent = result.Content.ToAIContent();\n\n return new(new ChatMessage(result.Role is Role.User ? ChatRole.User : ChatRole.Assistant, responseContent is not null ? [responseContent] : []))\n {\n ModelId = result.Model,\n FinishReason = result.StopReason switch\n {\n \"maxTokens\" => ChatFinishReason.Length,\n \"endTurn\" or \"stopSequence\" or _ => ChatFinishReason.Stop,\n }\n };\n }\n\n /// \n /// Creates an wrapper that can be used to send sampling requests to the client.\n /// \n /// The server to be wrapped as an .\n /// The that can be used to issue sampling requests to the client.\n /// is .\n /// The client does not support sampling.\n public static IChatClient AsSamplingChatClient(this IMcpServer server)\n {\n Throw.IfNull(server);\n ThrowIfSamplingUnsupported(server);\n\n return new SamplingChatClient(server);\n }\n\n /// Gets an on which logged messages will be sent as notifications to the client.\n /// The server to wrap as an .\n /// An that can be used to log to the client..\n public static ILoggerProvider AsClientLoggerProvider(this IMcpServer server)\n {\n Throw.IfNull(server);\n\n return new ClientLoggerProvider(server);\n }\n\n /// \n /// Requests the client to list the roots it exposes.\n /// \n /// The server initiating the request.\n /// The parameters for the list roots request.\n /// The to monitor for cancellation requests.\n /// A task containing the list of roots exposed by the client.\n /// is .\n /// The client does not support roots.\n /// \n /// This method requires the client to support the roots capability.\n /// Root resources allow clients to expose a hierarchical structure of resources that can be\n /// navigated and accessed by the server. These resources might include file systems, databases,\n /// or other structured data sources that the client makes available through the protocol.\n /// \n public static ValueTask RequestRootsAsync(\n this IMcpServer server, ListRootsRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfRootsUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.RootsList,\n request,\n McpJsonUtilities.JsonContext.Default.ListRootsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListRootsResult,\n cancellationToken: cancellationToken);\n }\n\n /// \n /// Requests additional information from the user via the client, allowing the server to elicit structured data.\n /// \n /// The server initiating the request.\n /// The parameters for the elicitation request.\n /// The to monitor for cancellation requests.\n /// A task containing the elicitation result.\n /// is .\n /// The client does not support elicitation.\n /// \n /// This method requires the client to support the elicitation capability.\n /// \n public static ValueTask ElicitAsync(\n this IMcpServer server, ElicitRequestParams request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(server);\n ThrowIfElicitationUnsupported(server);\n\n return server.SendRequestAsync(\n RequestMethods.ElicitationCreate,\n request,\n McpJsonUtilities.JsonContext.Default.ElicitRequestParams,\n McpJsonUtilities.JsonContext.Default.ElicitResult,\n cancellationToken: cancellationToken);\n }\n\n private static void ThrowIfSamplingUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Sampling is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Sampling is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support sampling.\");\n }\n }\n\n private static void ThrowIfRootsUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Roots is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Roots are not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support roots.\");\n }\n }\n\n private static void ThrowIfElicitationUnsupported(IMcpServer server)\n {\n if (server.ClientCapabilities?.Elicitation is null)\n {\n if (server.ServerOptions.KnownClientInfo is not null)\n {\n throw new InvalidOperationException(\"Elicitation is not supported in stateless mode.\");\n }\n\n throw new InvalidOperationException(\"Client does not support elicitation requests.\");\n }\n }\n\n /// Provides an implementation that's implemented via client sampling.\n private sealed class SamplingChatClient(IMcpServer server) : IChatClient\n {\n /// \n public Task GetResponseAsync(IEnumerable messages, ChatOptions? options = null, CancellationToken cancellationToken = default) =>\n server.SampleAsync(messages, options, cancellationToken);\n\n /// \n async IAsyncEnumerable IChatClient.GetStreamingResponseAsync(\n IEnumerable messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n var response = await GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);\n foreach (var update in response.ToChatResponseUpdates())\n {\n yield return update;\n }\n }\n\n /// \n object? IChatClient.GetService(Type serviceType, object? serviceKey)\n {\n Throw.IfNull(serviceType);\n\n return\n serviceKey is not null ? null :\n serviceType.IsInstanceOfType(this) ? this :\n serviceType.IsInstanceOfType(server) ? server :\n null;\n }\n\n /// \n void IDisposable.Dispose() { } // nop\n }\n\n /// \n /// Provides an implementation for creating loggers\n /// that send logging message notifications to the client for logged messages.\n /// \n private sealed class ClientLoggerProvider(IMcpServer server) : ILoggerProvider\n {\n /// \n public ILogger CreateLogger(string categoryName)\n {\n Throw.IfNull(categoryName);\n\n return new ClientLogger(server, categoryName);\n }\n\n /// \n void IDisposable.Dispose() { }\n\n private sealed class ClientLogger(IMcpServer server, string categoryName) : ILogger\n {\n /// \n public IDisposable? BeginScope(TState state) where TState : notnull =>\n null;\n\n /// \n public bool IsEnabled(LogLevel logLevel) =>\n server?.LoggingLevel is { } loggingLevel &&\n McpServer.ToLoggingLevel(logLevel) >= loggingLevel;\n\n /// \n public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)\n {\n if (!IsEnabled(logLevel))\n {\n return;\n }\n\n Throw.IfNull(formatter);\n\n Log(logLevel, formatter(state, exception));\n\n void Log(LogLevel logLevel, string message)\n {\n _ = server.SendNotificationAsync(NotificationMethods.LoggingMessageNotification, new LoggingMessageNotificationParams\n {\n Level = McpServer.ToLoggingLevel(logLevel),\n Data = JsonSerializer.SerializeToElement(message, McpJsonUtilities.JsonContext.Default.String),\n Logger = categoryName,\n });\n }\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/UriTemplate.cs", "#if NET\nusing System.Buffers;\n#endif\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Globalization;\nusing System.Runtime.CompilerServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nnamespace ModelContextProtocol;\n\n/// Provides basic support for parsing and formatting URI templates.\n/// \n/// This implementation should correctly handle valid URI templates, but it has undefined output for invalid templates,\n/// e.g. it may treat portions of invalid templates as literals rather than throwing.\n/// \ninternal static partial class UriTemplate\n{\n /// Regex pattern for finding URI template expressions and parsing out the operator and varname.\n private const string UriTemplateExpressionPattern = \"\"\"\n { # opening brace\n (?[+#./;?&]?) # optional operator\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}) # varchar: letter, digit, underscore, or pct-encoded\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))* # optionally dot-separated subsequent varchars\n )\n (?: :[1-9][0-9]{0,3} )? # optional prefix modifier (1–4 digits)\n \\*? # optional explode\n (?:, # comma separator, followed by the same as above\n (?\n (?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2})\n (?:\\.?(?:[A-Za-z0-9_]|%[0-9A-Fa-f]{2}))*\n )\n (?: :[1-9][0-9]{0,3} )?\n \\*?\n )* # zero or more additional vars\n } # closing brace\n \"\"\";\n\n /// Gets a regex for finding URI template expressions and parsing out the operator and varname.\n /// \n /// This regex is for parsing a static URI template.\n /// It is not for parsing a URI according to a template.\n /// \n#if NET\n [GeneratedRegex(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace)]\n private static partial Regex UriTemplateExpression();\n#else\n private static Regex UriTemplateExpression() => s_uriTemplateExpression;\n private static readonly Regex s_uriTemplateExpression = new(UriTemplateExpressionPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);\n#endif\n\n#if NET\n /// SearchValues for characters that needn't be escaped when allowing reserved characters.\n private static readonly SearchValues s_appendWhenAllowReserved = SearchValues.Create(\n \"abcdefghijklmnopqrstuvwxyz\" + // ASCII lowercase letters\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" + // ASCII uppercase letters\n \"0123456789\" + // ASCII digits\n \"-._~\" + // unreserved characters\n \":/?#[]@!$&'()*+,;=\"); // reserved characters\n#endif\n\n /// Create a for matching a URI against a URI template.\n /// The template against which to match.\n /// A regex pattern that can be used to match the specified URI template.\n public static Regex CreateParser(string uriTemplate)\n {\n DefaultInterpolatedStringHandler pattern = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n pattern.AppendFormatted('^');\n\n int lastIndex = 0;\n for (Match m = UriTemplateExpression().Match(uriTemplate); m.Success; m = m.NextMatch())\n {\n pattern.AppendFormatted(Regex.Escape(uriTemplate[lastIndex..m.Index]));\n lastIndex = m.Index + m.Length;\n\n var captures = m.Groups[\"varname\"].Captures;\n List paramNames = new(captures.Count);\n foreach (Capture c in captures)\n {\n paramNames.Add(c.Value);\n }\n\n switch (m.Groups[\"operator\"].Value)\n {\n case \"#\": AppendExpression(ref pattern, paramNames, '#', \"[^,]+\"); break;\n case \"/\": AppendExpression(ref pattern, paramNames, '/', \"[^/?]+\"); break;\n default: AppendExpression(ref pattern, paramNames, null, \"[^/?&]+\"); break;\n \n case \"?\": AppendQueryExpression(ref pattern, paramNames, '?'); break;\n case \"&\": AppendQueryExpression(ref pattern, paramNames, '&'); break;\n }\n }\n\n pattern.AppendFormatted(Regex.Escape(uriTemplate.Substring(lastIndex)));\n pattern.AppendFormatted('$');\n\n return new Regex(\n pattern.ToStringAndClear(),\n RegexOptions.IgnoreCase | RegexOptions.CultureInvariant |\n#if NET\n RegexOptions.NonBacktracking);\n#else\n RegexOptions.Compiled, TimeSpan.FromSeconds(10));\n#endif\n\n // Appends a regex fragment to `pattern` that matches an optional query string starting\n // with the given `prefix` (? or &), and up to one occurrence of each name in\n // `paramNames`. Each parameter is made optional and captured by a named group\n // of the form “paramName=value”.\n static void AppendQueryExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char prefix)\n {\n Debug.Assert(prefix is '?' or '&');\n\n pattern.AppendFormatted(\"(?:\\\\\");\n pattern.AppendFormatted(prefix);\n\n if (paramNames.Count > 0)\n {\n AppendParameter(ref pattern, paramNames[0]);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\&?\");\n AppendParameter(ref pattern, paramNames[i]);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName)\n {\n paramName = Regex.Escape(paramName);\n pattern.AppendFormatted(\"(?:\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\"=(?<\");\n pattern.AppendFormatted(paramName);\n pattern.AppendFormatted(\">[^/?&]+))?\");\n }\n }\n\n pattern.AppendFormatted(\")?\");\n }\n\n // Chooses a regex character‐class (`valueChars`) based on the initial `prefix` to define which\n // characters make up a parameter value. Then, for each name in `paramNames`, it optionally\n // appends the escaped `prefix` (only on the first parameter, then switches to ','), and\n // adds an optional named capture group `(?valueChars)` to match and capture that value.\n static void AppendExpression(ref DefaultInterpolatedStringHandler pattern, List paramNames, char? prefix, string valueChars)\n {\n Debug.Assert(prefix is '#' or '/' or null);\n\n if (paramNames.Count > 0)\n {\n if (prefix is not null)\n {\n pattern.AppendFormatted('\\\\');\n pattern.AppendFormatted(prefix);\n pattern.AppendFormatted('?');\n }\n\n AppendParameter(ref pattern, paramNames[0], valueChars);\n for (int i = 1; i < paramNames.Count; i++)\n {\n pattern.AppendFormatted(\"\\\\,?\");\n AppendParameter(ref pattern, paramNames[i], valueChars);\n }\n\n static void AppendParameter(ref DefaultInterpolatedStringHandler pattern, string paramName, string valueChars)\n {\n pattern.AppendFormatted(\"(?<\");\n pattern.AppendFormatted(Regex.Escape(paramName));\n pattern.AppendFormatted('>');\n pattern.AppendFormatted(valueChars);\n pattern.AppendFormatted(\")?\");\n }\n }\n }\n }\n\n /// \n /// Expand a URI template using the given variable values.\n /// \n public static string FormatUri(string uriTemplate, IReadOnlyDictionary arguments)\n {\n Throw.IfNull(uriTemplate);\n\n ReadOnlySpan uriTemplateSpan = uriTemplate.AsSpan();\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n while (!uriTemplateSpan.IsEmpty)\n {\n // Find the next expression.\n int openBracePos = uriTemplateSpan.IndexOf('{');\n if (openBracePos < 0)\n {\n if (uriTemplate.Length == uriTemplateSpan.Length)\n {\n return uriTemplate;\n }\n\n builder.AppendFormatted(uriTemplateSpan);\n break;\n }\n\n // Append as a literal everything before the next expression.\n builder.AppendFormatted(uriTemplateSpan.Slice(0, openBracePos));\n uriTemplateSpan = uriTemplateSpan.Slice(openBracePos + 1);\n\n int closeBracePos = uriTemplateSpan.IndexOf('}');\n if (closeBracePos < 0)\n {\n throw new FormatException($\"Unmatched '{{' in URI template '{uriTemplate}'\");\n }\n\n ReadOnlySpan expression = uriTemplateSpan.Slice(0, closeBracePos);\n uriTemplateSpan = uriTemplateSpan.Slice(closeBracePos + 1);\n if (expression.IsEmpty)\n {\n continue;\n }\n\n // The start of the expression may be a modifier; if it is, slice it off the expression.\n char modifier = expression[0];\n (string Prefix, string Separator, bool Named, bool IncludeNameIfEmpty, bool IncludeSeparatorIfEmpty, bool AllowReserved, bool PrefixEmptyExpansions, int ExpressionSlice) modifierBehavior = modifier switch\n {\n '+' => (string.Empty, \",\", false, false, true, true, false, 1),\n '#' => (\"#\", \",\", false, false, true, true, true, 1),\n '.' => (\".\", \".\", false, false, true, false, true, 1),\n '/' => (\"/\", \"/\", false, false, true, false, false, 1),\n ';' => (\";\", \";\", true, true, false, false, false, 1),\n '?' => (\"?\", \"&\", true, true, true, false, false, 1),\n '&' => (\"&\", \"&\", true, true, true, false, false, 1),\n _ => (string.Empty, \",\", false, false, true, false, false, 0),\n };\n expression = expression.Slice(modifierBehavior.ExpressionSlice);\n\n List expansions = [];\n\n // Process each varspec in the comma-delimited list in the expression (if it doesn't have any\n // commas, it will be the whole expression).\n while (!expression.IsEmpty)\n {\n // Find the next name.\n int commaPos = expression.IndexOf(',');\n ReadOnlySpan name;\n if (commaPos < 0)\n {\n name = expression;\n expression = ReadOnlySpan.Empty;\n }\n else\n {\n name = expression.Slice(0, commaPos);\n expression = expression.Slice(commaPos + 1);\n }\n\n bool explode = false;\n int prefixLength = -1;\n\n // If the name ends with a *, it means we should explode the value into separate\n // name=value pairs. If it has a colon, it means we should only take the first N characters\n // of the value. If it has both, the * takes precedence and we ignore the colon.\n if (!name.IsEmpty && name[name.Length - 1] == '*')\n {\n explode = true;\n name = name.Slice(0, name.Length - 1);\n }\n else if (name.IndexOf(':') >= 0)\n {\n int colonPos = name.IndexOf(':');\n if (colonPos < 0)\n {\n throw new FormatException($\"Invalid varspec '{name.ToString()}'\");\n }\n\n if (!int.TryParse(name.Slice(colonPos + 1)\n#if !NET\n .ToString()\n#endif\n , out prefixLength))\n {\n throw new FormatException($\"Invalid prefix length in varspec '{name.ToString()}'\");\n }\n\n name = name.Slice(0, colonPos);\n }\n\n // Look up the value for this name. If it doesn't exist, skip it.\n string nameString = name.ToString();\n if (!arguments.TryGetValue(nameString, out var value) || value is null)\n {\n continue;\n }\n\n if (value is IEnumerable list)\n {\n var items = list.Select(i => Encode(i, modifierBehavior.AllowReserved));\n if (explode)\n {\n if (modifierBehavior.Named)\n {\n foreach (var item in items)\n {\n expansions.Add($\"{nameString}={item}\");\n }\n }\n else\n {\n foreach (var item in items)\n {\n expansions.Add(item);\n }\n }\n }\n else\n {\n var joined = string.Join(\",\", items);\n expansions.Add(joined.Length > 0 && modifierBehavior.Named ?\n $\"{nameString}={joined}\" :\n joined);\n }\n }\n else if (value is IReadOnlyDictionary assoc)\n {\n var pairs = assoc.Select(kvp => (\n Encode(kvp.Key, modifierBehavior.AllowReserved),\n Encode(kvp.Value, modifierBehavior.AllowReserved)\n ));\n\n if (explode)\n {\n foreach (var (k, v) in pairs)\n {\n expansions.Add($\"{k}={v}\");\n }\n }\n else\n {\n var joined = string.Join(\",\", pairs.Select(p => $\"{p.Item1},{p.Item2}\"));\n if (joined.Length > 0)\n {\n expansions.Add(modifierBehavior.Named ? $\"{nameString}={joined}\" : joined);\n }\n }\n }\n else\n {\n string s =\n value as string ??\n (value is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture) : value.ToString()) ??\n string.Empty;\n\n s = Encode((uint)prefixLength < s.Length ? s.Substring(0, prefixLength) : s, modifierBehavior.AllowReserved);\n if (!modifierBehavior.Named)\n {\n expansions.Add(s);\n }\n else if (s.Length != 0 || modifierBehavior.IncludeNameIfEmpty)\n {\n expansions.Add(\n s.Length != 0 ? $\"{nameString}={s}\" :\n modifierBehavior.IncludeSeparatorIfEmpty ? $\"{nameString}=\" :\n nameString);\n }\n }\n }\n\n if (expansions.Count > 0 && \n (modifierBehavior.PrefixEmptyExpansions || !expansions.All(string.IsNullOrEmpty)))\n {\n builder.AppendLiteral(modifierBehavior.Prefix);\n AppendJoin(ref builder, modifierBehavior.Separator, expansions);\n }\n }\n\n return builder.ToStringAndClear();\n }\n\n private static void AppendJoin(ref DefaultInterpolatedStringHandler builder, string separator, IList values)\n {\n int count = values.Count;\n if (count > 0)\n {\n builder.AppendLiteral(values[0]);\n for (int i = 1; i < count; i++)\n {\n builder.AppendLiteral(separator);\n builder.AppendLiteral(values[i]);\n }\n }\n }\n\n private static string Encode(string value, bool allowReserved)\n {\n if (!allowReserved)\n {\n return Uri.EscapeDataString(value);\n }\n\n DefaultInterpolatedStringHandler builder = new(0, 0, CultureInfo.InvariantCulture, stackalloc char[256]);\n int i = 0;\n#if NET\n i = value.AsSpan().IndexOfAnyExcept(s_appendWhenAllowReserved);\n if (i < 0)\n {\n return value;\n }\n\n builder.AppendFormatted(value.AsSpan(0, i));\n#endif\n\n for (; i < value.Length; ++i)\n {\n char c = value[i];\n if (((uint)((c | 0x20) - 'a') <= 'z' - 'a') ||\n ((uint)(c - '0') <= '9' - '0') ||\n \"-._~:/?#[]@!$&'()*+,;=\".Contains(c))\n {\n builder.AppendFormatted(c);\n }\n else if (c == '%' && i < value.Length - 2 && Uri.IsHexDigit(value[i + 1]) && Uri.IsHexDigit(value[i + 2]))\n {\n builder.AppendFormatted(value.AsSpan(i, 3));\n i += 2;\n }\n else\n {\n AppendHex(ref builder, c);\n }\n }\n\n return builder.ToStringAndClear();\n\n static void AppendHex(ref DefaultInterpolatedStringHandler builder, char c)\n {\n ReadOnlySpan hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];\n\n if (c <= 0x7F)\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[c >> 4]);\n builder.AppendFormatted(hexDigits[c & 0xF]);\n }\n else\n {\n#if NET\n Span utf8 = stackalloc byte[Encoding.UTF8.GetMaxByteCount(1)];\n foreach (byte b in utf8.Slice(0, new Rune(c).EncodeToUtf8(utf8)))\n#else\n foreach (byte b in Encoding.UTF8.GetBytes([c]))\n#endif\n {\n builder.AppendFormatted('%');\n builder.AppendFormatted(hexDigits[b >> 4]);\n builder.AppendFormatted(hexDigits[b & 0xF]);\n }\n }\n }\n }\n\n /// \n /// Defines an equality comparer for Uri templates as follows:\n /// 1. Non-templated Uris use regular System.Uri equality comparison (host name is case insensitive).\n /// 2. Templated Uris use regular string equality.\n /// \n /// We do this because non-templated resources are looked up directly from the resource dictionary\n /// and we need to make sure equality is implemented correctly. Templated Uris are resolved in a\n /// fallback step using linear traversal of the resource dictionary, so their equality is only\n /// there to distinguish between different templates.\n /// \n public sealed class UriTemplateComparer : IEqualityComparer\n {\n public static IEqualityComparer Instance { get; } = new UriTemplateComparer();\n\n public bool Equals(string? uriTemplate1, string? uriTemplate2)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate1, out Uri? uri1) &&\n TryParseAsNonTemplatedUri(uriTemplate2, out Uri? uri2))\n {\n return uri1 == uri2;\n }\n\n return string.Equals(uriTemplate1, uriTemplate2, StringComparison.Ordinal);\n }\n\n public int GetHashCode([DisallowNull] string uriTemplate)\n {\n if (TryParseAsNonTemplatedUri(uriTemplate, out Uri? uri))\n {\n return uri.GetHashCode();\n }\n else\n {\n return StringComparer.Ordinal.GetHashCode(uriTemplate);\n }\n }\n\n private static bool TryParseAsNonTemplatedUri(string? uriTemplate, [NotNullWhen(true)] out Uri? uri)\n {\n if (uriTemplate is null || uriTemplate.Contains('{'))\n {\n uri = null;\n return false;\n }\n\n return Uri.TryCreate(uriTemplate, UriKind.Absolute, out uri);\n }\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/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/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/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/Protocol/JsonRpcMessage.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents any JSON-RPC message used in the Model Context Protocol (MCP).\n/// \n/// \n/// This interface serves as the foundation for all message types in the JSON-RPC 2.0 protocol\n/// used by MCP, including requests, responses, notifications, and errors. JSON-RPC is a stateless,\n/// lightweight remote procedure call (RPC) protocol that uses JSON as its data format.\n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessage()\n {\n }\n\n /// \n /// Gets the JSON-RPC protocol version used.\n /// \n /// \n [JsonPropertyName(\"jsonrpc\")]\n public string JsonRpc { get; init; } = \"2.0\";\n\n /// \n /// Gets or sets the transport the was received on or should be sent over.\n /// \n /// \n /// This is used to support the Streamable HTTP transport where the specification states that the server\n /// SHOULD include JSON-RPC responses in the HTTP response body for the POST request containing\n /// the corresponding JSON-RPC request. It may be for other transports.\n /// \n [JsonIgnore]\n public ITransport? RelatedTransport { get; set; }\n\n /// \n /// Gets or sets the that should be used to run any handlers\n /// \n /// \n /// This is used to support the Streamable HTTP transport in its default stateful mode. In this mode,\n /// the outlives the initial HTTP request context it was created on, and new\n /// JSON-RPC messages can originate from future HTTP requests. This allows the transport to flow the\n /// context with the JSON-RPC message. This is particularly useful for enabling IHttpContextAccessor\n /// in tool calls.\n /// \n [JsonIgnore]\n public ExecutionContext? ExecutionContext { get; set; }\n\n /// \n /// Provides a for messages,\n /// handling polymorphic deserialization of different message types.\n /// \n /// \n /// \n /// This converter is responsible for correctly deserializing JSON-RPC messages into their appropriate\n /// concrete types based on the message structure. It analyzes the JSON payload and determines if it\n /// represents a request, notification, successful response, or error response.\n /// \n /// \n /// The type determination rules follow the JSON-RPC 2.0 specification:\n /// \n /// Messages with \"method\" and \"id\" properties are deserialized as .\n /// Messages with \"method\" but no \"id\" property are deserialized as .\n /// Messages with \"id\" and \"result\" properties are deserialized as .\n /// Messages with \"id\" and \"error\" properties are deserialized as .\n /// \n /// \n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override JsonRpcMessage? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException(\"Expected StartObject token\");\n }\n\n using var doc = JsonDocument.ParseValue(ref reader);\n var root = doc.RootElement;\n\n // All JSON-RPC messages must have a jsonrpc property with value \"2.0\"\n if (!root.TryGetProperty(\"jsonrpc\", out var versionProperty) ||\n versionProperty.GetString() != \"2.0\")\n {\n throw new JsonException(\"Invalid or missing jsonrpc version\");\n }\n\n // Determine the message type based on the presence of id, method, and error properties\n bool hasId = root.TryGetProperty(\"id\", out _);\n bool hasMethod = root.TryGetProperty(\"method\", out _);\n bool hasError = root.TryGetProperty(\"error\", out _);\n\n var rawText = root.GetRawText();\n\n // Messages with an id but no method are responses\n if (hasId && !hasMethod)\n {\n // Messages with an error property are error responses\n if (hasError)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with a result property are success responses\n if (root.TryGetProperty(\"result\", out _))\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Response must have either result or error\");\n }\n\n // Messages with a method but no id are notifications\n if (hasMethod && !hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n // Messages with both method and id are requests\n if (hasMethod && hasId)\n {\n return JsonSerializer.Deserialize(rawText, options.GetTypeInfo());\n }\n\n throw new JsonException(\"Invalid JSON-RPC message format\");\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, JsonRpcMessage value, JsonSerializerOptions options)\n {\n switch (value)\n {\n case JsonRpcRequest request:\n JsonSerializer.Serialize(writer, request, options.GetTypeInfo());\n break;\n case JsonRpcNotification notification:\n JsonSerializer.Serialize(writer, notification, options.GetTypeInfo());\n break;\n case JsonRpcResponse response:\n JsonSerializer.Serialize(writer, response, options.GetTypeInfo());\n break;\n case JsonRpcError error:\n JsonSerializer.Serialize(writer, error, options.GetTypeInfo());\n break;\n default:\n throw new JsonException($\"Unknown JSON-RPC message type: {value.GetType()}\");\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientSessionTransport.cs", "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 protected override async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)\n {\n // Only clean up once.\n if (Interlocked.Exchange(ref _cleanedUp, 1) != 0)\n {\n return;\n }\n\n // We've not yet forcefully terminated the server. If it's already shut down, something went wrong,\n // so create an exception with details about that.\n error ??= await GetUnexpectedExitExceptionAsync(cancellationToken).ConfigureAwait(false);\n\n // Now terminate the server process.\n try\n {\n StdioClientTransport.DisposeProcess(_process, processRunning: true, _options.ShutdownTimeout, Name);\n }\n catch (Exception ex)\n {\n LogTransportShutdownFailed(Name, ex);\n }\n\n // And handle cleanup in the base type.\n await base.CleanupAsync(error, cancellationToken);\n }\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"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/SseWriter.cs", "using ModelContextProtocol.Protocol;\nusing System.Buffers;\nusing System.Net.ServerSentEvents;\nusing System.Text;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class SseWriter(string? messageEndpoint = null, BoundedChannelOptions? channelOptions = null) : IAsyncDisposable\n{\n private readonly Channel> _messages = Channel.CreateBounded>(channelOptions ?? new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private Utf8JsonWriter? _jsonWriter;\n private Task? _writeTask;\n private CancellationToken? _writeCancellationToken;\n\n private readonly SemaphoreSlim _disposeLock = new(1, 1);\n private bool _disposed;\n\n public Func>, CancellationToken, IAsyncEnumerable>>? MessageFilter { get; set; }\n\n public Task WriteAllAsync(Stream sseResponseStream, CancellationToken cancellationToken)\n {\n // When messageEndpoint is set, the very first SSE event isn't really an IJsonRpcMessage, but there's no API to write a single\n // item of a different type, so we fib and special-case the \"endpoint\" event type in the formatter.\n if (messageEndpoint is not null && !_messages.Writer.TryWrite(new SseItem(null, \"endpoint\")))\n {\n throw new InvalidOperationException(\"You must call RunAsync before calling SendMessageAsync.\");\n }\n\n _writeCancellationToken = cancellationToken;\n\n var messages = _messages.Reader.ReadAllAsync(cancellationToken);\n if (MessageFilter is not null)\n {\n messages = MessageFilter(messages, cancellationToken);\n }\n\n _writeTask = SseFormatter.WriteAsync(messages, sseResponseStream, WriteJsonRpcMessageToBuffer, cancellationToken);\n return _writeTask;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(message);\n\n using var _ = await _disposeLock.LockAsync(cancellationToken).ConfigureAwait(false);\n\n if (_disposed)\n {\n // Don't throw an ODE, because this is disposed internally when the transport disconnects due to an abort\n // or sending all the responses for the a give given Streamable HTTP POST request, so the user might not be at fault.\n // There's precedence for no-oping here similar to writing to the response body of an aborted request in ASP.NET Core.\n return;\n }\n\n // Emit redundant \"event: message\" lines for better compatibility with other SDKs.\n await _messages.Writer.WriteAsync(new SseItem(message, SseParser.EventTypeDefault), cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);\n\n if (_disposed)\n {\n return;\n }\n\n _messages.Writer.Complete();\n try\n {\n if (_writeTask is not null)\n {\n await _writeTask.ConfigureAwait(false);\n }\n }\n catch (OperationCanceledException) when (_writeCancellationToken?.IsCancellationRequested == true)\n {\n // Ignore exceptions caused by intentional cancellation during shutdown.\n }\n finally\n {\n _jsonWriter?.Dispose();\n _disposed = true;\n }\n }\n\n private void WriteJsonRpcMessageToBuffer(SseItem item, IBufferWriter writer)\n {\n if (item.EventType == \"endpoint\" && messageEndpoint is not null)\n {\n writer.Write(Encoding.UTF8.GetBytes(messageEndpoint));\n return;\n }\n\n JsonSerializer.Serialize(GetUtf8JsonWriter(writer), item.Data, McpJsonUtilities.JsonContext.Default.JsonRpcMessage!);\n }\n\n private Utf8JsonWriter GetUtf8JsonWriter(IBufferWriter writer)\n {\n if (_jsonWriter is null)\n {\n _jsonWriter = new Utf8JsonWriter(writer);\n }\n else\n {\n _jsonWriter.Reset(writer);\n }\n\n return _jsonWriter;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/IdleTrackingBackgroundService.cs", "using System.Runtime.InteropServices;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed partial class IdleTrackingBackgroundService(\n StreamableHttpHandler handler,\n IOptions options,\n IHostApplicationLifetime appLifetime,\n ILogger logger) : BackgroundService\n{\n // The compiler will complain about the parameter being unused otherwise despite the source generator.\n private readonly ILogger _logger = logger;\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n // Still run loop given infinite IdleTimeout to enforce the MaxIdleSessionCount and assist graceful shutdown.\n if (options.Value.IdleTimeout != Timeout.InfiniteTimeSpan)\n {\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.IdleTimeout, TimeSpan.Zero);\n }\n\n ArgumentOutOfRangeException.ThrowIfLessThan(options.Value.MaxIdleSessionCount, 0);\n\n try\n {\n var timeProvider = options.Value.TimeProvider;\n using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5), timeProvider);\n\n var idleTimeoutTicks = options.Value.IdleTimeout.Ticks;\n var maxIdleSessionCount = options.Value.MaxIdleSessionCount;\n\n // Create two lists that will be reused between runs.\n // This assumes that the number of idle sessions is not breached frequently.\n // If the idle sessions often breach the maximum, a priority queue could be considered.\n var idleSessionsTimestamps = new List();\n var idleSessionSessionIds = new List();\n\n while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))\n {\n var idleActivityCutoff = idleTimeoutTicks switch\n {\n < 0 => long.MinValue,\n var ticks => timeProvider.GetTimestamp() - ticks,\n };\n\n foreach (var (_, session) in handler.Sessions)\n {\n if (session.IsActive || session.SessionClosed.IsCancellationRequested)\n {\n // There's a request currently active or the session is already being closed.\n continue;\n }\n\n if (session.LastActivityTicks < idleActivityCutoff)\n {\n RemoveAndCloseSession(session.Id);\n continue;\n }\n\n // Add the timestamp and the session\n idleSessionsTimestamps.Add(session.LastActivityTicks);\n idleSessionSessionIds.Add(session.Id);\n\n // Emit critical log at most once every 5 seconds the idle count it exceeded,\n // since the IdleTimeout will no longer be respected.\n if (idleSessionsTimestamps.Count == maxIdleSessionCount + 1)\n {\n LogMaxSessionIdleCountExceeded(maxIdleSessionCount);\n }\n }\n\n if (idleSessionsTimestamps.Count > maxIdleSessionCount)\n {\n var timestamps = CollectionsMarshal.AsSpan(idleSessionsTimestamps);\n\n // Sort only if the maximum is breached and sort solely by the timestamp. Sort both collections.\n timestamps.Sort(CollectionsMarshal.AsSpan(idleSessionSessionIds));\n\n var sessionsToPrune = CollectionsMarshal.AsSpan(idleSessionSessionIds)[..^maxIdleSessionCount];\n foreach (var id in sessionsToPrune)\n {\n RemoveAndCloseSession(id);\n }\n }\n\n idleSessionsTimestamps.Clear();\n idleSessionSessionIds.Clear();\n }\n }\n catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)\n {\n }\n finally\n {\n try\n {\n List disposeSessionTasks = [];\n\n foreach (var (sessionKey, _) in handler.Sessions)\n {\n if (handler.Sessions.TryRemove(sessionKey, out var session))\n {\n disposeSessionTasks.Add(DisposeSessionAsync(session));\n }\n }\n\n await Task.WhenAll(disposeSessionTasks);\n }\n finally\n {\n if (!stoppingToken.IsCancellationRequested)\n {\n // Something went terribly wrong. A very unexpected exception must be bubbling up, but let's ensure we also stop the application,\n // so that it hopefully gets looked at and restarted. This shouldn't really be reachable.\n appLifetime.StopApplication();\n IdleTrackingBackgroundServiceStoppedUnexpectedly();\n }\n }\n }\n }\n\n private void RemoveAndCloseSession(string sessionId)\n {\n if (!handler.Sessions.TryRemove(sessionId, out var session))\n {\n return;\n }\n\n LogSessionIdle(session.Id);\n // Don't slow down the idle tracking loop. DisposeSessionAsync logs. We only await during graceful shutdown.\n _ = DisposeSessionAsync(session);\n }\n\n private async Task DisposeSessionAsync(HttpMcpSession session)\n {\n try\n {\n await session.DisposeAsync();\n }\n catch (Exception ex)\n {\n LogSessionDisposeError(session.Id, ex);\n }\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Closing idle session {sessionId}.\")]\n private partial void LogSessionIdle(string sessionId);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"Error disposing session {sessionId}.\")]\n private partial void LogSessionDisposeError(string sessionId, Exception ex);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"Exceeded maximum of {maxIdleSessionCount} idle sessions. Now closing sessions active more recently than configured IdleTimeout.\")]\n private partial void LogMaxSessionIdleCountExceeded(int maxIdleSessionCount);\n\n [LoggerMessage(Level = LogLevel.Critical, Message = \"The IdleTrackingBackgroundService has stopped unexpectedly.\")]\n private partial void IdleTrackingBackgroundServiceStoppedUnexpectedly();\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/Common/CancellableStreamReader/ValueStringBuilder.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.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\n#nullable enable\n\nnamespace System.Text\n{\n internal ref partial struct ValueStringBuilder\n {\n private char[]? _arrayToReturnToPool;\n private Span _chars;\n private int _pos;\n\n public ValueStringBuilder(Span initialBuffer)\n {\n _arrayToReturnToPool = null;\n _chars = initialBuffer;\n _pos = 0;\n }\n\n public ValueStringBuilder(int initialCapacity)\n {\n _arrayToReturnToPool = ArrayPool.Shared.Rent(initialCapacity);\n _chars = _arrayToReturnToPool;\n _pos = 0;\n }\n\n public int Length\n {\n get => _pos;\n set\n {\n Debug.Assert(value >= 0);\n Debug.Assert(value <= _chars.Length);\n _pos = value;\n }\n }\n\n public int Capacity => _chars.Length;\n\n public void EnsureCapacity(int capacity)\n {\n // This is not expected to be called this with negative capacity\n Debug.Assert(capacity >= 0);\n\n // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.\n if ((uint)capacity > (uint)_chars.Length)\n Grow(capacity - _pos);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// Does not ensure there is a null char after \n /// This overload is pattern matched in the C# 7.3+ compiler so you can omit\n /// the explicit method call, and write eg \"fixed (char* c = builder)\"\n /// \n public ref char GetPinnableReference()\n {\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n /// \n /// Get a pinnable reference to the builder.\n /// \n /// Ensures that the builder has a null char after \n public ref char GetPinnableReference(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return ref MemoryMarshal.GetReference(_chars);\n }\n\n public ref char this[int index]\n {\n get\n {\n Debug.Assert(index < _pos);\n return ref _chars[index];\n }\n }\n\n public override string ToString()\n {\n string s = _chars.Slice(0, _pos).ToString();\n Dispose();\n return s;\n }\n\n /// Returns the underlying storage of the builder.\n public Span RawChars => _chars;\n\n /// \n /// Returns a span around the contents of the builder.\n /// \n /// Ensures that the builder has a null char after \n public ReadOnlySpan AsSpan(bool terminate)\n {\n if (terminate)\n {\n EnsureCapacity(Length + 1);\n _chars[Length] = '\\0';\n }\n return _chars.Slice(0, _pos);\n }\n\n public ReadOnlySpan AsSpan() => _chars.Slice(0, _pos);\n public ReadOnlySpan AsSpan(int start) => _chars.Slice(start, _pos - start);\n public ReadOnlySpan AsSpan(int start, int length) => _chars.Slice(start, length);\n\n public bool TryCopyTo(Span destination, out int charsWritten)\n {\n if (_chars.Slice(0, _pos).TryCopyTo(destination))\n {\n charsWritten = _pos;\n Dispose();\n return true;\n }\n else\n {\n charsWritten = 0;\n Dispose();\n return false;\n }\n }\n\n public void Insert(int index, char value, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n _chars.Slice(index, count).Fill(value);\n _pos += count;\n }\n\n public void Insert(int index, string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int count = s.Length;\n\n if (_pos > (_chars.Length - count))\n {\n Grow(count);\n }\n\n int remaining = _pos - index;\n _chars.Slice(index, remaining).CopyTo(_chars.Slice(index + count));\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(index));\n _pos += count;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(char c)\n {\n int pos = _pos;\n Span chars = _chars;\n if ((uint)pos < (uint)chars.Length)\n {\n chars[pos] = c;\n _pos = pos + 1;\n }\n else\n {\n GrowAndAppend(c);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Append(string? s)\n {\n if (s == null)\n {\n return;\n }\n\n int pos = _pos;\n if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.\n {\n _chars[pos] = s[0];\n _pos = pos + 1;\n }\n else\n {\n AppendSlow(s);\n }\n }\n\n private void AppendSlow(string s)\n {\n int pos = _pos;\n if (pos > _chars.Length - s.Length)\n {\n Grow(s.Length);\n }\n\n s\n#if !NET\n .AsSpan()\n#endif\n .CopyTo(_chars.Slice(pos));\n _pos += s.Length;\n }\n\n public void Append(char c, int count)\n {\n if (_pos > _chars.Length - count)\n {\n Grow(count);\n }\n\n Span dst = _chars.Slice(_pos, count);\n for (int i = 0; i < dst.Length; i++)\n {\n dst[i] = c;\n }\n _pos += count;\n }\n\n public void Append(scoped ReadOnlySpan value)\n {\n int pos = _pos;\n if (pos > _chars.Length - value.Length)\n {\n Grow(value.Length);\n }\n\n value.CopyTo(_chars.Slice(_pos));\n _pos += value.Length;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public Span AppendSpan(int length)\n {\n int origPos = _pos;\n if (origPos > _chars.Length - length)\n {\n Grow(length);\n }\n\n _pos = origPos + length;\n return _chars.Slice(origPos, length);\n }\n\n [MethodImpl(MethodImplOptions.NoInlining)]\n private void GrowAndAppend(char c)\n {\n Grow(1);\n Append(c);\n }\n\n /// \n /// Resize the internal buffer either by doubling current buffer size or\n /// by adding to\n /// whichever is greater.\n /// \n /// \n /// Number of chars requested beyond current position.\n /// \n [MethodImpl(MethodImplOptions.NoInlining)]\n private void Grow(int additionalCapacityBeyondPos)\n {\n Debug.Assert(additionalCapacityBeyondPos > 0);\n Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, \"Grow called incorrectly, no resize is needed.\");\n\n const uint ArrayMaxLength = 0x7FFFFFC7; // same as Array.MaxLength\n\n // Increase to at least the required size (_pos + additionalCapacityBeyondPos), but try\n // to double the size if possible, bounding the doubling to not go beyond the max array length.\n int newCapacity = (int)Math.Max(\n (uint)(_pos + additionalCapacityBeyondPos),\n Math.Min((uint)_chars.Length * 2, ArrayMaxLength));\n\n // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative.\n // This could also go negative if the actual required length wraps around.\n char[] poolArray = ArrayPool.Shared.Rent(newCapacity);\n\n _chars.Slice(0, _pos).CopyTo(poolArray);\n\n char[]? toReturn = _arrayToReturnToPool;\n _chars = _arrayToReturnToPool = poolArray;\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public void Dispose()\n {\n char[]? toReturn = _arrayToReturnToPool;\n this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again\n if (toReturn != null)\n {\n ArrayPool.Shared.Return(toReturn);\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpEndpointExtensions.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for interacting with an .\n/// \n/// \n/// \n/// This class provides strongly-typed methods for working with the Model Context Protocol (MCP) endpoints,\n/// simplifying JSON-RPC communication by handling serialization and deserialization of parameters and results.\n/// \n/// \n/// These extension methods are designed to be used with both client () and\n/// server () implementations of the interface.\n/// \n/// \npublic static class McpEndpointExtensions\n{\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The request id for the request.\n /// The options governing request serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n public static ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo paramsTypeInfo = serializerOptions.GetTypeInfo();\n JsonTypeInfo resultTypeInfo = serializerOptions.GetTypeInfo();\n return SendRequestAsync(endpoint, method, parameters, paramsTypeInfo, resultTypeInfo, requestId, cancellationToken);\n }\n\n /// \n /// Sends a JSON-RPC request and attempts to deserialize the result to .\n /// \n /// The type of the request parameters to serialize from.\n /// The type of the result to deserialize to.\n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The type information for request parameter deserialization.\n /// The request id for the request.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous operation. The task result contains the deserialized result.\n internal static async ValueTask SendRequestAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n JsonTypeInfo resultTypeInfo,\n RequestId requestId = default,\n CancellationToken cancellationToken = default)\n where TResult : notnull\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n Throw.IfNull(resultTypeInfo);\n\n JsonRpcRequest jsonRpcRequest = new()\n {\n Id = requestId,\n Method = method,\n Params = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo),\n };\n\n JsonRpcResponse response = await endpoint.SendRequestAsync(jsonRpcRequest, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.Deserialize(response.Result, resultTypeInfo) ?? throw new JsonException(\"Unexpected JSON result in response.\");\n }\n\n /// \n /// Sends a parameterless notification to the connected endpoint.\n /// \n /// The MCP client or server instance.\n /// The notification method name.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification without any parameters. Notifications are one-way messages \n /// that don't expect a response. They are commonly used for events, status updates, or to signal \n /// changes in state.\n /// \n /// \n public static Task SendNotificationAsync(this IMcpEndpoint client, string method, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(client);\n Throw.IfNullOrWhiteSpace(method);\n return client.SendMessageAsync(new JsonRpcNotification { Method = method }, cancellationToken);\n }\n\n /// \n /// Sends a notification with parameters to the connected endpoint.\n /// \n /// The type of the notification parameters to serialize.\n /// The MCP client or server instance.\n /// The JSON-RPC method name for the notification.\n /// Object representing the notification parameters.\n /// The options governing parameter serialization. If null, default options are used.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// \n /// \n /// This method sends a notification with parameters to the connected endpoint. Notifications are one-way \n /// messages that don't expect a response, commonly used for events, status updates, or signaling changes.\n /// \n /// \n /// The parameters object is serialized to JSON according to the provided serializer options or the default \n /// options if none are specified.\n /// \n /// \n /// The Model Context Protocol defines several standard notification methods in ,\n /// but custom methods can also be used for application-specific notifications.\n /// \n /// \n public static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n serializerOptions ??= McpJsonUtilities.DefaultOptions;\n serializerOptions.MakeReadOnly();\n\n JsonTypeInfo parametersTypeInfo = serializerOptions.GetTypeInfo();\n return SendNotificationAsync(endpoint, method, parameters, parametersTypeInfo, cancellationToken);\n }\n\n /// \n /// Sends a notification to the server with parameters.\n /// \n /// The MCP client or server instance.\n /// The JSON-RPC method name to invoke.\n /// Object representing the request parameters.\n /// The type information for request parameter serialization.\n /// The to monitor for cancellation requests. The default is .\n internal static Task SendNotificationAsync(\n this IMcpEndpoint endpoint,\n string method,\n TParameters parameters,\n JsonTypeInfo parametersTypeInfo,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(parametersTypeInfo);\n\n JsonNode? parametersJson = JsonSerializer.SerializeToNode(parameters, parametersTypeInfo);\n return endpoint.SendMessageAsync(new JsonRpcNotification { Method = method, Params = parametersJson }, cancellationToken);\n }\n\n /// \n /// Notifies the connected endpoint of progress for a long-running operation.\n /// \n /// The endpoint issuing the notification.\n /// The identifying the operation for which progress is being reported.\n /// The progress update to send, containing information such as percentage complete or status message.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the completion of the notification operation (not the operation being tracked).\n /// is .\n /// \n /// \n /// This method sends a progress notification to the connected endpoint using the Model Context Protocol's\n /// standardized progress notification format. Progress updates are identified by a \n /// that allows the recipient to correlate multiple updates with a specific long-running operation.\n /// \n /// \n /// Progress notifications are sent asynchronously and don't block the operation from continuing.\n /// \n /// \n public static Task NotifyProgressAsync(\n this IMcpEndpoint endpoint,\n ProgressToken progressToken,\n ProgressNotificationValue progress, \n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(endpoint);\n\n return endpoint.SendNotificationAsync(\n NotificationMethods.ProgressNotification,\n new ProgressNotificationParams\n {\n ProgressToken = progressToken,\n Progress = progress,\n },\n McpJsonUtilities.JsonContext.Default.ProgressNotificationParams,\n cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrimitiveCollection.cs", "using System.Collections;\nusing System.Collections.Concurrent;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their names.\n/// Specifies the type of primitive stored in the collection.\npublic class McpServerPrimitiveCollection : ICollection, IReadOnlyCollection\n where T : IMcpServerPrimitive\n{\n /// Concurrent dictionary of primitives, indexed by their names.\n private readonly ConcurrentDictionary _primitives;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPrimitiveCollection(IEqualityComparer? keyComparer = null)\n {\n _primitives = new(keyComparer ?? EqualityComparer.Default);\n }\n\n /// Occurs when the collection is changed.\n /// \n /// By default, this is raised when a primitive is added or removed. However, a derived implementation\n /// may raise this event for other reasons, such as when a primitive is modified.\n /// \n public event EventHandler? Changed;\n\n /// Gets the number of primitives in the collection.\n public int Count => _primitives.Count;\n\n /// Gets whether there are any primitives in the collection.\n public bool IsEmpty => _primitives.IsEmpty;\n\n /// Raises if there are registered handlers.\n protected void RaiseChanged() => Changed?.Invoke(this, EventArgs.Empty);\n\n /// Gets the with the specified from the collection.\n /// The name of the primitive to retrieve.\n /// The with the specified name.\n /// is .\n /// An primitive with the specified name does not exist in the collection.\n public T this[string name]\n {\n get\n {\n Throw.IfNull(name);\n return _primitives[name];\n }\n }\n\n /// Clears all primitives from the collection.\n public virtual void Clear()\n {\n _primitives.Clear();\n RaiseChanged();\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// is .\n /// A primitive with the same name as already exists in the collection.\n public void Add(T primitive)\n {\n if (!TryAdd(primitive))\n {\n throw new ArgumentException($\"A primitive with the same name '{primitive.Id}' already exists in the collection.\", nameof(primitive));\n }\n }\n\n /// Adds the specified to the collection.\n /// The primitive to be added.\n /// if the primitive was added; otherwise, .\n /// is .\n public virtual bool TryAdd(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool added = _primitives.TryAdd(primitive.Id, primitive);\n if (added)\n {\n RaiseChanged();\n }\n\n return added;\n }\n\n /// Removes the specified primitivefrom the collection.\n /// The primitive to be removed from the collection.\n /// \n /// if the primitive was found in the collection and removed; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool Remove(T primitive)\n {\n Throw.IfNull(primitive);\n\n bool removed = ((ICollection>)_primitives).Remove(new(primitive.Id, primitive));\n if (removed)\n {\n RaiseChanged();\n }\n\n return removed;\n }\n\n /// Attempts to get the primitive with the specified name from the collection.\n /// The name of the primitive to retrieve.\n /// The primitive, if found; otherwise, .\n /// \n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// \n /// is .\n public virtual bool TryGetPrimitive(string name, [NotNullWhen(true)] out T? primitive)\n {\n Throw.IfNull(name);\n return _primitives.TryGetValue(name, out primitive);\n }\n\n /// Checks if a specific primitive is present in the collection of primitives.\n /// The primitive to search for in the collection.\n /// if the primitive was found in the collection and return; otherwise, if it couldn't be found.\n /// is .\n public virtual bool Contains(T primitive)\n {\n Throw.IfNull(primitive);\n return ((ICollection>)_primitives).Contains(new(primitive.Id, primitive));\n }\n\n /// Gets the names of all of the primitives in the collection.\n public virtual ICollection PrimitiveNames => _primitives.Keys;\n\n /// Creates an array containing all of the primitives in the collection.\n /// An array containing all of the primitives in the collection.\n public virtual T[] ToArray() => _primitives.Values.ToArray();\n\n /// \n public virtual void CopyTo(T[] array, int arrayIndex)\n {\n Throw.IfNull(array);\n\n _primitives.Values.CopyTo(array, arrayIndex);\n }\n\n /// \n public virtual IEnumerator GetEnumerator()\n {\n foreach (var entry in _primitives)\n {\n yield return entry.Value;\n }\n }\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n /// \n bool ICollection.IsReadOnly => false;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthenticatingMcpHttpClient.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Net.Http.Headers;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// A delegating handler that adds authentication tokens to requests and handles 401 responses.\n/// \ninternal sealed class AuthenticatingMcpHttpClient(HttpClient httpClient, ClientOAuthProvider credentialProvider) : McpHttpClient(httpClient)\n{\n // Select first supported scheme as the default\n private string _currentScheme = credentialProvider.SupportedSchemes.FirstOrDefault() ??\n throw new ArgumentException(\"Authorization provider must support at least one authentication scheme.\", nameof(credentialProvider));\n\n /// \n /// Sends an HTTP request with authentication handling.\n /// \n internal override async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (request.Headers.Authorization == null)\n {\n await AddAuthorizationHeaderAsync(request, _currentScheme, cancellationToken).ConfigureAwait(false);\n }\n\n var response = await base.SendAsync(request, message, cancellationToken).ConfigureAwait(false);\n\n if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)\n {\n return await HandleUnauthorizedResponseAsync(request, message, response, cancellationToken).ConfigureAwait(false);\n }\n\n return response;\n }\n\n /// \n /// Handles a 401 Unauthorized response by attempting to authenticate and retry the request.\n /// \n private async Task HandleUnauthorizedResponseAsync(\n HttpRequestMessage originalRequest,\n JsonRpcMessage? originalJsonRpcMessage,\n HttpResponseMessage response,\n CancellationToken cancellationToken)\n {\n // Gather the schemes the server wants us to use from WWW-Authenticate headers\n var serverSchemes = ExtractServerSupportedSchemes(response);\n\n if (!serverSchemes.Contains(_currentScheme))\n {\n // Find the first server scheme that's in our supported set\n var bestSchemeMatch = serverSchemes.Intersect(credentialProvider.SupportedSchemes, StringComparer.OrdinalIgnoreCase).FirstOrDefault();\n\n if (bestSchemeMatch is not null)\n {\n _currentScheme = bestSchemeMatch;\n }\n else if (serverSchemes.Count > 0)\n {\n // If no match was found, either throw an exception or use default\n throw new McpException(\n $\"The server does not support any of the provided authentication schemes.\" +\n $\"Server supports: [{string.Join(\", \", serverSchemes)}], \" +\n $\"Provider supports: [{string.Join(\", \", credentialProvider.SupportedSchemes)}].\");\n }\n }\n\n // Try to handle the 401 response with the selected scheme\n await credentialProvider.HandleUnauthorizedResponseAsync(_currentScheme, response, cancellationToken).ConfigureAwait(false);\n\n using var retryRequest = new HttpRequestMessage(originalRequest.Method, originalRequest.RequestUri);\n\n // Copy headers except Authorization which we'll set separately\n foreach (var header in originalRequest.Headers)\n {\n if (!header.Key.Equals(\"Authorization\", StringComparison.OrdinalIgnoreCase))\n {\n retryRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);\n }\n }\n\n await AddAuthorizationHeaderAsync(retryRequest, _currentScheme, cancellationToken).ConfigureAwait(false);\n return await base.SendAsync(retryRequest, originalJsonRpcMessage, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Extracts the authentication schemes that the server supports from the WWW-Authenticate headers.\n /// \n private static HashSet ExtractServerSupportedSchemes(HttpResponseMessage response)\n {\n var serverSchemes = new HashSet(StringComparer.OrdinalIgnoreCase);\n\n foreach (var header in response.Headers.WwwAuthenticate)\n {\n serverSchemes.Add(header.Scheme);\n }\n\n return serverSchemes;\n }\n\n /// \n /// Adds an authorization header to the request.\n /// \n private async Task AddAuthorizationHeaderAsync(HttpRequestMessage request, string scheme, CancellationToken cancellationToken)\n {\n if (request.RequestUri is null)\n {\n return;\n }\n\n var token = await credentialProvider.GetCredentialAsync(scheme, request.RequestUri, cancellationToken).ConfigureAwait(false);\n if (string.IsNullOrEmpty(token))\n {\n return;\n }\n\n request.Headers.Authorization = new AuthenticationHeaderValue(scheme, token);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/RequestHandlers.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\ninternal sealed class RequestHandlers : Dictionary>>\n{\n /// \n /// Registers a handler for incoming requests of a specific method in the MCP protocol.\n /// \n /// Type of request payload that will be deserialized from incoming JSON\n /// Type of response payload that will be serialized to JSON (not full RPC response)\n /// Method identifier to register for (e.g., \"tools/list\", \"logging/setLevel\")\n /// Handler function to be called when a request with the specified method identifier is received\n /// The JSON contract governing request parameter deserialization\n /// The JSON contract governing response serialization\n /// \n /// \n /// This method is used internally by the MCP infrastructure to register handlers for various protocol methods.\n /// When an incoming request matches the specified method, the registered handler will be invoked with the\n /// deserialized request parameters.\n /// \n /// \n /// The handler function receives the deserialized request object and a cancellation token, and should return\n /// a response object that will be serialized back to the client.\n /// \n /// \n public void Set(\n string method,\n Func> handler,\n JsonTypeInfo requestTypeInfo,\n JsonTypeInfo responseTypeInfo)\n {\n Throw.IfNull(method);\n Throw.IfNull(handler);\n Throw.IfNull(requestTypeInfo);\n Throw.IfNull(responseTypeInfo);\n\n this[method] = async (request, cancellationToken) =>\n {\n TRequest? typedRequest = JsonSerializer.Deserialize(request.Params, requestTypeInfo);\n object? result = await handler(typedRequest, request.RelatedTransport, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToNode(result, responseTypeInfo);\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamableHttpPostTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.IO.Pipelines;\nusing System.Net.ServerSentEvents;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Handles processing the request/response body pairs for the Streamable HTTP transport.\n/// This is typically used via .\n/// \ninternal sealed class StreamableHttpPostTransport(StreamableHttpServerTransport parentTransport, IDuplexPipe httpBodies) : ITransport\n{\n private readonly SseWriter _sseWriter = new();\n private RequestId _pendingRequest;\n\n public ChannelReader MessageReader => throw new NotSupportedException(\"JsonRpcMessage.RelatedTransport should only be used for sending messages.\");\n\n string? ITransport.SessionId => parentTransport.SessionId;\n\n /// \n /// True, if data was written to the respond body.\n /// False, if nothing was written because the request body did not contain any messages to respond to.\n /// The HTTP application should typically respond with an empty \"202 Accepted\" response in this scenario.\n /// \n public async ValueTask RunAsync(CancellationToken cancellationToken)\n {\n var message = await JsonSerializer.DeserializeAsync(httpBodies.Input.AsStream(),\n McpJsonUtilities.JsonContext.Default.JsonRpcMessage, cancellationToken).ConfigureAwait(false);\n await OnMessageReceivedAsync(message, cancellationToken).ConfigureAwait(false);\n\n if (_pendingRequest.Id is null)\n {\n return false;\n }\n\n _sseWriter.MessageFilter = StopOnFinalResponseFilter;\n await _sseWriter.WriteAllAsync(httpBodies.Output.AsStream(), cancellationToken).ConfigureAwait(false);\n return true;\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (parentTransport.Stateless && message is JsonRpcRequest)\n {\n throw new InvalidOperationException(\"Server to client requests are not supported in stateless mode.\");\n }\n\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n public async ValueTask DisposeAsync()\n {\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n private async IAsyncEnumerable> StopOnFinalResponseFilter(IAsyncEnumerable> messages, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n await foreach (var message in messages.WithCancellation(cancellationToken))\n {\n yield return message;\n\n if (message.Data is JsonRpcResponse or JsonRpcError && ((JsonRpcMessageWithId)message.Data).Id == _pendingRequest)\n {\n // Complete the SSE response stream now that all pending requests have been processed.\n break;\n }\n }\n }\n\n private async ValueTask OnMessageReceivedAsync(JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n if (message is null)\n {\n throw new InvalidOperationException(\"Received invalid null message.\");\n }\n\n if (message is JsonRpcRequest request)\n {\n _pendingRequest = request.Id;\n\n // Invoke the initialize request callback if applicable.\n if (parentTransport.OnInitRequestReceived is { } onInitRequest && request.Method == RequestMethods.Initialize)\n {\n var initializeRequest = JsonSerializer.Deserialize(request.Params, McpJsonUtilities.JsonContext.Default.InitializeRequestParams);\n await onInitRequest(initializeRequest).ConfigureAwait(false);\n }\n }\n\n message.RelatedTransport = this;\n\n if (parentTransport.FlowExecutionContextFromRequests)\n {\n message.ExecutionContext = ExecutionContext.Capture();\n }\n\n await parentTransport.MessageWriter.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that's implemented via an .\ninternal sealed class AIFunctionMcpServerPrompt : McpServerPrompt\n{\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method.Method, options);\n\n return Create(method.Method, method.Target, options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n object? target,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n public static new AIFunctionMcpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(method);\n Throw.IfNull(createTargetFunc);\n\n options = DeriveOptions(method, options);\n\n return Create(\n AIFunctionFactory.Create(method, args =>\n {\n Debug.Assert(args.Services is RequestServiceProvider, $\"The service provider should be a {nameof(RequestServiceProvider)} for this method to work correctly.\");\n return createTargetFunc(((RequestServiceProvider)args.Services!).Request);\n }, CreateAIFunctionFactoryOptions(method, options)),\n options);\n }\n\n private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(\n MethodInfo method, McpServerPromptCreateOptions? options) =>\n new()\n {\n Name = options?.Name ?? method.GetCustomAttribute()?.Name ?? AIFunctionMcpServerTool.DeriveName(method),\n Description = options?.Description,\n MarshalResult = static (result, _, cancellationToken) => new ValueTask(result),\n SerializerOptions = options?.SerializerOptions ?? McpJsonUtilities.DefaultOptions,\n JsonSchemaCreateOptions = options?.SchemaCreateOptions,\n ConfigureParameterBinding = pi =>\n {\n if (RequestServiceProvider.IsAugmentedWith(pi.ParameterType) ||\n (options?.Services?.GetService() is { } ispis &&\n ispis.IsService(pi.ParameterType)))\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n args.Services?.GetService(pi.ParameterType) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n if (pi.GetCustomAttribute() is { } keyedAttr)\n {\n return new()\n {\n ExcludeFromSchema = true,\n BindParameter = (pi, args) =>\n (args?.Services as IKeyedServiceProvider)?.GetKeyedService(pi.ParameterType, keyedAttr.Key) ??\n (pi.HasDefaultValue ? null :\n throw new ArgumentException(\"No service of the requested type was found.\")),\n };\n }\n\n return default;\n },\n };\n\n /// Creates an that wraps the specified .\n public static new AIFunctionMcpServerPrompt Create(AIFunction function, McpServerPromptCreateOptions? options)\n {\n Throw.IfNull(function);\n\n List args = [];\n HashSet? requiredProps = function.JsonSchema.TryGetProperty(\"required\", out JsonElement required)\n ? new(required.EnumerateArray().Select(p => p.GetString()!), StringComparer.Ordinal)\n : null;\n\n if (function.JsonSchema.TryGetProperty(\"properties\", out JsonElement properties))\n {\n foreach (var param in properties.EnumerateObject())\n {\n args.Add(new()\n {\n Name = param.Name,\n Description = param.Value.TryGetProperty(\"description\", out JsonElement description) ? description.GetString() : null,\n Required = requiredProps?.Contains(param.Name) ?? false,\n });\n }\n }\n\n Prompt prompt = new()\n {\n Name = options?.Name ?? function.Name,\n Title = options?.Title,\n Description = options?.Description ?? function.Description,\n Arguments = args,\n };\n\n return new AIFunctionMcpServerPrompt(function, prompt);\n }\n\n private static McpServerPromptCreateOptions DeriveOptions(MethodInfo method, McpServerPromptCreateOptions? options)\n {\n McpServerPromptCreateOptions newOptions = options?.Clone() ?? new();\n\n if (method.GetCustomAttribute() is { } promptAttr)\n {\n newOptions.Name ??= promptAttr.Name;\n newOptions.Title ??= promptAttr.Title;\n }\n\n if (method.GetCustomAttribute() is { } descAttr)\n {\n newOptions.Description ??= descAttr.Description;\n }\n\n return newOptions;\n }\n\n /// Gets the wrapped by this prompt.\n internal AIFunction AIFunction { get; }\n\n /// Initializes a new instance of the class.\n private AIFunctionMcpServerPrompt(AIFunction function, Prompt prompt)\n {\n AIFunction = function;\n ProtocolPrompt = prompt;\n }\n\n /// \n public override Prompt ProtocolPrompt { get; }\n\n /// \n public override async ValueTask GetAsync(\n RequestContext request, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(request);\n cancellationToken.ThrowIfCancellationRequested();\n\n request.Services = new RequestServiceProvider(request, request.Services);\n AIFunctionArguments arguments = new() { Services = request.Services };\n\n if (request.Params?.Arguments is { } argDict)\n {\n foreach (var kvp in argDict)\n {\n arguments[kvp.Key] = kvp.Value;\n }\n }\n\n object? result = await AIFunction.InvokeAsync(arguments, cancellationToken).ConfigureAwait(false);\n\n return result switch\n {\n GetPromptResult getPromptResult => getPromptResult,\n\n string text => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [new() { Role = Role.User, Content = new TextContentBlock { Text = text } }],\n },\n\n PromptMessage promptMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [promptMessage],\n },\n\n IEnumerable promptMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. promptMessages],\n },\n\n ChatMessage chatMessage => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessage.ToPromptMessages()],\n },\n\n IEnumerable chatMessages => new()\n {\n Description = ProtocolPrompt.Description,\n Messages = [.. chatMessages.SelectMany(chatMessage => chatMessage.ToPromptMessages())],\n },\n\n null => throw new InvalidOperationException(\"Null result returned from prompt function.\"),\n\n _ => throw new InvalidOperationException($\"Unknown result type '{result.GetType()}' returned from prompt function.\"),\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.Collections.ObjectModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides an that calls a tool via an .\n/// \n/// \n/// \n/// The class encapsulates an along with a description of \n/// a tool available via that client, allowing it to be invoked as an . This enables integration\n/// with AI models that support function calling capabilities.\n/// \n/// \n/// Tools retrieved from an MCP server can be customized for model presentation using methods like\n/// and without changing the underlying tool functionality.\n/// \n/// \n/// Typically, you would get instances of this class by calling the \n/// or extension methods on an instance.\n/// \n/// \npublic sealed class McpClientTool : AIFunction\n{\n /// Additional properties exposed from tools.\n private static readonly ReadOnlyDictionary s_additionalProperties =\n new(new Dictionary()\n {\n [\"Strict\"] = false, // some MCP schemas may not meet \"strict\" requirements\n });\n\n private readonly IMcpClient _client;\n private readonly string _name;\n private readonly string _description;\n private readonly IProgress? _progress;\n\n internal McpClientTool(\n IMcpClient client,\n Tool tool,\n JsonSerializerOptions serializerOptions,\n string? name = null,\n string? description = null,\n IProgress? progress = null)\n {\n _client = client;\n ProtocolTool = tool;\n JsonSerializerOptions = serializerOptions;\n _name = name ?? tool.Name;\n _description = description ?? tool.Description ?? string.Empty;\n _progress = progress;\n }\n\n /// \n /// Gets the protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the tool,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// It contains the original metadata about the tool as provided by the server, including its\n /// name, description, and schema information before any customizations applied through methods\n /// like or .\n /// \n public Tool ProtocolTool { get; }\n\n /// \n public override string Name => _name;\n\n /// Gets the tool's title.\n public string? Title => ProtocolTool.Title ?? ProtocolTool.Annotations?.Title;\n\n /// \n public override string Description => _description;\n\n /// \n public override JsonElement JsonSchema => ProtocolTool.InputSchema;\n\n /// \n public override JsonElement? ReturnJsonSchema => ProtocolTool.OutputSchema;\n\n /// \n public override JsonSerializerOptions JsonSerializerOptions { get; }\n\n /// \n public override IReadOnlyDictionary AdditionalProperties => s_additionalProperties;\n\n /// \n protected async override ValueTask InvokeCoreAsync(\n AIFunctionArguments arguments, CancellationToken cancellationToken)\n {\n CallToolResult result = await CallAsync(arguments, _progress, JsonSerializerOptions, cancellationToken).ConfigureAwait(false);\n return JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult);\n }\n\n /// \n /// Invokes the tool on the server.\n /// \n /// An optional dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// \n /// An optional to have progress notifications reported to it. Setting this to a non-\n /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation\n /// routed to this instance.\n /// \n /// \n /// The JSON serialization options governing argument serialization. If , the default serialization options will be used.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// A task containing the from the tool execution. The response includes\n /// the tool's output content, which may be structured data, text, or an error message.\n /// \n /// \n /// The base method is overridden to invoke this method.\n /// The only difference in behavior is will serialize the resulting \"/>\n /// such that the returned is a containing the serialized .\n /// This method is intended to be called directly by user code, whereas the base \n /// is intended to be used polymorphically via the base class, typically as part of an operation.\n /// \n /// The server could not find the requested tool, or the server encountered an error while processing the request.\n /// \n /// \n /// var result = await tool.CallAsync(\n /// new Dictionary<string, object?>\n /// {\n /// [\"message\"] = \"Hello MCP!\"\n /// });\n /// \n /// \n public ValueTask CallAsync(\n IReadOnlyDictionary? arguments = null,\n IProgress? progress = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default) =>\n _client.CallToolAsync(ProtocolTool.Name, arguments, progress, serializerOptions, cancellationToken);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified name from its property.\n /// \n /// The model-facing name to give the tool.\n /// A new instance of with the provided name.\n /// \n /// \n /// This is useful for optimizing the tool name for specific models or for prefixing the tool name \n /// with a namespace to avoid conflicts.\n /// \n /// \n /// Changing the name can help with:\n /// \n /// \n /// Making the tool name more intuitive for the model\n /// Preventing name collisions when using tools from multiple sources\n /// Creating specialized versions of a general tool for specific contexts\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool name, so no mapping is required on the server side. This new name only affects\n /// the value returned from this instance's .\n /// \n /// \n public McpClientTool WithName(string name) =>\n new(_client, ProtocolTool, JsonSerializerOptions, name, _description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to return the specified description from its property.\n /// \n /// The description to give the tool.\n /// \n /// \n /// Changing the description can help the model better understand the tool's purpose or provide more\n /// context about how the tool should be used. This is particularly useful when:\n /// \n /// \n /// The original description is too technical or lacks clarity for the model\n /// You want to add example usage scenarios to improve the model's understanding\n /// You need to tailor the tool's description for specific model requirements\n /// \n /// \n /// When invoking , the MCP server will still be called with \n /// the original tool description, so no mapping is required on the server side. This new description only affects\n /// the value returned from this instance's .\n /// \n /// \n /// A new instance of with the provided description.\n public McpClientTool WithDescription(string description) =>\n new(_client, ProtocolTool, JsonSerializerOptions, _name, description, _progress);\n\n /// \n /// Creates a new instance of the tool but modified to report progress via the specified .\n /// \n /// The to which progress notifications should be reported.\n /// \n /// \n /// Adding an to the tool does not impact how it is reported to any AI model.\n /// Rather, when the tool is invoked, the request to the MCP server will include a unique progress token,\n /// and any progress notifications issued by the server with that progress token while the operation is in\n /// flight will be reported to the instance.\n /// \n /// \n /// Only one can be specified at a time. Calling again\n /// will overwrite any previously specified progress instance.\n /// \n /// \n /// A new instance of , configured with the provided progress instance.\n public McpClientTool WithProgress(IProgress progress)\n {\n Throw.IfNull(progress);\n\n return new McpClientTool(_client, ProtocolTool, JsonSerializerOptions, _name, _description, progress);\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/Server/SseResponseStreamTransport.cs", "using ModelContextProtocol.Protocol;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implementation using Server-Sent Events (SSE) for server-to-client communication.\n/// \n/// \n/// \n/// This transport provides one-way communication from server to client using the SSE protocol over HTTP,\n/// while receiving client messages through a separate mechanism. It writes messages as \n/// SSE events to a response stream, typically associated with an HTTP response.\n/// \n/// \n/// This transport is used in scenarios where the server needs to push messages to the client in real-time,\n/// such as when streaming completion results or providing progress updates during long-running operations.\n/// \n/// \n/// The response stream to write MCP JSON-RPC messages as SSE events to.\n/// \n/// The relative or absolute URI the client should use to post MCP JSON-RPC messages for this session.\n/// These messages should be passed to .\n/// Defaults to \"/message\".\n/// \n/// The identifier corresponding to the current MCP session.\npublic sealed class SseResponseStreamTransport(Stream sseResponseStream, string? messageEndpoint = \"/message\", string? sessionId = null) : ITransport\n{\n private readonly SseWriter _sseWriter = new(messageEndpoint);\n private readonly Channel _incomingChannel = Channel.CreateBounded(new BoundedChannelOptions(1)\n {\n SingleReader = true,\n SingleWriter = false,\n });\n\n private bool _isConnected;\n\n /// \n /// Starts the transport and writes the JSON-RPC messages sent via \n /// to the SSE response stream until cancellation is requested or the transport is disposed.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task representing the send loop that writes JSON-RPC messages to the SSE response stream.\n public async Task RunAsync(CancellationToken cancellationToken)\n {\n _isConnected = true;\n await _sseWriter.WriteAllAsync(sseResponseStream, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n public ChannelReader MessageReader => _incomingChannel.Reader;\n\n /// \n public string? SessionId { get; } = sessionId;\n\n /// \n public async ValueTask DisposeAsync()\n {\n _isConnected = false;\n _incomingChannel.Writer.TryComplete();\n await _sseWriter.DisposeAsync().ConfigureAwait(false);\n }\n\n /// \n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n await _sseWriter.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Handles incoming JSON-RPC messages received on the /message endpoint.\n /// \n /// The JSON-RPC message received from the client.\n /// The to monitor for cancellation requests. The default is .\n /// A task representing the asynchronous operation to buffer the JSON-RPC message for processing.\n /// Thrown when there is an attempt to process a message before calling .\n /// \n /// \n /// This method is the entry point for processing client-to-server communication in the SSE transport model. \n /// While the SSE protocol itself is unidirectional (server to client), this method allows bidirectional \n /// communication by handling HTTP POST requests sent to the message endpoint.\n /// \n /// \n /// When a client sends a JSON-RPC message to the /message endpoint, the server calls this method to\n /// process the message and make it available to the MCP server via the channel.\n /// \n /// \n /// This method validates that the transport is connected before processing the message, ensuring proper\n /// sequencing of operations in the transport lifecycle.\n /// \n /// \n public async Task OnMessageReceivedAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n Throw.IfNull(message);\n\n if (!_isConnected)\n {\n throw new InvalidOperationException($\"Transport is not connected. Make sure to call {nameof(RunAsync)} first.\");\n }\n\n await _incomingChannel.Writer.WriteAsync(message, cancellationToken).ConfigureAwait(false);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/IMcpEndpoint.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Represents a client or server Model Context Protocol (MCP) endpoint.\n/// \n/// \n/// \n/// The MCP endpoint provides the core communication functionality used by both clients and servers:\n/// \n/// Sending JSON-RPC requests and receiving responses.\n/// Sending notifications to the connected endpoint.\n/// Registering handlers for receiving notifications.\n/// \n/// \n/// \n/// serves as the base interface for both and \n/// interfaces, providing the common functionality needed for MCP protocol \n/// communication. Most applications will use these more specific interfaces rather than working with \n/// directly.\n/// \n/// \n/// All MCP endpoints should be properly disposed after use as they implement .\n/// \n/// \npublic interface IMcpEndpoint : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Sends a JSON-RPC request to the connected endpoint and waits for a response.\n /// \n /// The JSON-RPC request to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the endpoint's response.\n /// The transport is not connected, or another error occurs during request processing.\n /// An error occured during request processing.\n /// \n /// This method provides low-level access to send raw JSON-RPC requests. For most use cases,\n /// consider using the strongly-typed extension methods that provide a more convenient API.\n /// \n Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default);\n\n /// \n /// Sends a JSON-RPC message to the connected endpoint.\n /// \n /// \n /// The JSON-RPC message to send. This can be any type that implements JsonRpcMessage, such as\n /// JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, or JsonRpcError.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// is .\n /// \n /// \n /// This method provides low-level access to send any JSON-RPC message. For specific message types,\n /// consider using the higher-level methods such as or extension methods\n /// like ,\n /// which provide a simpler API.\n /// \n /// \n /// The method will serialize the message and transmit it using the underlying transport mechanism.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n\n /// Registers a handler to be invoked when a notification for the specified method is received.\n /// The notification method.\n /// The handler to be invoked.\n /// An that will remove the registered handler when disposed.\n IAsyncDisposable RegisterNotificationHandler(string method, Func handler);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ProgressToken.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a progress token, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct ProgressToken : IEquatable\n{\n /// The token, either a string or a boxed long or null.\n private readonly object? _token;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(string value)\n {\n Throw.IfNull(value);\n _token = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public ProgressToken(long value)\n {\n // Box the long. Progress tokens are almost always strings in practice, so this should be rare.\n _token = value;\n }\n\n /// Gets the underlying object for this token.\n /// This will either be a , a boxed , or .\n public object? Token => _token;\n\n /// \n public override string? ToString() =>\n _token is string stringValue ? stringValue :\n _token is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n null;\n\n /// \n public bool Equals(ProgressToken other) => Equals(_token, other._token);\n\n /// \n public override bool Equals(object? obj) => obj is ProgressToken other && Equals(other);\n\n /// \n public override int GetHashCode() => _token?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(ProgressToken left, ProgressToken right) => left.Equals(right);\n\n /// \n public static bool operator !=(ProgressToken left, ProgressToken right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressToken Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"progressToken must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressToken value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._token)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\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/Protocol/Reference.cs", "using ModelContextProtocol.Client;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a reference to a resource or prompt in the Model Context Protocol.\n/// \n/// \n/// \n/// References are commonly used with to request completion suggestions for arguments,\n/// and with other methods that need to reference resources or prompts.\n/// \n/// \n/// See the schema for details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class Reference\n{\n /// Prevent external derivations.\n private protected Reference() \n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This can be \"ref/resource\" or \"ref/prompt\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override Reference? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? name = null;\n string? title = null;\n string? uri = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n default:\n break;\n }\n }\n\n // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n\n switch (type)\n {\n case \"ref/prompt\":\n if (name is null)\n {\n throw new JsonException(\"Prompt references must have a 'name' property.\");\n }\n\n return new PromptReference { Name = name, Title = title };\n\n case \"ref/resource\":\n if (uri is null)\n {\n throw new JsonException(\"Resource references must have a 'uri' property.\");\n }\n\n return new ResourceTemplateReference { Uri = uri };\n\n default:\n throw new JsonException($\"Unknown content type: '{type}'\");\n }\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, Reference value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case PromptReference pr:\n writer.WriteString(\"name\", pr.Name);\n if (pr.Title is not null)\n {\n writer.WriteString(\"title\", pr.Title);\n }\n break;\n\n case ResourceTemplateReference rtr:\n writer.WriteString(\"uri\", rtr.Uri);\n break;\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// \n/// Represents a reference to a prompt, identified by its name.\n/// \npublic sealed class PromptReference : Reference, IBaseMetadata\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public PromptReference() => Type = \"ref/prompt\";\n\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Name}\\\"\";\n}\n\n/// \n/// Represents a reference to a resource or resource template definition.\n/// \npublic sealed class ResourceTemplateReference : Reference\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public ResourceTemplateReference() => Type = \"ref/resource\";\n\n /// \n /// Gets or sets the URI or URI template of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public required string? Uri { get; set; }\n\n /// \n public override string ToString() => $\"\\\"{Type}\\\": \\\"{Uri}\\\"\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestId.cs", "using System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC request identifier, which can be either a string or an integer.\n/// \n[JsonConverter(typeof(Converter))]\npublic readonly struct RequestId : IEquatable\n{\n /// The id, either a string or a boxed long or null.\n private readonly object? _id;\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(string value)\n {\n Throw.IfNull(value);\n _id = value;\n }\n\n /// Initializes a new instance of the with a specified value.\n /// The required ID value.\n public RequestId(long value)\n {\n // Box the long. Request IDs are almost always strings in practice, so this should be rare.\n _id = value;\n }\n\n /// Gets the underlying object for this id.\n /// This will either be a , a boxed , or .\n public object? Id => _id;\n\n /// \n public override string ToString() =>\n _id is string stringValue ? stringValue :\n _id is long longValue ? longValue.ToString(CultureInfo.InvariantCulture) :\n string.Empty;\n\n /// \n public bool Equals(RequestId other) => Equals(_id, other._id);\n\n /// \n public override bool Equals(object? obj) => obj is RequestId other && Equals(other);\n\n /// \n public override int GetHashCode() => _id?.GetHashCode() ?? 0;\n\n /// \n public static bool operator ==(RequestId left, RequestId right) => left.Equals(right);\n\n /// \n public static bool operator !=(RequestId left, RequestId right) => !left.Equals(right);\n\n /// \n /// Provides a for that handles both string and number values.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override RequestId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n return reader.TokenType switch\n {\n JsonTokenType.String => new(reader.GetString()!),\n JsonTokenType.Number => new(reader.GetInt64()),\n _ => throw new JsonException(\"requestId must be a string or an integer\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, RequestId value, JsonSerializerOptions options)\n {\n Throw.IfNull(writer);\n\n switch (value._id)\n {\n case string str:\n writer.WriteStringValue(str);\n return;\n\n case long longValue:\n writer.WriteNumberValue(longValue);\n return;\n\n case null:\n writer.WriteStringValue(string.Empty);\n return;\n }\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationHandler.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Authentication;\nusing System.Text.Encodings.Web;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Authentication handler for MCP protocol that adds resource metadata to challenge responses\n/// and handles resource metadata endpoint requests.\n/// \npublic class McpAuthenticationHandler : AuthenticationHandler, IAuthenticationRequestHandler\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationHandler(\n IOptionsMonitor options,\n ILoggerFactory logger,\n UrlEncoder encoder)\n : base(options, logger, encoder)\n {\n }\n\n /// \n public async Task HandleRequestAsync()\n {\n // Check if the request is for the resource metadata endpoint\n string requestPath = Request.Path.Value ?? string.Empty;\n\n string expectedMetadataPath = Options.ResourceMetadataUri?.ToString() ?? string.Empty;\n if (Options.ResourceMetadataUri != null && !Options.ResourceMetadataUri.IsAbsoluteUri)\n {\n // For relative URIs, it's just the path component.\n expectedMetadataPath = Options.ResourceMetadataUri.OriginalString;\n }\n\n // If the path doesn't match, let the request continue through the pipeline\n if (!string.Equals(requestPath, expectedMetadataPath, StringComparison.OrdinalIgnoreCase))\n {\n return false;\n }\n\n return await HandleResourceMetadataRequestAsync();\n }\n\n /// \n /// Gets the base URL from the current request, including scheme, host, and path base.\n /// \n private string GetBaseUrl() => $\"{Request.Scheme}://{Request.Host}{Request.PathBase}\";\n\n /// \n /// Gets the absolute URI for the resource metadata endpoint.\n /// \n private string GetAbsoluteResourceMetadataUri()\n {\n var resourceMetadataUri = Options.ResourceMetadataUri;\n\n string currentPath = resourceMetadataUri?.ToString() ?? string.Empty;\n\n if (resourceMetadataUri != null && resourceMetadataUri.IsAbsoluteUri)\n {\n return currentPath;\n }\n\n // For relative URIs, combine with the base URL\n string baseUrl = GetBaseUrl();\n string relativePath = resourceMetadataUri?.OriginalString.TrimStart('/') ?? string.Empty;\n\n if (!Uri.TryCreate($\"{baseUrl.TrimEnd('/')}/{relativePath}\", UriKind.Absolute, out var absoluteUri))\n {\n throw new InvalidOperationException($\"Could not create absolute URI for resource metadata. Base URL: {baseUrl}, Relative Path: {relativePath}\");\n }\n\n return absoluteUri.ToString();\n }\n\n private async Task HandleResourceMetadataRequestAsync()\n {\n var resourceMetadata = Options.ResourceMetadata;\n\n if (Options.Events.OnResourceMetadataRequest is not null)\n {\n var context = new ResourceMetadataRequestContext(Request.HttpContext, Scheme, Options)\n {\n ResourceMetadata = CloneResourceMetadata(resourceMetadata),\n };\n\n await Options.Events.OnResourceMetadataRequest(context);\n\n if (context.Result is not null)\n {\n if (context.Result.Handled)\n {\n return true;\n }\n else if (context.Result.Skipped)\n {\n return false;\n }\n else if (context.Result.Failure is not null)\n {\n throw new AuthenticationFailureException(\"An error occurred from the OnResourceMetadataRequest event.\", context.Result.Failure);\n }\n }\n\n resourceMetadata = context.ResourceMetadata;\n }\n\n if (resourceMetadata == null)\n {\n throw new InvalidOperationException(\n \"ResourceMetadata has not been configured. Please set McpAuthenticationOptions.ResourceMetadata or ensure context.ResourceMetadata is set inside McpAuthenticationOptions.Events.OnResourceMetadataRequest.\"\n );\n }\n\n await Results.Json(resourceMetadata, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ProtectedResourceMetadata))).ExecuteAsync(Context);\n return true;\n }\n\n /// \n // If no forwarding is configured, this handler doesn't perform authentication\n protected override async Task HandleAuthenticateAsync() => AuthenticateResult.NoResult();\n\n /// \n protected override Task HandleChallengeAsync(AuthenticationProperties properties)\n {\n // Get the absolute URI for the resource metadata\n string rawPrmDocumentUri = GetAbsoluteResourceMetadataUri();\n\n properties ??= new AuthenticationProperties();\n\n // Store the resource_metadata in properties in case other handlers need it\n properties.Items[\"resource_metadata\"] = rawPrmDocumentUri;\n\n // Add the WWW-Authenticate header with Bearer scheme and resource metadata\n string headerValue = $\"Bearer realm=\\\"{Scheme.Name}\\\", resource_metadata=\\\"{rawPrmDocumentUri}\\\"\";\n Response.Headers.Append(\"WWW-Authenticate\", headerValue);\n\n return base.HandleChallengeAsync(properties);\n }\n\n internal static ProtectedResourceMetadata? CloneResourceMetadata(ProtectedResourceMetadata? resourceMetadata)\n {\n if (resourceMetadata is null)\n {\n return null;\n }\n\n return new ProtectedResourceMetadata\n {\n Resource = resourceMetadata.Resource,\n AuthorizationServers = [.. resourceMetadata.AuthorizationServers],\n BearerMethodsSupported = [.. resourceMetadata.BearerMethodsSupported],\n ScopesSupported = [.. resourceMetadata.ScopesSupported],\n JwksUri = resourceMetadata.JwksUri,\n ResourceSigningAlgValuesSupported = resourceMetadata.ResourceSigningAlgValuesSupported is not null ? [.. resourceMetadata.ResourceSigningAlgValuesSupported] : null,\n ResourceName = resourceMetadata.ResourceName,\n ResourceDocumentation = resourceMetadata.ResourceDocumentation,\n ResourcePolicyUri = resourceMetadata.ResourcePolicyUri,\n ResourceTosUri = resourceMetadata.ResourceTosUri,\n TlsClientCertificateBoundAccessTokens = resourceMetadata.TlsClientCertificateBoundAccessTokens,\n AuthorizationDetailsTypesSupported = resourceMetadata.AuthorizationDetailsTypesSupported is not null ? [.. resourceMetadata.AuthorizationDetailsTypesSupported] : null,\n DpopSigningAlgValuesSupported = resourceMetadata.DpopSigningAlgValuesSupported is not null ? [.. resourceMetadata.DpopSigningAlgValuesSupported] : null,\n DpopBoundAccessTokensRequired = resourceMetadata.DpopBoundAccessTokensRequired\n };\n }\n\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerHandlers.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a container for handlers used in the creation of an MCP server.\n/// \n/// \n/// \n/// This class provides a centralized collection of delegates that implement various capabilities of the Model Context Protocol.\n/// Each handler in this class corresponds to a specific endpoint in the Model Context Protocol and\n/// is responsible for processing a particular type of request. The handlers are used to customize\n/// the behavior of the MCP server by providing implementations for the various protocol operations.\n/// \n/// \n/// Handlers can be configured individually using the extension methods in \n/// such as and\n/// .\n/// \n/// \n/// When a client sends a request to the server, the appropriate handler is invoked to process the\n/// request and produce a response according to the protocol specification. Which handler is selected\n/// is done based on an ordinal, case-sensitive string comparison.\n/// \n/// \npublic sealed class McpServerHandlers\n{\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// \n /// \n /// This handler works alongside any tools defined in the collection.\n /// Tools from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the collection.\n /// The handler should implement logic to execute the requested tool and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// The handler should return a list of available prompts when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more prompts.\n /// \n /// \n /// This handler works alongside any prompts defined in the collection.\n /// Prompts from both sources will be combined when returning results to clients.\n /// \n /// \n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt that isn't found in the collection.\n /// The handler should implement logic to fetch or generate the requested prompt and return appropriate results.\n /// \n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resource templates when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resource templates.\n /// \n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available resources when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more resources.\n /// \n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests the content of a specific resource identified by its URI.\n /// The handler should implement logic to locate and retrieve the requested resource.\n /// \n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler processes auto-completion requests, returning a list of suggestions based on the \n /// reference type and current argument value.\n /// \n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to receive notifications about changes to specific resources or resource patterns.\n /// The handler should implement logic to register the client's interest in the specified resources\n /// and set up the necessary infrastructure to send notifications when those resources change.\n /// \n /// \n /// After a successful subscription, the server should send resource change notifications to the client\n /// whenever a relevant resource is created, updated, or deleted.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client wants to stop receiving notifications about previously subscribed resources.\n /// The handler should implement logic to remove the client's subscriptions to the specified resources\n /// and clean up any associated resources.\n /// \n /// \n /// After a successful unsubscription, the server should no longer send resource change notifications\n /// to the client for the specified resources.\n /// \n /// \n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler processes requests from clients. When set, it enables\n /// clients to control which log messages they receive by specifying a minimum severity threshold.\n /// \n /// \n /// After handling a level change request, the server typically begins sending log messages\n /// at or above the specified level to the client as notifications/message notifications.\n /// \n /// \n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n\n /// \n /// Overwrite any handlers in McpServerOptions with non-null handlers from this instance.\n /// \n /// \n /// \n internal void OverwriteWithSetHandlers(McpServerOptions options)\n {\n PromptsCapability? promptsCapability = options.Capabilities?.Prompts;\n if (ListPromptsHandler is not null || GetPromptHandler is not null)\n {\n promptsCapability ??= new();\n promptsCapability.ListPromptsHandler = ListPromptsHandler ?? promptsCapability.ListPromptsHandler;\n promptsCapability.GetPromptHandler = GetPromptHandler ?? promptsCapability.GetPromptHandler;\n }\n\n ResourcesCapability? resourcesCapability = options.Capabilities?.Resources;\n if (ListResourcesHandler is not null ||\n ReadResourceHandler is not null)\n {\n resourcesCapability ??= new();\n resourcesCapability.ListResourceTemplatesHandler = ListResourceTemplatesHandler ?? resourcesCapability.ListResourceTemplatesHandler;\n resourcesCapability.ListResourcesHandler = ListResourcesHandler ?? resourcesCapability.ListResourcesHandler;\n resourcesCapability.ReadResourceHandler = ReadResourceHandler ?? resourcesCapability.ReadResourceHandler;\n\n if (SubscribeToResourcesHandler is not null || UnsubscribeFromResourcesHandler is not null)\n {\n resourcesCapability.SubscribeToResourcesHandler = SubscribeToResourcesHandler ?? resourcesCapability.SubscribeToResourcesHandler;\n resourcesCapability.UnsubscribeFromResourcesHandler = UnsubscribeFromResourcesHandler ?? resourcesCapability.UnsubscribeFromResourcesHandler;\n resourcesCapability.Subscribe = true;\n }\n }\n\n ToolsCapability? toolsCapability = options.Capabilities?.Tools;\n if (ListToolsHandler is not null || CallToolHandler is not null)\n {\n toolsCapability ??= new();\n toolsCapability.ListToolsHandler = ListToolsHandler ?? toolsCapability.ListToolsHandler;\n toolsCapability.CallToolHandler = CallToolHandler ?? toolsCapability.CallToolHandler;\n }\n\n LoggingCapability? loggingCapability = options.Capabilities?.Logging;\n if (SetLoggingLevelHandler is not null)\n {\n loggingCapability ??= new();\n loggingCapability.SetLoggingLevelHandler = SetLoggingLevelHandler;\n }\n\n CompletionsCapability? completionsCapability = options.Capabilities?.Completions;\n if (CompleteHandler is not null)\n {\n completionsCapability ??= new();\n completionsCapability.CompleteHandler = CompleteHandler;\n }\n\n options.Capabilities ??= new();\n options.Capabilities.Prompts = promptsCapability;\n options.Capabilities.Resources = resourcesCapability;\n options.Capabilities.Tools = toolsCapability;\n options.Capabilities.Logging = loggingCapability;\n options.Capabilities.Completions = completionsCapability;\n }\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 posts.\n internal static UserIdClaim? GetUserIdClaim(ClaimsPrincipal user)\n {\n if (user?.Identity?.IsAuthenticated != true)\n {\n return null;\n }\n\n var claim = user.FindFirst(ClaimTypes.NameIdentifier) ?? user.FindFirst(\"sub\") ?? user.FindFirst(ClaimTypes.Upn);\n\n if (claim is { } idClaim)\n {\n return new(idClaim.Type, idClaim.Value, idClaim.Issuer);\n }\n\n return null;\n }\n\n private static JsonTypeInfo GetRequiredJsonTypeInfo() => (JsonTypeInfo)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));\n\n private static bool MatchesApplicationJsonMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"application/json\");\n\n private static bool MatchesTextEventStreamMediaType(MediaTypeHeaderValue acceptHeaderValue)\n => acceptHeaderValue.MatchesMediaType(\"text/event-stream\");\n\n private sealed class HttpDuplexPipe(HttpContext context) : IDuplexPipe\n {\n public PipeReader Input => context.Request.BodyReader;\n public PipeWriter Output => context.Response.BodyWriter;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ProgressNotificationParams.cs", "using Microsoft.Extensions.Logging.Abstractions;\nusing System.ComponentModel;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an out-of-band notification used to inform the receiver of a progress update for a long-running request.\n/// \n/// \n/// See the schema for more details.\n/// \n[JsonConverter(typeof(Converter))]\npublic sealed class ProgressNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the progress token which was given in the initial request, used to associate this notification with \n /// the corresponding request.\n /// \n /// \n /// \n /// This token acts as a correlation identifier that links progress updates to their corresponding request.\n /// \n /// \n /// When an endpoint initiates a request with a in its metadata, \n /// the receiver can send progress notifications using this same token. This allows both sides to \n /// correlate the notifications with the original request.\n /// \n /// \n public required ProgressToken ProgressToken { get; init; }\n\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// This should increase for each notification issued as part of the same request, even if the total is unknown.\n /// \n public required ProgressNotificationValue Progress { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class Converter : JsonConverter\n {\n /// \n public override ProgressNotificationParams? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n ProgressToken? progressToken = null;\n float? progress = null;\n float? total = null;\n string? message = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType == JsonTokenType.PropertyName)\n {\n var propertyName = reader.GetString();\n reader.Read();\n switch (propertyName)\n {\n case \"progressToken\":\n progressToken = (ProgressToken)JsonSerializer.Deserialize(ref reader, options.GetTypeInfo(typeof(ProgressToken)))!;\n break;\n\n case \"progress\":\n progress = reader.GetSingle();\n break;\n\n case \"total\":\n total = reader.GetSingle();\n break;\n\n case \"message\":\n message = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n }\n }\n }\n\n if (progress is null)\n {\n throw new JsonException(\"Missing required property 'progress'.\");\n }\n\n if (progressToken is null)\n {\n throw new JsonException(\"Missing required property 'progressToken'.\");\n }\n\n return new ProgressNotificationParams\n {\n ProgressToken = progressToken.GetValueOrDefault(),\n Progress = new ProgressNotificationValue\n {\n Progress = progress.GetValueOrDefault(),\n Total = total,\n Message = message,\n },\n Meta = meta,\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ProgressNotificationParams value, JsonSerializerOptions options)\n {\n writer.WriteStartObject();\n\n writer.WritePropertyName(\"progressToken\");\n JsonSerializer.Serialize(writer, value.ProgressToken, options.GetTypeInfo(typeof(ProgressToken)));\n\n writer.WriteNumber(\"progress\", value.Progress.Progress);\n\n if (value.Progress.Total is { } total)\n {\n writer.WriteNumber(\"total\", total);\n }\n\n if (value.Progress.Message is { } message)\n {\n writer.WriteString(\"message\", message);\n }\n\n if (value.Meta is { } meta)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitRequestParams.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued from the server to elicit additional information from the user via the client.\n/// \npublic sealed class ElicitRequestParams\n{\n /// \n /// Gets or sets the message to present to the user.\n /// \n [JsonPropertyName(\"message\")]\n public string Message { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the requested schema.\n /// \n /// \n /// May be one of , , , or .\n /// \n [JsonPropertyName(\"requestedSchema\")]\n [field: MaybeNull]\n public RequestSchema RequestedSchema\n {\n get => field ??= new RequestSchema();\n set => field = value;\n }\n\n /// Represents a request schema used in an elicitation request.\n public class RequestSchema\n {\n /// Gets the type of the schema.\n /// This is always \"object\".\n [JsonPropertyName(\"type\")]\n public string Type => \"object\";\n\n /// Gets or sets the properties of the schema.\n [JsonPropertyName(\"properties\")]\n [field: MaybeNull]\n public IDictionary Properties\n {\n get => field ??= new Dictionary();\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets the required properties of the schema.\n [JsonPropertyName(\"required\")]\n public IList? Required { get; set; }\n }\n\n /// \n /// Represents restricted subset of JSON Schema: \n /// , , , or .\n /// \n [JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\n public abstract class PrimitiveSchemaDefinition\n {\n /// Prevent external derivations.\n protected private PrimitiveSchemaDefinition()\n {\n }\n\n /// Gets the type of the schema.\n [JsonPropertyName(\"type\")]\n public abstract string Type { get; set; }\n\n /// Gets or sets a title for the schema.\n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// Gets or sets a description for the schema.\n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override PrimitiveSchemaDefinition? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? title = null;\n string? description = null;\n int? minLength = null;\n int? maxLength = null;\n string? format = null;\n double? minimum = null;\n double? maximum = null;\n bool? defaultBool = null;\n IList? enumValues = null;\n IList? enumNames = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"title\":\n title = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"minLength\":\n minLength = reader.GetInt32();\n break;\n\n case \"maxLength\":\n maxLength = reader.GetInt32();\n break;\n\n case \"format\":\n format = reader.GetString();\n break;\n\n case \"minimum\":\n minimum = reader.GetDouble();\n break;\n\n case \"maximum\":\n maximum = reader.GetDouble();\n break;\n\n case \"default\":\n defaultBool = reader.GetBoolean();\n break;\n\n case \"enum\":\n enumValues = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n case \"enumNames\":\n enumNames = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.IListString);\n break;\n\n default:\n break;\n }\n }\n\n if (type is null)\n {\n throw new JsonException(\"The 'type' property is required.\");\n }\n\n PrimitiveSchemaDefinition? psd = null;\n switch (type)\n {\n case \"string\":\n if (enumValues is not null)\n {\n psd = new EnumSchema\n {\n Enum = enumValues,\n EnumNames = enumNames\n };\n }\n else\n {\n psd = new StringSchema\n {\n MinLength = minLength,\n MaxLength = maxLength,\n Format = format,\n };\n }\n break;\n\n case \"integer\":\n case \"number\":\n psd = new NumberSchema\n {\n Minimum = minimum,\n Maximum = maximum,\n };\n break;\n\n case \"boolean\":\n psd = new BooleanSchema\n {\n Default = defaultBool,\n };\n break;\n }\n\n if (psd is not null)\n {\n psd.Type = type;\n psd.Title = title;\n psd.Description = description;\n }\n\n return psd;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, PrimitiveSchemaDefinition value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n if (value.Title is not null)\n {\n writer.WriteString(\"title\", value.Title);\n }\n if (value.Description is not null)\n {\n writer.WriteString(\"description\", value.Description);\n }\n\n switch (value)\n {\n case StringSchema stringSchema:\n if (stringSchema.MinLength.HasValue)\n {\n writer.WriteNumber(\"minLength\", stringSchema.MinLength.Value);\n }\n if (stringSchema.MaxLength.HasValue)\n {\n writer.WriteNumber(\"maxLength\", stringSchema.MaxLength.Value);\n }\n if (stringSchema.Format is not null)\n {\n writer.WriteString(\"format\", stringSchema.Format);\n }\n break;\n\n case NumberSchema numberSchema:\n if (numberSchema.Minimum.HasValue)\n {\n writer.WriteNumber(\"minimum\", numberSchema.Minimum.Value);\n }\n if (numberSchema.Maximum.HasValue)\n {\n writer.WriteNumber(\"maximum\", numberSchema.Maximum.Value);\n }\n break;\n\n case BooleanSchema booleanSchema:\n if (booleanSchema.Default.HasValue)\n {\n writer.WriteBoolean(\"default\", booleanSchema.Default.Value);\n }\n break;\n\n case EnumSchema enumSchema:\n if (enumSchema.Enum is not null)\n {\n writer.WritePropertyName(\"enum\");\n JsonSerializer.Serialize(writer, enumSchema.Enum, McpJsonUtilities.JsonContext.Default.IListString);\n }\n if (enumSchema.EnumNames is not null)\n {\n writer.WritePropertyName(\"enumNames\");\n JsonSerializer.Serialize(writer, enumSchema.EnumNames, McpJsonUtilities.JsonContext.Default.IListString);\n }\n break;\n\n default:\n throw new JsonException($\"Unexpected schema type: {value.GetType().Name}\");\n }\n\n writer.WriteEndObject();\n }\n }\n }\n\n /// Represents a schema for a string type.\n public sealed class StringSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the minimum length for the string.\n [JsonPropertyName(\"minLength\")]\n public int? MinLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Minimum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the maximum length for the string.\n [JsonPropertyName(\"maxLength\")]\n public int? MaxLength\n {\n get => field;\n set\n {\n if (value < 0)\n {\n throw new ArgumentOutOfRangeException(nameof(value), \"Maximum length cannot be negative.\");\n }\n\n field = value;\n }\n }\n\n /// Gets or sets a specific format for the string (\"email\", \"uri\", \"date\", or \"date-time\").\n [JsonPropertyName(\"format\")]\n public string? Format\n {\n get => field;\n set\n {\n if (value is not (null or \"email\" or \"uri\" or \"date\" or \"date-time\"))\n {\n throw new ArgumentException(\"Format must be 'email', 'uri', 'date', or 'date-time'.\", nameof(value));\n }\n\n field = value;\n }\n }\n }\n\n /// Represents a schema for a number or integer type.\n public sealed class NumberSchema : PrimitiveSchemaDefinition\n {\n /// \n [field: MaybeNull]\n public override string Type\n {\n get => field ??= \"number\";\n set\n {\n if (value is not (\"number\" or \"integer\"))\n {\n throw new ArgumentException(\"Type must be 'number' or 'integer'.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// Gets or sets the minimum allowed value.\n [JsonPropertyName(\"minimum\")]\n public double? Minimum { get; set; }\n\n /// Gets or sets the maximum allowed value.\n [JsonPropertyName(\"maximum\")]\n public double? Maximum { get; set; }\n }\n\n /// Represents a schema for a Boolean type.\n public sealed class BooleanSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"boolean\";\n set\n {\n if (value is not \"boolean\")\n {\n throw new ArgumentException(\"Type must be 'boolean'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the default value for the Boolean.\n [JsonPropertyName(\"default\")]\n public bool? Default { get; set; }\n }\n\n /// Represents a schema for an enum type.\n public sealed class EnumSchema : PrimitiveSchemaDefinition\n {\n /// \n [JsonPropertyName(\"type\")]\n public override string Type\n {\n get => \"string\";\n set\n {\n if (value is not \"string\")\n {\n throw new ArgumentException(\"Type must be 'string'.\", nameof(value));\n }\n }\n }\n\n /// Gets or sets the list of allowed string values for the enum.\n [JsonPropertyName(\"enum\")]\n [field: MaybeNull]\n public IList Enum\n {\n get => field ??= [];\n set\n {\n Throw.IfNull(value);\n field = value;\n }\n }\n\n /// Gets or sets optional display names corresponding to the enum values.\n [JsonPropertyName(\"enumNames\")]\n public IList? EnumNames { get; set; }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/AIContentExtensions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\n#if !NET\nusing System.Runtime.InteropServices;\n#endif\nusing System.Text.Json;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides extension methods for converting between Model Context Protocol (MCP) types and Microsoft.Extensions.AI types.\n/// \n/// \n/// This class serves as an adapter layer between Model Context Protocol (MCP) types and the model types\n/// from the Microsoft.Extensions.AI namespace.\n/// \npublic static class AIContentExtensions\n{\n /// \n /// Converts a to a object.\n /// \n /// The prompt message to convert.\n /// A object created from the prompt message.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries.\n /// \n public static ChatMessage ToChatMessage(this PromptMessage promptMessage)\n {\n Throw.IfNull(promptMessage);\n\n AIContent? content = ToAIContent(promptMessage.Content);\n\n return new()\n {\n RawRepresentation = promptMessage,\n Role = promptMessage.Role == Role.User ? ChatRole.User : ChatRole.Assistant,\n Contents = content is not null ? [content] : [],\n };\n }\n\n /// \n /// Converts a to a object.\n /// \n /// The tool result to convert.\n /// The identifier for the function call request that triggered the tool invocation.\n /// A object created from the tool result.\n /// \n /// This method transforms a protocol-specific from the Model Context Protocol\n /// into a standard object that can be used with AI client libraries. It produces a\n /// message containing a with result as a\n /// serialized .\n /// \n public static ChatMessage ToChatMessage(this CallToolResult result, string callId)\n {\n Throw.IfNull(result);\n Throw.IfNull(callId);\n\n return new(ChatRole.Tool, [new FunctionResultContent(callId, JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult))\n {\n RawRepresentation = result,\n }]);\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The prompt result containing messages to convert.\n /// A list of objects created from the prompt messages.\n /// \n /// This method transforms protocol-specific objects from a Model Context Protocol\n /// prompt result into standard objects that can be used with AI client libraries.\n /// \n public static IList ToChatMessages(this GetPromptResult promptResult)\n {\n Throw.IfNull(promptResult);\n\n return promptResult.Messages.Select(m => m.ToChatMessage()).ToList();\n }\n\n /// \n /// Converts a to a list of objects.\n /// \n /// The chat message to convert.\n /// A list of objects created from the chat message's contents.\n /// \n /// This method transforms standard objects used with AI client libraries into\n /// protocol-specific objects for the Model Context Protocol system.\n /// Only representable content items are processed.\n /// \n public static IList ToPromptMessages(this ChatMessage chatMessage)\n {\n Throw.IfNull(chatMessage);\n\n Role r = chatMessage.Role == ChatRole.User ? Role.User : Role.Assistant;\n\n List messages = [];\n foreach (var content in chatMessage.Contents)\n {\n if (content is TextContent or DataContent)\n {\n messages.Add(new PromptMessage { Role = r, Content = content.ToContent() });\n }\n }\n\n return messages;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// \n /// The created . If the content can't be converted (such as when it's a resource link), is returned.\n /// \n /// \n /// This method converts Model Context Protocol content types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent? ToAIContent(this ContentBlock content)\n {\n Throw.IfNull(content);\n\n AIContent? ac = content switch\n {\n TextContentBlock textContent => new TextContent(textContent.Text),\n ImageContentBlock imageContent => new DataContent(Convert.FromBase64String(imageContent.Data), imageContent.MimeType),\n AudioContentBlock audioContent => new DataContent(Convert.FromBase64String(audioContent.Data), audioContent.MimeType),\n EmbeddedResourceBlock resourceContent => resourceContent.Resource.ToAIContent(),\n _ => null,\n };\n\n if (ac is not null)\n {\n ac.RawRepresentation = content;\n }\n\n return ac;\n }\n\n /// Creates a new from the content of a .\n /// The to convert.\n /// The created .\n /// \n /// This method converts Model Context Protocol resource types to the equivalent Microsoft.Extensions.AI \n /// content types, enabling seamless integration between the protocol and AI client libraries.\n /// \n public static AIContent ToAIContent(this ResourceContents content)\n {\n Throw.IfNull(content);\n\n AIContent ac = content switch\n {\n BlobResourceContents blobResource => new DataContent(Convert.FromBase64String(blobResource.Blob), blobResource.MimeType ?? \"application/octet-stream\"),\n TextResourceContents textResource => new TextContent(textResource.Text),\n _ => throw new NotSupportedException($\"Resource type '{content.GetType().Name}' is not supported.\")\n };\n\n (ac.AdditionalProperties ??= [])[\"uri\"] = content.Uri;\n ac.RawRepresentation = content;\n\n return ac;\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// The created instances.\n /// \n /// \n /// This method converts a collection of Model Context Protocol content objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple content items, such as\n /// when processing the contents of a message or response.\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic for text, images, audio, and resources.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent).OfType()];\n }\n\n /// Creates a list of from a sequence of .\n /// The instances to convert.\n /// A list of objects created from the resource contents.\n /// \n /// \n /// This method converts a collection of Model Context Protocol resource objects into a collection of\n /// Microsoft.Extensions.AI content objects. It's useful when working with multiple resources, such as\n /// when processing the contents of a .\n /// \n /// \n /// Each object is converted using ,\n /// preserving the type-specific conversion logic: text resources become objects and\n /// binary resources become objects.\n /// \n /// \n public static IList ToAIContents(this IEnumerable contents)\n {\n Throw.IfNull(contents);\n\n return [.. contents.Select(ToAIContent)];\n }\n\n internal static ContentBlock ToContent(this AIContent content) =>\n content switch\n {\n TextContent textContent => new TextContentBlock\n {\n Text = textContent.Text,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"image\") => new ImageContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent when dataContent.HasTopLevelMediaType(\"audio\") => new AudioContentBlock\n {\n Data = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n },\n\n DataContent dataContent => new EmbeddedResourceBlock\n {\n Resource = new BlobResourceContents\n {\n Blob = dataContent.Base64Data.ToString(),\n MimeType = dataContent.MediaType,\n }\n },\n\n _ => new TextContentBlock\n {\n Text = JsonSerializer.Serialize(content, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))),\n }\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContentBlock.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents content within the Model Context Protocol (MCP).\n/// \n/// \n/// \n/// The class is a fundamental type in the MCP that can represent different forms of content\n/// based on the property. Derived types like , ,\n/// and provide the type-specific content.\n/// \n/// \n/// This class is used throughout the MCP for representing content in messages, tool responses,\n/// and other communication between clients and servers.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))] // TODO: This converter exists due to the lack of downlevel support for AllowOutOfOrderMetadataProperties.\npublic abstract class ContentBlock\n{\n /// Prevent external derivations.\n private protected ContentBlock()\n {\n }\n\n /// \n /// Gets or sets the type of content.\n /// \n /// \n /// This determines the structure of the content object. Valid values include \"image\", \"audio\", \"text\", \"resource\", and \"resource_link\".\n /// \n [JsonPropertyName(\"type\")]\n public string Type { get; set; } = string.Empty;\n\n /// \n /// Gets or sets optional annotations for the content.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the content. Clients can use this information to filter or prioritize content for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ContentBlock? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? type = null;\n string? text = null;\n string? name = null;\n string? data = null;\n string? mimeType = null;\n string? uri = null;\n string? description = null;\n long? size = null;\n ResourceContents? resource = null;\n Annotations? annotations = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"type\":\n type = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"name\":\n name = reader.GetString();\n break;\n\n case \"data\":\n data = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"description\":\n description = reader.GetString();\n break;\n\n case \"size\":\n size = reader.GetInt64();\n break;\n\n case \"resource\":\n resource = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.ResourceContents);\n break;\n\n case \"annotations\":\n annotations = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.Annotations);\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n return type switch\n {\n \"text\" => new TextContentBlock\n {\n Text = text ?? throw new JsonException(\"Text contents must be provided for 'text' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"image\" => new ImageContentBlock\n {\n Data = data ?? throw new JsonException(\"Image data must be provided for 'image' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'image' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"audio\" => new AudioContentBlock\n {\n Data = data ?? throw new JsonException(\"Audio data must be provided for 'audio' type.\"),\n MimeType = mimeType ?? throw new JsonException(\"MIME type must be provided for 'audio' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource\" => new EmbeddedResourceBlock\n {\n Resource = resource ?? throw new JsonException(\"Resource contents must be provided for 'resource' type.\"),\n Annotations = annotations,\n Meta = meta,\n },\n\n \"resource_link\" => new ResourceLinkBlock\n {\n Uri = uri ?? throw new JsonException(\"URI must be provided for 'resource_link' type.\"),\n Name = name ?? throw new JsonException(\"Name must be provided for 'resource_link' type.\"),\n Description = description,\n MimeType = mimeType,\n Size = size,\n Annotations = annotations,\n },\n\n _ => throw new JsonException($\"Unknown content type: '{type}'\"),\n };\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ContentBlock value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n\n writer.WriteString(\"type\", value.Type);\n\n switch (value)\n {\n case TextContentBlock textContent:\n writer.WriteString(\"text\", textContent.Text);\n if (textContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, textContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ImageContentBlock imageContent:\n writer.WriteString(\"data\", imageContent.Data);\n writer.WriteString(\"mimeType\", imageContent.MimeType);\n if (imageContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, imageContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case AudioContentBlock audioContent:\n writer.WriteString(\"data\", audioContent.Data);\n writer.WriteString(\"mimeType\", audioContent.MimeType);\n if (audioContent.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, audioContent.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case EmbeddedResourceBlock embeddedResource:\n writer.WritePropertyName(\"resource\");\n JsonSerializer.Serialize(writer, embeddedResource.Resource, McpJsonUtilities.JsonContext.Default.ResourceContents);\n if (embeddedResource.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, embeddedResource.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n break;\n\n case ResourceLinkBlock resourceLink:\n writer.WriteString(\"uri\", resourceLink.Uri);\n writer.WriteString(\"name\", resourceLink.Name);\n if (resourceLink.Description is not null)\n {\n writer.WriteString(\"description\", resourceLink.Description);\n }\n if (resourceLink.MimeType is not null)\n {\n writer.WriteString(\"mimeType\", resourceLink.MimeType);\n }\n if (resourceLink.Size.HasValue)\n {\n writer.WriteNumber(\"size\", resourceLink.Size.Value);\n }\n break;\n }\n\n if (value.Annotations is { } annotations)\n {\n writer.WritePropertyName(\"annotations\");\n JsonSerializer.Serialize(writer, annotations, McpJsonUtilities.JsonContext.Default.Annotations);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n\n/// Represents text provided to or from an LLM.\npublic sealed class TextContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public TextContentBlock() => Type = \"text\";\n\n /// \n /// Gets or sets the text content of the message.\n /// \n [JsonPropertyName(\"text\")]\n public required string Text { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents an image provided to or from an LLM.\npublic sealed class ImageContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ImageContentBlock() => Type = \"image\";\n\n /// \n /// Gets or sets the base64-encoded image data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"image/png\" and \"image/jpeg\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents audio provided to or from an LLM.\npublic sealed class AudioContentBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public AudioContentBlock() => Type = \"audio\";\n\n /// \n /// Gets or sets the base64-encoded audio data.\n /// \n [JsonPropertyName(\"data\")]\n public required string Data { get; set; }\n\n /// \n /// Gets or sets the MIME type (or \"media type\") of the content, specifying the format of the data.\n /// \n /// \n /// \n /// Common values include \"audio/wav\" and \"audio/mp3\".\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public required string MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents the contents of a resource, embedded into a prompt or tool call result.\n/// \n/// It is up to the client how best to render embedded resources for the benefit of the LLM and/or the user.\n/// \npublic sealed class EmbeddedResourceBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public EmbeddedResourceBlock() => Type = \"resource\";\n\n /// \n /// Gets or sets the resource content of the message when is \"resource\".\n /// \n /// \n /// \n /// Resources can be either text-based () or \n /// binary (), allowing for flexible data representation.\n /// Each resource has a URI that can be used for identification and retrieval.\n /// \n /// \n [JsonPropertyName(\"resource\")]\n public required ResourceContents Resource { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n\n/// Represents a resource that the server is capable of reading, included in a prompt or tool call result.\n/// \n/// Resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n/// \npublic sealed class ResourceLinkBlock : ContentBlock\n{\n /// Initializes the instance of the class.\n public ResourceLinkBlock() => Type = \"resource_link\";\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for this resource.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\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/ModelContextProtocol.AspNetCore/HttpMcpSession.cs", "using ModelContextProtocol.AspNetCore.Stateless;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Security.Claims;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed class HttpMcpSession(\n string sessionId,\n TTransport transport,\n UserIdClaim? userId,\n TimeProvider timeProvider) : IAsyncDisposable\n where TTransport : ITransport\n{\n private int _referenceCount;\n private int _getRequestStarted;\n private CancellationTokenSource _disposeCts = new();\n\n public string Id { get; } = sessionId;\n public TTransport Transport { get; } = transport;\n public UserIdClaim? UserIdClaim { get; } = userId;\n\n public CancellationToken SessionClosed => _disposeCts.Token;\n\n public bool IsActive => !SessionClosed.IsCancellationRequested && _referenceCount > 0;\n public long LastActivityTicks { get; private set; } = timeProvider.GetTimestamp();\n\n private TimeProvider TimeProvider => timeProvider;\n\n public IMcpServer? Server { get; set; }\n public Task? ServerRunTask { get; set; }\n\n public IDisposable AcquireReference()\n {\n Interlocked.Increment(ref _referenceCount);\n return new UnreferenceDisposable(this);\n }\n\n public bool TryStartGetRequest() => Interlocked.Exchange(ref _getRequestStarted, 1) == 0;\n\n public async ValueTask DisposeAsync()\n {\n try\n {\n await _disposeCts.CancelAsync();\n\n if (ServerRunTask is not null)\n {\n await ServerRunTask;\n }\n }\n catch (OperationCanceledException)\n {\n }\n finally\n {\n try\n {\n if (Server is not null)\n {\n await Server.DisposeAsync();\n }\n }\n finally\n {\n await Transport.DisposeAsync();\n _disposeCts.Dispose();\n }\n }\n }\n\n public bool HasSameUserId(ClaimsPrincipal user)\n => UserIdClaim == StreamableHttpHandler.GetUserIdClaim(user);\n\n private sealed class UnreferenceDisposable(HttpMcpSession session) : IDisposable\n {\n public void Dispose()\n {\n if (Interlocked.Decrement(ref session._referenceCount) == 0)\n {\n session.LastActivityTicks = session.TimeProvider.GetTimestamp();\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Diagnostics.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\n\nnamespace ModelContextProtocol;\n\ninternal static class Diagnostics\n{\n internal static ActivitySource ActivitySource { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Meter Meter { get; } = new(\"Experimental.ModelContextProtocol\");\n\n internal static Histogram CreateDurationHistogram(string name, string description, bool longBuckets) =>\n Meter.CreateHistogram(name, \"s\", description\n#if NET9_0_OR_GREATER\n , advice: longBuckets ? LongSecondsBucketBoundaries : ShortSecondsBucketBoundaries\n#endif\n );\n\n#if NET9_0_OR_GREATER\n /// \n /// Follows boundaries from http.server.request.duration/http.client.request.duration\n /// \n private static InstrumentAdvice ShortSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n };\n\n /// \n /// Not based on a standard. Larger bucket sizes for longer lasting operations, e.g. HTTP connection duration.\n /// See https://github.com/open-telemetry/semantic-conventions/issues/336\n /// \n private static InstrumentAdvice LongSecondsBucketBoundaries { get; } = new()\n {\n HistogramBucketBoundaries = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300],\n };\n#endif\n\n internal static ActivityContext ExtractActivityContext(this DistributedContextPropagator propagator, JsonRpcMessage message)\n {\n propagator.ExtractTraceIdAndState(message, ExtractContext, out var traceparent, out var tracestate);\n ActivityContext.TryParse(traceparent, tracestate, true, out var activityContext);\n return activityContext;\n }\n\n private static void ExtractContext(object? message, string fieldName, out string? fieldValue, out IEnumerable? fieldValues)\n {\n fieldValues = null;\n fieldValue = null;\n\n JsonNode? meta = null;\n switch (message)\n {\n case JsonRpcRequest request:\n meta = request.Params?[\"_meta\"];\n break;\n\n case JsonRpcNotification notification:\n meta = notification.Params?[\"_meta\"];\n break;\n }\n\n if (meta?[fieldName] is JsonValue value && value.GetValueKind() == JsonValueKind.String)\n {\n fieldValue = value.GetValue();\n }\n }\n\n internal static void InjectActivityContext(this DistributedContextPropagator propagator, Activity? activity, JsonRpcMessage message)\n {\n // noop if activity is null\n propagator.Inject(activity, message, InjectContext);\n }\n\n private static void InjectContext(object? message, string key, string value)\n {\n JsonNode? parameters = null;\n switch (message)\n {\n case JsonRpcRequest request:\n parameters = request.Params;\n break;\n\n case JsonRpcNotification notification:\n parameters = notification.Params;\n break;\n }\n\n // Replace any params._meta with the current value\n if (parameters is JsonObject jsonObject)\n {\n if (jsonObject[\"_meta\"] is not JsonObject meta)\n {\n meta = new JsonObject();\n jsonObject[\"_meta\"] = meta;\n }\n meta[key] = value;\n }\n }\n\n internal static bool ShouldInstrumentMessage(JsonRpcMessage message) =>\n ActivitySource.HasListeners() &&\n message switch\n {\n JsonRpcRequest => true,\n JsonRpcNotification notification => notification.Method != NotificationMethods.LoggingMessageNotification,\n _ => false\n };\n\n internal static ActivityLink[] ActivityLinkFromCurrent() => Activity.Current is null ? [] : [new ActivityLink(Activity.Current.Context)];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceContents.cs", "using System.ComponentModel;\nusing System.Diagnostics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class representing contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// serves as the base class for different types of resources that can be \n/// exchanged through the Model Context Protocol. Resources are identified by URIs and can contain\n/// different types of data.\n/// \n/// \n/// This class is abstract and has two concrete implementations:\n/// \n/// - For text-based resources\n/// - For binary data resources\n/// \n/// \n/// \n/// See the schema for more details.\n/// \n/// \n[JsonConverter(typeof(Converter))]\npublic abstract class ResourceContents\n{\n /// Prevent external derivations.\n private protected ResourceContents()\n {\n }\n\n /// \n /// Gets or sets the URI of the resource.\n /// \n [JsonPropertyName(\"uri\")]\n public string Uri { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the MIME type of the resource content.\n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Provides a for .\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public class Converter : JsonConverter\n {\n /// \n public override ResourceContents? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n if (reader.TokenType == JsonTokenType.Null)\n {\n return null;\n }\n\n if (reader.TokenType != JsonTokenType.StartObject)\n {\n throw new JsonException();\n }\n\n string? uri = null;\n string? mimeType = null;\n string? blob = null;\n string? text = null;\n JsonObject? meta = null;\n\n while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)\n {\n if (reader.TokenType != JsonTokenType.PropertyName)\n {\n continue;\n }\n\n string? propertyName = reader.GetString();\n bool success = reader.Read();\n Debug.Assert(success, \"STJ must have buffered the entire object for us.\");\n\n switch (propertyName)\n {\n case \"uri\":\n uri = reader.GetString();\n break;\n\n case \"mimeType\":\n mimeType = reader.GetString();\n break;\n\n case \"blob\":\n blob = reader.GetString();\n break;\n\n case \"text\":\n text = reader.GetString();\n break;\n\n case \"_meta\":\n meta = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.JsonObject);\n break;\n\n default:\n break;\n }\n }\n\n if (blob is not null)\n {\n return new BlobResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Blob = blob,\n Meta = meta,\n };\n }\n\n if (text is not null)\n {\n return new TextResourceContents\n {\n Uri = uri ?? string.Empty,\n MimeType = mimeType,\n Text = text,\n Meta = meta,\n };\n }\n\n return null;\n }\n\n /// \n public override void Write(Utf8JsonWriter writer, ResourceContents value, JsonSerializerOptions options)\n {\n if (value is null)\n {\n writer.WriteNullValue();\n return;\n }\n\n writer.WriteStartObject();\n writer.WriteString(\"uri\", value.Uri);\n writer.WriteString(\"mimeType\", value.MimeType);\n \n Debug.Assert(value is BlobResourceContents or TextResourceContents);\n if (value is BlobResourceContents blobResource)\n {\n writer.WriteString(\"blob\", blobResource.Blob);\n }\n else if (value is TextResourceContents textResource)\n {\n writer.WriteString(\"text\", textResource.Text);\n }\n\n if (value.Meta is not null)\n {\n writer.WritePropertyName(\"_meta\");\n JsonSerializer.Serialize(writer, value.Meta, McpJsonUtilities.JsonContext.Default.JsonObject);\n }\n\n writer.WriteEndObject();\n }\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/PasteArguments.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\n// Copied from:\n// https://github.com/dotnet/runtime/blob/d2650b6ae7023a2d9d2c74c56116f1f18472ab04/src/libraries/System.Private.CoreLib/src/System/PasteArguments.cs\n// and changed from using ValueStringBuilder to StringBuilder.\n\n#if !NET\nusing System.Text;\n\nnamespace System;\n\ninternal static partial class PasteArguments\n{\n internal static void AppendArgument(StringBuilder stringBuilder, string argument)\n {\n if (stringBuilder.Length != 0)\n {\n stringBuilder.Append(' ');\n }\n\n // Parsing rules for non-argv[0] arguments:\n // - Backslash is a normal character except followed by a quote.\n // - 2N backslashes followed by a quote ==> N literal backslashes followed by unescaped quote\n // - 2N+1 backslashes followed by a quote ==> N literal backslashes followed by a literal quote\n // - Parsing stops at first whitespace outside of quoted region.\n // - (post 2008 rule): A closing quote followed by another quote ==> literal quote, and parsing remains in quoting mode.\n if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument))\n {\n // Simple case - no quoting or changes needed.\n stringBuilder.Append(argument);\n }\n else\n {\n stringBuilder.Append(Quote);\n int idx = 0;\n while (idx < argument.Length)\n {\n char c = argument[idx++];\n if (c == Backslash)\n {\n int numBackSlash = 1;\n while (idx < argument.Length && argument[idx] == Backslash)\n {\n idx++;\n numBackSlash++;\n }\n\n if (idx == argument.Length)\n {\n // We'll emit an end quote after this so must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2);\n }\n else if (argument[idx] == Quote)\n {\n // Backslashes will be followed by a quote. Must double the number of backslashes.\n stringBuilder.Append(Backslash, numBackSlash * 2 + 1);\n stringBuilder.Append(Quote);\n idx++;\n }\n else\n {\n // Backslash will not be followed by a quote, so emit as normal characters.\n stringBuilder.Append(Backslash, numBackSlash);\n }\n\n continue;\n }\n\n if (c == Quote)\n {\n // Escape the quote so it appears as a literal. This also guarantees that we won't end up generating a closing quote followed\n // by another quote (which parses differently pre-2008 vs. post-2008.)\n stringBuilder.Append(Backslash);\n stringBuilder.Append(Quote);\n continue;\n }\n\n stringBuilder.Append(c);\n }\n\n stringBuilder.Append(Quote);\n }\n }\n\n private static bool ContainsNoWhitespaceOrQuotes(string s)\n {\n for (int i = 0; i < s.Length; i++)\n {\n char c = s[i];\n if (char.IsWhiteSpace(c) || c == Quote)\n {\n return false;\n }\n }\n\n return true;\n }\n\n private const char Quote = '\\\"';\n private const char Backslash = '\\\\';\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol/McpServerOptionsSetup.cs", "using Microsoft.Extensions.Options;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Configures the McpServerOptions using addition services from DI.\n/// \n/// The server handlers configuration options.\n/// Tools individually registered.\n/// Prompts individually registered.\n/// Resources individually registered.\ninternal sealed class McpServerOptionsSetup(\n IOptions serverHandlers,\n IEnumerable serverTools,\n IEnumerable serverPrompts,\n IEnumerable serverResources) : IConfigureOptions\n{\n /// \n /// Configures the given McpServerOptions instance by setting server information\n /// and applying custom server handlers and tools.\n /// \n /// The options instance to be configured.\n public void Configure(McpServerOptions options)\n {\n Throw.IfNull(options);\n\n // Collect all of the provided tools into a tools collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection toolCollection = options.Capabilities?.Tools?.ToolCollection ?? [];\n foreach (var tool in serverTools)\n {\n toolCollection.TryAdd(tool);\n }\n\n if (!toolCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Tools ??= new();\n options.Capabilities.Tools.ToolCollection = toolCollection;\n }\n\n // Collect all of the provided prompts into a prompts collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerPrimitiveCollection promptCollection = options.Capabilities?.Prompts?.PromptCollection ?? [];\n foreach (var prompt in serverPrompts)\n {\n promptCollection.TryAdd(prompt);\n }\n\n if (!promptCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Prompts ??= new();\n options.Capabilities.Prompts.PromptCollection = promptCollection;\n }\n\n // Collect all of the provided resources into a resources collection. If the options already has\n // a collection, add to it, otherwise create a new one. We want to maintain the identity\n // of an existing collection in case someone has provided their own derived type, wants\n // change notifications, etc.\n McpServerResourceCollection resourceCollection = options.Capabilities?.Resources?.ResourceCollection ?? [];\n foreach (var resource in serverResources)\n {\n resourceCollection.TryAdd(resource);\n }\n\n if (!resourceCollection.IsEmpty)\n {\n options.Capabilities ??= new();\n options.Capabilities.Resources ??= new();\n options.Capabilities.Resources.ResourceCollection = resourceCollection;\n }\n\n // Apply custom server handlers.\n serverHandlers.Value.OverwriteWithSetHandlers(options);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ClientCapabilities.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a client may support.\n/// \n/// \n/// \n/// Capabilities define the features and functionality that a client can handle when communicating with an MCP server.\n/// These are advertised to the server during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ClientCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the client supports.\n /// \n /// \n /// \n /// The dictionary allows clients to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Servers should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets the client's roots capability, which are entry points for resource navigation.\n /// \n /// \n /// \n /// When is non-, the client indicates that it can respond to \n /// server requests for listing root URIs. Root URIs serve as entry points for resource navigation in the protocol.\n /// \n /// \n /// The server can use to request the list of\n /// available roots from the client, which will trigger the client's .\n /// \n /// \n [JsonPropertyName(\"roots\")]\n public RootsCapability? Roots { get; set; }\n\n /// \n /// Gets or sets the client's sampling capability, which indicates whether the client \n /// supports issuing requests to an LLM on behalf of the server.\n /// \n [JsonPropertyName(\"sampling\")]\n public SamplingCapability? Sampling { get; set; }\n\n /// \n /// Gets or sets the client's elicitation capability, which indicates whether the client \n /// supports elicitation of additional information from the user on behalf of the server.\n /// \n [JsonPropertyName(\"elicitation\")]\n public ElicitationCapability? Elicitation { get; set; }\n\n /// Gets or sets notification handlers to register with the client.\n /// \n /// \n /// When constructed, the client will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The client will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the client to respond to server-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the client for the lifetime of the client.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/CustomizableJsonStringEnumConverter.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.ComponentModel;\nusing System.Diagnostics.CodeAnalysis;\n#if !NET9_0_OR_GREATER\nusing System.Reflection;\n#endif\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n#if !NET9_0_OR_GREATER\nusing ModelContextProtocol;\n#endif\n\n// NOTE:\n// This is a workaround for lack of System.Text.Json's JsonStringEnumConverter\n// 9.x support for JsonStringEnumMemberNameAttribute. Once all builds use the System.Text.Json 9.x\n// version, this whole file can be removed. Note that the type is public so that external source\n// generators can use it, so removing it is a potential breaking change.\n\nnamespace ModelContextProtocol\n{\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// The enum type to convert.\n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n public sealed class CustomizableJsonStringEnumConverter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] TEnum> :\n JsonStringEnumConverter where TEnum : struct, Enum\n {\n#if !NET9_0_OR_GREATER\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The converter automatically detects any enum members decorated with \n /// and uses those values during serialization and deserialization.\n /// \n public CustomizableJsonStringEnumConverter() :\n base(namingPolicy: ResolveNamingPolicy())\n {\n }\n\n private static JsonNamingPolicy? ResolveNamingPolicy()\n {\n var map = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)\n .Select(f => (f.Name, AttributeName: f.GetCustomAttribute()?.Name))\n .Where(pair => pair.AttributeName != null)\n .ToDictionary(pair => pair.Name, pair => pair.AttributeName);\n\n return map.Count > 0 ? new EnumMemberNamingPolicy(map!) : null;\n }\n\n private sealed class EnumMemberNamingPolicy(Dictionary map) : JsonNamingPolicy\n {\n public override string ConvertName(string name) =>\n map.TryGetValue(name, out string? newName) ?\n newName :\n name;\n }\n#endif\n }\n\n /// \n /// A JSON converter for enums that allows customizing the serialized string value of enum members\n /// using the .\n /// \n /// \n /// This is a temporary workaround for lack of System.Text.Json's JsonStringEnumConverter<T>\n /// 9.x support for custom enum member naming. It will be replaced by the built-in functionality\n /// once .NET 9 is fully adopted.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n [RequiresUnreferencedCode(\"Requires unreferenced code to instantiate the generic enum converter.\")]\n [RequiresDynamicCode(\"Requires dynamic code to instantiate the generic enum converter.\")]\n public sealed class CustomizableJsonStringEnumConverter : JsonConverterFactory\n {\n /// \n public override bool CanConvert(Type typeToConvert) => typeToConvert.IsEnum;\n /// \n public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)\n {\n Type converterType = typeof(CustomizableJsonStringEnumConverter<>).MakeGenericType(typeToConvert)!;\n var factory = (JsonConverterFactory)Activator.CreateInstance(converterType)!;\n return factory.CreateConverter(typeToConvert, options);\n }\n }\n}\n\n#if !NET9_0_OR_GREATER\nnamespace System.Text.Json.Serialization\n{\n /// \n /// Determines the custom string value that should be used when serializing an enum member using JSON.\n /// \n /// \n /// This attribute is a temporary workaround for lack of System.Text.Json's support for custom enum member naming\n /// in versions prior to .NET 9. It works together with \n /// to provide customized string representations of enum values during JSON serialization and deserialization.\n /// \n [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\n internal sealed class JsonStringEnumMemberNameAttribute : Attribute\n {\n /// \n /// Creates new attribute instance with a specified enum member name.\n /// \n /// The name to apply to the current enum member when serialized to JSON.\n public JsonStringEnumMemberNameAttribute(string name)\n {\n Name = name;\n }\n\n /// \n /// Gets the custom JSON name of the enum member.\n /// \n public string Name { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientPrompt.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named prompt that can be retrieved from an MCP server and invoked with arguments.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a prompt defined on an MCP server. It allows\n/// retrieving the prompt's content by sending a request to the server with optional arguments.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \n/// Each prompt has a name and optionally a description, and it can be invoked with arguments\n/// to produce customized prompt content from the server.\n/// \n/// \npublic sealed class McpClientPrompt\n{\n private readonly IMcpClient _client;\n\n internal McpClientPrompt(IMcpClient client, Prompt prompt)\n {\n _client = client;\n ProtocolPrompt = prompt;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the prompt,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Prompt ProtocolPrompt { get; }\n\n /// Gets the name of the prompt.\n public string Name => ProtocolPrompt.Name;\n\n /// Gets the title of the prompt.\n public string? Title => ProtocolPrompt.Title;\n\n /// Gets a description of the prompt.\n public string? Description => ProtocolPrompt.Description;\n\n /// \n /// Gets this prompt's content by sending a request to the server with optional arguments.\n /// \n /// Optional arguments to pass to the prompt. Keys are parameter names, and values are the argument values.\n /// The serialization options governing argument serialization.\n /// The to monitor for cancellation requests. The default is .\n /// A containing the prompt's result with content and messages.\n /// \n /// \n /// This method sends a request to the MCP server to execute this prompt with the provided arguments.\n /// The server will process the request and return a result containing messages or other content.\n /// \n /// \n /// This is a convenience method that internally calls \n /// with this prompt's name and arguments.\n /// \n /// \n public async ValueTask GetAsync(\n IEnumerable>? arguments = null,\n JsonSerializerOptions? serializerOptions = null,\n CancellationToken cancellationToken = default)\n {\n IReadOnlyDictionary? argDict =\n arguments as IReadOnlyDictionary ??\n arguments?.ToDictionary();\n\n return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, serializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false);\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientFactory.cs", "using Microsoft.Extensions.Logging;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides factory methods for creating Model Context Protocol (MCP) clients.\n/// \n/// \n/// This factory class is the primary way to instantiate instances\n/// that connect to MCP servers. It handles the creation and connection\n/// of appropriate implementations through the supplied transport.\n/// \npublic static partial class McpClientFactory\n{\n /// Creates an , connecting it to the specified server.\n /// The transport instance used to communicate with the server.\n /// \n /// A client configuration object which specifies client capabilities and protocol version.\n /// If , details based on the current process will be employed.\n /// \n /// A logger factory for creating loggers for clients.\n /// The to monitor for cancellation requests. The default is .\n /// An that's connected to the specified server.\n /// is .\n /// is .\n public static async Task CreateAsync(\n IClientTransport clientTransport,\n McpClientOptions? clientOptions = null,\n ILoggerFactory? loggerFactory = null,\n CancellationToken cancellationToken = default)\n {\n Throw.IfNull(clientTransport);\n\n McpClient client = new(clientTransport, clientOptions, loggerFactory);\n try\n {\n await client.ConnectAsync(cancellationToken).ConfigureAwait(false);\n if (loggerFactory?.CreateLogger(typeof(McpClientFactory)) is ILogger logger)\n {\n logger.LogClientCreated(client.EndpointName);\n }\n }\n catch\n {\n await client.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n\n return client;\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} client created and connected.\")]\n private static partial void LogClientCreated(this ILogger logger, string endpointName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ServerCapabilities.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capabilities that a server may support.\n/// \n/// \n/// \n/// Server capabilities define the features and functionality available when clients connect.\n/// These capabilities are advertised to clients during the initialize handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ServerCapabilities\n{\n /// \n /// Gets or sets experimental, non-standard capabilities that the server supports.\n /// \n /// \n /// \n /// The dictionary allows servers to advertise support for features that are not yet \n /// standardized in the Model Context Protocol specification. This extension mechanism enables \n /// future protocol enhancements while maintaining backward compatibility.\n /// \n /// \n /// Values in this dictionary are implementation-specific and should be coordinated between client \n /// and server implementations. Clients should not assume the presence of any experimental capability \n /// without checking for it first.\n /// \n /// \n [JsonPropertyName(\"experimental\")]\n public IDictionary? Experimental { get; set; }\n\n /// \n /// Gets or sets a server's logging capability, supporting sending log messages to the client.\n /// \n [JsonPropertyName(\"logging\")]\n public LoggingCapability? Logging { get; set; }\n\n /// \n /// Gets or sets a server's prompts capability for serving predefined prompt templates that clients can discover and use.\n /// \n [JsonPropertyName(\"prompts\")]\n public PromptsCapability? Prompts { get; set; }\n\n /// \n /// Gets or sets a server's resources capability for serving predefined resources that clients can discover and use.\n /// \n [JsonPropertyName(\"resources\")]\n public ResourcesCapability? Resources { get; set; }\n\n /// \n /// Gets or sets a server's tools capability for listing tools that a client is able to invoke.\n /// \n [JsonPropertyName(\"tools\")]\n public ToolsCapability? Tools { get; set; }\n\n /// \n /// Gets or sets a server's completions capability for supporting argument auto-completion suggestions.\n /// \n [JsonPropertyName(\"completions\")]\n public CompletionsCapability? Completions { get; set; }\n\n /// Gets or sets notification handlers to register with the server.\n /// \n /// \n /// When constructed, the server will enumerate these handlers once, which may contain multiple handlers per notification method key.\n /// The server will not re-enumerate the sequence after initialization.\n /// \n /// \n /// Notification handlers allow the server to respond to client-sent notifications for specific methods.\n /// Each key in the collection is a notification method name, and each value is a callback that will be invoked\n /// when a notification with that method is received.\n /// \n /// \n /// Handlers provided via will be registered with the server for the lifetime of the server.\n /// For transient handlers, may be used to register a handler that can\n /// then be unregistered by disposing of the returned from the method.\n /// \n /// \n [JsonIgnore]\n public IEnumerable>>? NotificationHandlers { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerTool.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable tool used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP tool for use in the server (as opposed\n/// to , which provides the protocol representation of a tool, and , which\n/// provides a client-side representation of a tool). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithToolsFromAssembly and WithTools. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \npublic abstract class McpServerTool : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerTool()\n {\n }\n\n /// Gets the protocol type for this instance.\n public abstract Tool ProtocolTool { get; }\n\n /// Invokes the .\n /// The request information resulting in the invocation of this tool.\n /// The to monitor for cancellation requests. The default is .\n /// The call response from invoking the tool.\n /// is .\n public abstract ValueTask InvokeAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n Delegate method,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerTool Create(\n MethodInfo method, \n object? target = null,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerTool Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerTool Create(\n AIFunction function,\n McpServerToolCreateOptions? options = null) =>\n AIFunctionMcpServerTool.Create(function, options);\n\n /// \n public override string ToString() => ProtocolTool.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolTool.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPrompt.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable prompt used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP prompt for use in the server (as opposed\n/// to , which provides the protocol representation of a prompt, and , which\n/// provides a client-side representation of a prompt). Instances of can be added into a\n/// to be picked up automatically when is used to create\n/// an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithPromptsFromAssembly and WithPrompts. The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the JSON received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to \n/// rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerPrompt : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerPrompt()\n {\n }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolPrompt property represents the underlying prompt definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the prompt's name,\n /// description, and acceptable arguments.\n /// \n public abstract Prompt ProtocolPrompt { get; }\n\n /// \n /// Gets the prompt, rendering it with the provided request parameters and returning the prompt result.\n /// \n /// \n /// The request context containing information about the prompt invocation, including any arguments\n /// passed to the prompt. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the prompt content and messages.\n /// \n /// is .\n /// The prompt implementation returns or an unsupported result type.\n public abstract ValueTask GetAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n Delegate method,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerPrompt Create(\n MethodInfo method, \n object? target = null,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerPrompt Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerPrompt Create(\n AIFunction function,\n McpServerPromptCreateOptions? options = null) =>\n AIFunctionMcpServerPrompt.Create(function, options);\n\n /// \n public override string ToString() => ProtocolPrompt.Name;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolPrompt.Name;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StdioServerTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implemented via \"stdio\" (standard input/output).\n/// \npublic sealed class StdioServerTransport : StreamServerTransport\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The server options.\n /// Optional logger factory used for logging employed by the transport.\n /// is or contains a null name.\n public StdioServerTransport(McpServerOptions serverOptions, ILoggerFactory? loggerFactory = null)\n : this(GetServerName(serverOptions), loggerFactory: loggerFactory)\n {\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The name of the server.\n /// Optional logger factory used for logging employed by the transport.\n /// is .\n public StdioServerTransport(string serverName, ILoggerFactory? loggerFactory = null)\n : base(new CancellableStdinStream(Console.OpenStandardInput()),\n new BufferedStream(Console.OpenStandardOutput()),\n serverName ?? throw new ArgumentNullException(nameof(serverName)),\n loggerFactory)\n {\n }\n\n private static string GetServerName(McpServerOptions serverOptions)\n {\n Throw.IfNull(serverOptions);\n\n return serverOptions.ServerInfo?.Name ?? McpServer.DefaultImplementation.Name;\n }\n\n // Neither WindowsConsoleStream nor UnixConsoleStream respect CancellationTokens or cancel any I/O on Dispose.\n // WindowsConsoleStream will return an EOS on Ctrl-C, but that is not the only reason the shutdownToken may fire.\n private sealed class CancellableStdinStream(Stream stdinStream) : Stream\n {\n public override bool CanRead => true;\n public override bool CanSeek => false;\n public override bool CanWrite => false;\n\n public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)\n => stdinStream.ReadAsync(buffer, offset, count, cancellationToken).WaitAsync(cancellationToken);\n\n#if NET\n public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)\n {\n ValueTask vt = stdinStream.ReadAsync(buffer, cancellationToken);\n return vt.IsCompletedSuccessfully ? vt : new(vt.AsTask().WaitAsync(cancellationToken));\n }\n#endif\n\n // The McpServer shouldn't call flush on the stdin Stream, but it doesn't need to throw just in case.\n public override void Flush() { }\n\n public override long Length => throw new NotSupportedException();\n\n public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }\n\n public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();\n\n public override void SetLength(long value) => throw new NotSupportedException();\n public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResource.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Reflection;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an invocable resource used by Model Context Protocol clients and servers.\n/// \n/// \n/// \n/// is an abstract base class that represents an MCP resource for use in the server (as opposed\n/// to or , which provide the protocol representations of a resource). Instances of \n/// can be added into a to be picked up automatically when\n/// is used to create an , or added into a .\n/// \n/// \n/// Most commonly, instances are created using the static methods.\n/// These methods enable creating an for a method, specified via a or \n/// , and are what are used implicitly by WithResourcesFromAssembly and\n/// . The methods\n/// create instances capable of working with a large variety of .NET method signatures, automatically handling\n/// how parameters are marshaled into the method from the URI received from the MCP client, and how the return value is marshaled back\n/// into the that's then serialized and sent back to the client.\n/// \n/// \n/// is used to represent both direct resources (e.g. \"resource://example\") and templated\n/// resources (e.g. \"resource://example/{id}\").\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \npublic abstract class McpServerResource : IMcpServerPrimitive\n{\n /// Initializes a new instance of the class.\n protected McpServerResource()\n {\n }\n\n /// Gets whether this resource is a URI template with parameters as opposed to a direct resource.\n public bool IsTemplated => ProtocolResourceTemplate.UriTemplate.Contains('{');\n\n /// Gets the protocol type for this instance.\n /// \n /// \n /// The property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n /// \n /// Every valid resource URI is a valid resource URI template, and thus this property always returns an instance.\n /// In contrast, the property may return if the resource template\n /// contains a parameter, in which case the resource template URI is not a valid resource URI.\n /// \n /// \n public abstract ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the protocol type for this instance.\n /// \n /// The ProtocolResourceTemplate property represents the underlying resource template definition as defined in the\n /// Model Context Protocol specification. It contains metadata like the resource templates's URI template, name, and description.\n /// \n public virtual Resource? ProtocolResource => ProtocolResourceTemplate.AsResource();\n\n /// \n /// Gets the resource, rendering it with the provided request parameters and returning the resource result.\n /// \n /// \n /// The request context containing information about the resource invocation, including any arguments\n /// passed to the resource. This object provides access to both the request parameters and the server context.\n /// \n /// \n /// The to monitor for cancellation requests. The default is .\n /// \n /// \n /// A representing the asynchronous operation, containing a with\n /// the resource content and messages. If and only if this doesn't match the ,\n /// the method returns .\n /// \n /// is .\n /// The resource implementation returned or an unsupported result type.\n public abstract ValueTask ReadAsync(\n RequestContext request,\n CancellationToken cancellationToken = default);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n Delegate method,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, options);\n\n /// \n /// Creates an instance for a method, specified via a instance.\n /// \n /// The method to be represented via the created .\n /// The instance if is an instance method; otherwise, .\n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n /// is an instance method but is .\n public static McpServerResource Create(\n MethodInfo method, \n object? target = null,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, target, options);\n\n /// \n /// Creates an instance for a method, specified via an for\n /// and instance method, along with a representing the type of the target object to\n /// instantiate each time the method is invoked.\n /// \n /// The instance method to be represented via the created .\n /// \n /// Callback used on each function invocation to create an instance of the type on which the instance method \n /// will be invoked. If the returned instance is or , it will\n /// be disposed of after method completes its invocation.\n /// \n /// Optional options used in the creation of the to control its behavior.\n /// The created for invoking .\n /// is .\n public static McpServerResource Create(\n MethodInfo method,\n Func, object> createTargetFunc,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(method, createTargetFunc, options);\n\n /// Creates an that wraps the specified .\n /// The function to wrap.\n /// Optional options used in the creation of the to control its behavior.\n /// is .\n /// \n /// Unlike the other overloads of Create, the created by \n /// does not provide all of the special parameter handling for MCP-specific concepts, like .\n /// \n public static McpServerResource Create(\n AIFunction function,\n McpServerResourceCreateOptions? options = null) =>\n AIFunctionMcpServerResource.Create(function, options);\n\n /// \n public override string ToString() => ProtocolResourceTemplate.UriTemplate;\n\n /// \n string IMcpServerPrimitive.Id => ProtocolResourceTemplate.UriTemplate;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/RequestContext.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Provides a context container that provides access to the client request parameters and resources for the request.\n/// \n/// Type of the request parameters specific to each MCP operation.\n/// \n/// The encapsulates all contextual information for handling an MCP request.\n/// This type is typically received as a parameter in handler delegates registered with IMcpServerBuilder,\n/// and may be injected as parameters into s.\n/// \npublic sealed class RequestContext\n{\n /// The server with which this instance is associated.\n private IMcpServer _server;\n\n /// \n /// Initializes a new instance of the class with the specified server.\n /// \n /// The server with which this instance is associated.\n public RequestContext(IMcpServer server)\n {\n Throw.IfNull(server);\n\n _server = server;\n Services = server.Services;\n }\n\n /// Gets or sets the server with which this instance is associated.\n public IMcpServer Server \n {\n get => _server;\n set\n {\n Throw.IfNull(value);\n _server = value;\n }\n }\n\n /// Gets or sets the services associated with this request.\n /// \n /// This may not be the same instance stored in \n /// if was true, in which case this\n /// might be a scoped derived from the server's\n /// .\n /// \n public IServiceProvider? Services { get; set; }\n\n /// Gets or sets the parameters associated with this request.\n public TParams? Params { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as tools in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as tools that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs, and are represented in the JSON schema for the function, as exposed in the returned 's\n/// 's . Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// . The parameter is not included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request,\n/// and are not included in the JSON schema.\n/// \n/// \n/// \n/// \n/// parameters are not included in the JSON schema and are bound directly to the \n/// instance associated with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are not included in the JSON schema and are bound to an instance manufactured\n/// to forward progress notifications from the tool to the client. If the client included a in their request, \n/// progress reports issued to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will not be included in the generated JSON schema and will be resolved \n/// from the provided to when the tool is invoked rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided when the tool is invoked rather than from the argument\n/// collection, and will not be included in the generated JSON schema.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary, \n/// using the supplied in , or if none was provided, \n/// using .\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the tool, consider having \n/// the tool be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Returns an empty list.\n/// \n/// \n/// \n/// Converted to a single object using .\n/// \n/// \n/// \n/// Converted to a single object with its text set to the string value.\n/// \n/// \n/// \n/// Returned as a single-item list.\n/// \n/// \n/// of \n/// Each is converted to a object with its text set to the string value.\n/// \n/// \n/// of \n/// Each is converted to a object using .\n/// \n/// \n/// of \n/// Returned as the list.\n/// \n/// \n/// \n/// Returned directly without modification.\n/// \n/// \n/// Other types\n/// Serialized to JSON and returned as a single object with set to \"text\".\n/// \n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerToolAttribute : Attribute\n{\n // Defaults based on the spec\n private const bool DestructiveDefault = true;\n private const bool IdempotentDefault = false;\n private const bool OpenWorldDefault = true;\n private const bool ReadOnlyDefault = false;\n\n // Nullable backing fields so we can distinguish\n internal bool? _destructive;\n internal bool? _idempotent;\n internal bool? _openWorld;\n internal bool? _readOnly;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerToolAttribute()\n {\n }\n\n /// Gets the name of the tool.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Destructive \n {\n get => _destructive ?? DestructiveDefault; \n set => _destructive = value; \n }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool Idempotent \n {\n get => _idempotent ?? IdempotentDefault;\n set => _idempotent = value; \n }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool OpenWorld\n {\n get => _openWorld ?? OpenWorldDefault; \n set => _openWorld = value; \n }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool ReadOnly \n {\n get => _readOnly ?? ReadOnlyDefault; \n set => _readOnly = value; \n }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/McpEndpointRouteBuilderExtensions.cs", "using Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Metadata;\nusing Microsoft.AspNetCore.Routing;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\n\nnamespace Microsoft.AspNetCore.Builder;\n\n/// \n/// Provides extension methods for to add MCP endpoints.\n/// \npublic static class McpEndpointRouteBuilderExtensions\n{\n /// \n /// Sets up endpoints for handling MCP Streamable HTTP transport.\n /// See the 2025-06-18 protocol specification for details about the Streamable HTTP transport.\n /// Also maps legacy SSE endpoints for backward compatibility at the path \"/sse\" and \"/message\". the 2024-11-05 protocol specification for details about the HTTP with SSE transport.\n /// \n /// The web application to attach MCP HTTP endpoints.\n /// The route pattern prefix to map to.\n /// Returns a builder for configuring additional endpoint conventions like authorization policies.\n public static IEndpointConventionBuilder MapMcp(this IEndpointRouteBuilder endpoints, [StringSyntax(\"Route\")] string pattern = \"\")\n {\n var streamableHttpHandler = endpoints.ServiceProvider.GetService() ??\n throw new InvalidOperationException(\"You must call WithHttpTransport(). Unable to find required services. Call builder.Services.AddMcpServer().WithHttpTransport() in application startup code.\");\n\n var mcpGroup = endpoints.MapGroup(pattern);\n var streamableHttpGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP Streamable HTTP | {b.DisplayName}\")\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status404NotFound, typeof(JsonRpcError), contentTypes: [\"application/json\"]));\n\n streamableHttpGroup.MapPost(\"\", streamableHttpHandler.HandlePostRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n\n if (!streamableHttpHandler.HttpServerTransportOptions.Stateless)\n {\n // The GET and DELETE endpoints are not mapped in Stateless mode since there's no way to send unsolicited messages\n // for the GET to handle, and there is no server-side state for the DELETE to clean up.\n streamableHttpGroup.MapGet(\"\", streamableHttpHandler.HandleGetRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n streamableHttpGroup.MapDelete(\"\", streamableHttpHandler.HandleDeleteRequestAsync);\n\n // Map legacy HTTP with SSE endpoints only if not in Stateless mode, because we cannot guarantee the /message requests\n // will be handled by the same process as the /sse request.\n var sseHandler = endpoints.ServiceProvider.GetRequiredService();\n var sseGroup = mcpGroup.MapGroup(\"\")\n .WithDisplayName(b => $\"MCP HTTP with SSE | {b.DisplayName}\");\n\n sseGroup.MapGet(\"/sse\", sseHandler.HandleSseRequestAsync)\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, contentTypes: [\"text/event-stream\"]));\n sseGroup.MapPost(\"/message\", sseHandler.HandleMessageRequestAsync)\n .WithMetadata(new AcceptsMetadata([\"application/json\"]))\n .WithMetadata(new ProducesResponseTypeMetadata(StatusCodes.Status202Accepted));\n }\n\n return mcpGroup;\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Program.cs", "using EverythingServer;\nusing EverythingServer.Prompts;\nusing EverythingServer.Resources;\nusing EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Resources;\nusing OpenTelemetry.Trace;\n\nvar builder = Host.CreateApplicationBuilder(args);\nbuilder.Logging.AddConsole(consoleLogOptions =>\n{\n // Configure all logs to go to stderr\n consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nHashSet subscriptions = [];\nvar _minimumLoggingLevel = LoggingLevel.Debug;\n\nbuilder.Services\n .AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithTools()\n .WithPrompts()\n .WithPrompts()\n .WithResources()\n .WithSubscribeToResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n\n if (uri is not null)\n {\n subscriptions.Add(uri);\n\n await ctx.Server.SampleAsync([\n new ChatMessage(ChatRole.System, \"You are a helpful test server\"),\n new ChatMessage(ChatRole.User, $\"Resource {uri}, context: A new subscription was started\"),\n ],\n options: new ChatOptions\n {\n MaxOutputTokens = 100,\n Temperature = 0.7f,\n },\n cancellationToken: ct);\n }\n\n return new EmptyResult();\n })\n .WithUnsubscribeFromResourcesHandler(async (ctx, ct) =>\n {\n var uri = ctx.Params?.Uri;\n if (uri is not null)\n {\n subscriptions.Remove(uri);\n }\n return new EmptyResult();\n })\n .WithCompleteHandler(async (ctx, ct) =>\n {\n var exampleCompletions = new Dictionary>\n {\n { \"style\", [\"casual\", \"formal\", \"technical\", \"friendly\"] },\n { \"temperature\", [\"0\", \"0.5\", \"0.7\", \"1.0\"] },\n { \"resourceId\", [\"1\", \"2\", \"3\", \"4\", \"5\"] }\n };\n\n if (ctx.Params is not { } @params)\n {\n throw new NotSupportedException($\"Params are required.\");\n }\n\n var @ref = @params.Ref;\n var argument = @params.Argument;\n\n if (@ref is ResourceTemplateReference rtr)\n {\n var resourceId = rtr.Uri?.Split(\"/\").Last();\n\n if (resourceId is null)\n {\n return new CompleteResult();\n }\n\n var values = exampleCompletions[\"resourceId\"].Where(id => id.StartsWith(argument.Value));\n\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n if (@ref is PromptReference pr)\n {\n if (!exampleCompletions.TryGetValue(argument.Name, out IEnumerable? value))\n {\n throw new NotSupportedException($\"Unknown argument name: {argument.Name}\");\n }\n\n var values = value.Where(value => value.StartsWith(argument.Value));\n return new CompleteResult\n {\n Completion = new Completion { Values = [.. values], HasMore = false, Total = values.Count() }\n };\n }\n\n throw new NotSupportedException($\"Unknown reference type: {@ref.Type}\");\n })\n .WithSetLoggingLevelHandler(async (ctx, ct) =>\n {\n if (ctx.Params?.Level is null)\n {\n throw new McpException(\"Missing required argument 'level'\", McpErrorCode.InvalidParams);\n }\n\n _minimumLoggingLevel = ctx.Params.Level;\n\n await ctx.Server.SendNotificationAsync(\"notifications/message\", new\n {\n Level = \"debug\",\n Logger = \"test-server\",\n Data = $\"Logging level set to {_minimumLoggingLevel}\",\n }, cancellationToken: ct);\n\n return new EmptyResult();\n });\n\nResourceBuilder resource = ResourceBuilder.CreateDefault().AddService(\"everything-server\");\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithMetrics(b => b.AddMeter(\"*\").AddHttpClientInstrumentation().SetResourceBuilder(resource))\n .WithLogging(b => b.SetResourceBuilder(resource))\n .UseOtlpExporter();\n\nbuilder.Services.AddSingleton(subscriptions);\nbuilder.Services.AddHostedService();\nbuilder.Services.AddHostedService();\n\nbuilder.Services.AddSingleton>(_ => () => _minimumLoggingLevel);\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for all request parameters.\n/// \n/// \n/// See the schema for details.\n/// \npublic abstract class RequestParams\n{\n /// Prevent external derivations.\n private protected RequestParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n [JsonIgnore]\n public ProgressToken? ProgressToken\n {\n get\n {\n if (Meta?[\"progressToken\"] is JsonValue progressToken)\n {\n if (progressToken.TryGetValue(out string? stringValue))\n {\n return new ProgressToken(stringValue);\n }\n\n if (progressToken.TryGetValue(out long longValue))\n {\n return new ProgressToken(longValue);\n }\n }\n\n return null;\n }\n set\n {\n if (value is null)\n {\n Meta?.Remove(\"progressToken\");\n }\n else\n {\n (Meta ??= [])[\"progressToken\"] = value.Value.Token switch\n {\n string s => JsonValue.Create(s),\n long l => JsonValue.Create(l),\n _ => throw new InvalidOperationException(\"ProgressToken must be a string or a long.\")\n };\n }\n }\n }\n}\n"], ["/csharp-sdk/samples/ProtectedMCPClient/Program.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Net;\nusing System.Text;\nusing System.Web;\n\nvar serverUrl = \"http://localhost:7071/\";\n\nConsole.WriteLine(\"Protected MCP Client\");\nConsole.WriteLine($\"Connecting to weather server at {serverUrl}...\");\nConsole.WriteLine();\n\n// We can customize a shared HttpClient with a custom handler if desired\nvar sharedHandler = new SocketsHttpHandler\n{\n PooledConnectionLifetime = TimeSpan.FromMinutes(2),\n PooledConnectionIdleTimeout = TimeSpan.FromMinutes(1)\n};\nvar httpClient = new HttpClient(sharedHandler);\n\nvar consoleLoggerFactory = LoggerFactory.Create(builder =>\n{\n builder.AddConsole();\n});\n\nvar transport = new SseClientTransport(new()\n{\n Endpoint = new Uri(serverUrl),\n Name = \"Secure Weather Client\",\n OAuth = new()\n {\n ClientName = \"ProtectedMcpClient\",\n RedirectUri = new Uri(\"http://localhost:1179/callback\"),\n AuthorizationRedirectDelegate = HandleAuthorizationUrlAsync,\n }\n}, httpClient, consoleLoggerFactory);\n\nvar client = await McpClientFactory.CreateAsync(transport, loggerFactory: consoleLoggerFactory);\n\nvar tools = await client.ListToolsAsync();\nif (tools.Count == 0)\n{\n Console.WriteLine(\"No tools available on the server.\");\n return;\n}\n\nConsole.WriteLine($\"Found {tools.Count} tools on the server.\");\nConsole.WriteLine();\n\nif (tools.Any(t => t.Name == \"get_alerts\"))\n{\n Console.WriteLine(\"Calling get_alerts tool...\");\n\n var result = await client.CallToolAsync(\n \"get_alerts\",\n new Dictionary { { \"state\", \"WA\" } }\n );\n\n Console.WriteLine(\"Result: \" + ((TextContentBlock)result.Content[0]).Text);\n Console.WriteLine();\n}\n\n/// Handles the OAuth authorization URL by starting a local HTTP server and opening a browser.\n/// This implementation demonstrates how SDK consumers can provide their own authorization flow.\n/// \n/// The authorization URL to open in the browser.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// The authorization code extracted from the callback, or null if the operation failed.\nstatic async Task HandleAuthorizationUrlAsync(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken)\n{\n Console.WriteLine(\"Starting OAuth authorization flow...\");\n Console.WriteLine($\"Opening browser to: {authorizationUrl}\");\n\n var listenerPrefix = redirectUri.GetLeftPart(UriPartial.Authority);\n if (!listenerPrefix.EndsWith(\"/\")) listenerPrefix += \"/\";\n\n using var listener = new HttpListener();\n listener.Prefixes.Add(listenerPrefix);\n\n try\n {\n listener.Start();\n Console.WriteLine($\"Listening for OAuth callback on: {listenerPrefix}\");\n\n OpenBrowser(authorizationUrl);\n\n var context = await listener.GetContextAsync();\n var query = HttpUtility.ParseQueryString(context.Request.Url?.Query ?? string.Empty);\n var code = query[\"code\"];\n var error = query[\"error\"];\n\n string responseHtml = \"

Authentication complete

You can close this window now.

\";\n byte[] buffer = Encoding.UTF8.GetBytes(responseHtml);\n context.Response.ContentLength64 = buffer.Length;\n context.Response.ContentType = \"text/html\";\n context.Response.OutputStream.Write(buffer, 0, buffer.Length);\n context.Response.Close();\n\n if (!string.IsNullOrEmpty(error))\n {\n Console.WriteLine($\"Auth error: {error}\");\n return null;\n }\n\n if (string.IsNullOrEmpty(code))\n {\n Console.WriteLine(\"No authorization code received\");\n return null;\n }\n\n Console.WriteLine(\"Authorization code received successfully.\");\n return code;\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error getting auth code: {ex.Message}\");\n return null;\n }\n finally\n {\n if (listener.IsListening) listener.Stop();\n }\n}\n\n/// \n/// Opens the specified URL in the default browser.\n/// \n/// The URL to open.\nstatic void OpenBrowser(Uri url)\n{\n try\n {\n var psi = new ProcessStartInfo\n {\n FileName = url.ToString(),\n UseShellExecute = true\n };\n Process.Start(psi);\n }\n catch (Exception ex)\n {\n Console.WriteLine($\"Error opening browser. {ex.Message}\");\n Console.WriteLine($\"Please manually open this URL: {url}\");\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/SemaphoreSlimExtensions.cs", "namespace ModelContextProtocol;\n\ninternal static class SynchronizationExtensions\n{\n /// \n /// Asynchronously acquires a lock on the semaphore and returns a disposable object that releases the lock when disposed.\n /// \n /// The semaphore to acquire a lock on.\n /// A cancellation token to observe while waiting for the semaphore.\n /// A disposable that releases the semaphore when disposed.\n /// \n /// This extension method provides a convenient pattern for using a semaphore in asynchronous code,\n /// similar to how the `lock` statement is used in synchronous code.\n /// \n /// The was canceled.\n public static async ValueTask LockAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default)\n {\n await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);\n return new(semaphore);\n }\n\n /// \n /// A disposable struct that releases a semaphore when disposed.\n /// \n /// \n /// This struct is used with the extension method to provide\n /// a using-pattern for semaphore locking, similar to lock statements.\n /// \n public readonly struct Releaser(SemaphoreSlim semaphore) : IDisposable\n {\n /// \n /// Releases the semaphore.\n /// \n /// \n /// This method is called automatically when the goes out of scope\n /// in a using statement or expression.\n /// \n public void Dispose() => semaphore.Release();\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StreamClientTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides an implemented around a pair of input/output streams.\n/// \n/// \n/// This transport is useful for scenarios where you already have established streams for communication,\n/// such as custom network protocols, pipe connections, or for testing purposes. It works with any\n/// readable and writable streams.\n/// \npublic sealed class StreamClientTransport : IClientTransport\n{\n private readonly Stream _serverInput;\n private readonly Stream _serverOutput;\n private readonly ILoggerFactory? _loggerFactory;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The stream representing the connected server's input. \n /// Writes to this stream will be sent to the server.\n /// \n /// \n /// The stream representing the connected server's output.\n /// Reads from this stream will receive messages from the server.\n /// \n /// A logger factory for creating loggers.\n public StreamClientTransport(\n Stream serverInput, Stream serverOutput, ILoggerFactory? loggerFactory = null)\n {\n Throw.IfNull(serverInput);\n Throw.IfNull(serverOutput);\n\n _serverInput = serverInput;\n _serverOutput = serverOutput;\n _loggerFactory = loggerFactory;\n }\n\n /// \n public string Name => \"in-memory-stream\";\n\n /// \n public Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n return Task.FromResult(new StreamClientSessionTransport(\n _serverInput,\n _serverOutput,\n encoding: null,\n \"Client (stream)\",\n _loggerFactory));\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/NullableAttributes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n /// Specifies that null is allowed as an input even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class AllowNullAttribute : Attribute;\n\n /// Specifies that null is disallowed as an input even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)]\n internal sealed class DisallowNullAttribute : Attribute;\n\n /// Specifies that an output may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class MaybeNullAttribute : Attribute;\n\n /// Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns.\n [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)]\n internal sealed class NotNullAttribute : Attribute;\n\n /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class MaybeNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter may be null.\n /// \n public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class NotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition.\n /// \n /// The return value condition. If the method returns this value, the associated parameter will not be null.\n /// \n public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n }\n\n /// Specifies that the output will be non-null if the named parameter is non-null.\n [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]\n internal sealed class NotNullIfNotNullAttribute : Attribute\n {\n /// Initializes the attribute with the associated parameter name.\n /// \n /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null.\n /// \n public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName;\n\n /// Gets the associated parameter name.\n public string ParameterName { get; }\n }\n\n /// Applied to a method that will never return under any circumstance.\n [AttributeUsage(AttributeTargets.Method, Inherited = false)]\n internal sealed class DoesNotReturnAttribute : Attribute;\n\n /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value.\n [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]\n internal sealed class DoesNotReturnIfAttribute : Attribute\n {\n /// Initializes the attribute with the specified parameter value.\n /// \n /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to\n /// the associated parameter matches this value.\n /// \n public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue;\n\n /// Gets the condition parameter value.\n public bool ParameterValue { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullAttribute : Attribute\n {\n /// Initializes the attribute with a field or property member.\n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullAttribute(string member) => Members = [member];\n\n /// Initializes the attribute with the list of field and property members.\n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullAttribute(params string[] members) => Members = members;\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n\n /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition.\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]\n internal sealed class MemberNotNullWhenAttribute : Attribute\n {\n /// Initializes the attribute with the specified return value condition and a field or property member.\n /// \n /// The return value condition. If the method returns this value, the associated field or property member will not be null.\n /// \n /// \n /// The field or property member that is promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, string member)\n {\n ReturnValue = returnValue;\n Members = [member];\n }\n\n /// Initializes the attribute with the specified return value condition and list of field and property members.\n /// \n /// The return value condition. If the method returns this value, the associated field and property members will not be null.\n /// \n /// \n /// The list of field and property members that are promised to be not-null.\n /// \n public MemberNotNullWhenAttribute(bool returnValue, params string[] members)\n {\n ReturnValue = returnValue;\n Members = members;\n }\n\n /// Gets the return value condition.\n public bool ReturnValue { get; }\n\n /// Gets field or property member names.\n public string[] Members { get; }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpJsonUtilities.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Authentication;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol;\n\n/// Provides a collection of utility methods for working with JSON data in the context of MCP.\npublic static partial class McpJsonUtilities\n{\n /// \n /// Gets the singleton used as the default in JSON serialization operations.\n /// \n /// \n /// \n /// For Native AOT or applications disabling , this instance \n /// includes source generated contracts for all common exchange types contained in the ModelContextProtocol library.\n /// \n /// \n /// It additionally turns on the following settings:\n /// \n /// Enables defaults.\n /// Enables as the default ignore condition for properties.\n /// Enables as the default number handling for number types.\n /// \n /// \n /// \n public static JsonSerializerOptions DefaultOptions { get; } = CreateDefaultOptions();\n\n /// \n /// Creates default options to use for MCP-related serialization.\n /// \n /// The configured options.\n [UnconditionalSuppressMessage(\"ReflectionAnalysis\", \"IL3050:RequiresDynamicCode\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n [UnconditionalSuppressMessage(\"Trimming\", \"IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access\", Justification = \"Converter is guarded by IsReflectionEnabledByDefault check.\")]\n private static JsonSerializerOptions CreateDefaultOptions()\n {\n // Copy the configuration from the source generated context.\n JsonSerializerOptions options = new(JsonContext.Default.Options);\n\n // Chain with all supported types from MEAI.\n options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);\n\n // Add a converter for user-defined enums, if reflection is enabled by default.\n if (JsonSerializer.IsReflectionEnabledByDefault)\n {\n options.Converters.Add(new CustomizableJsonStringEnumConverter());\n }\n\n options.MakeReadOnly();\n return options;\n }\n\n internal static JsonTypeInfo GetTypeInfo(this JsonSerializerOptions options) =>\n (JsonTypeInfo)options.GetTypeInfo(typeof(T));\n\n internal static JsonElement DefaultMcpToolSchema { get; } = ParseJsonElement(\"\"\"{\"type\":\"object\"}\"\"\"u8);\n internal static object? AsObject(this JsonElement element) => element.ValueKind is JsonValueKind.Null ? null : element;\n\n internal static bool IsValidMcpToolSchema(JsonElement element)\n {\n if (element.ValueKind is not JsonValueKind.Object)\n {\n return false;\n }\n\n foreach (JsonProperty property in element.EnumerateObject())\n {\n if (property.NameEquals(\"type\"))\n {\n if (property.Value.ValueKind is not JsonValueKind.String ||\n !property.Value.ValueEquals(\"object\"))\n {\n return false;\n }\n\n return true; // No need to check other properties\n }\n }\n\n return false; // No type keyword found.\n }\n\n // Keep in sync with CreateDefaultOptions above.\n [JsonSourceGenerationOptions(JsonSerializerDefaults.Web,\n DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n NumberHandling = JsonNumberHandling.AllowReadingFromString)]\n \n // JSON-RPC\n [JsonSerializable(typeof(JsonRpcMessage))]\n [JsonSerializable(typeof(JsonRpcMessage[]))]\n [JsonSerializable(typeof(JsonRpcRequest))]\n [JsonSerializable(typeof(JsonRpcNotification))]\n [JsonSerializable(typeof(JsonRpcResponse))]\n [JsonSerializable(typeof(JsonRpcError))]\n\n // MCP Notification Params\n [JsonSerializable(typeof(CancelledNotificationParams))]\n [JsonSerializable(typeof(InitializedNotificationParams))]\n [JsonSerializable(typeof(LoggingMessageNotificationParams))]\n [JsonSerializable(typeof(ProgressNotificationParams))]\n [JsonSerializable(typeof(PromptListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceListChangedNotificationParams))]\n [JsonSerializable(typeof(ResourceUpdatedNotificationParams))]\n [JsonSerializable(typeof(RootsListChangedNotificationParams))]\n [JsonSerializable(typeof(ToolListChangedNotificationParams))]\n\n // MCP Request Params / Results\n [JsonSerializable(typeof(CallToolRequestParams))]\n [JsonSerializable(typeof(CallToolResult))]\n [JsonSerializable(typeof(CompleteRequestParams))]\n [JsonSerializable(typeof(CompleteResult))]\n [JsonSerializable(typeof(CreateMessageRequestParams))]\n [JsonSerializable(typeof(CreateMessageResult))]\n [JsonSerializable(typeof(ElicitRequestParams))]\n [JsonSerializable(typeof(ElicitResult))]\n [JsonSerializable(typeof(EmptyResult))]\n [JsonSerializable(typeof(GetPromptRequestParams))]\n [JsonSerializable(typeof(GetPromptResult))]\n [JsonSerializable(typeof(InitializeRequestParams))]\n [JsonSerializable(typeof(InitializeResult))]\n [JsonSerializable(typeof(ListPromptsRequestParams))]\n [JsonSerializable(typeof(ListPromptsResult))]\n [JsonSerializable(typeof(ListResourcesRequestParams))]\n [JsonSerializable(typeof(ListResourcesResult))]\n [JsonSerializable(typeof(ListResourceTemplatesRequestParams))]\n [JsonSerializable(typeof(ListResourceTemplatesResult))]\n [JsonSerializable(typeof(ListRootsRequestParams))]\n [JsonSerializable(typeof(ListRootsResult))]\n [JsonSerializable(typeof(ListToolsRequestParams))]\n [JsonSerializable(typeof(ListToolsResult))]\n [JsonSerializable(typeof(PingResult))]\n [JsonSerializable(typeof(ReadResourceRequestParams))]\n [JsonSerializable(typeof(ReadResourceResult))]\n [JsonSerializable(typeof(SetLevelRequestParams))]\n [JsonSerializable(typeof(SubscribeRequestParams))]\n [JsonSerializable(typeof(UnsubscribeRequestParams))]\n\n // MCP Content\n [JsonSerializable(typeof(ContentBlock))]\n [JsonSerializable(typeof(TextContentBlock))]\n [JsonSerializable(typeof(ImageContentBlock))]\n [JsonSerializable(typeof(AudioContentBlock))]\n [JsonSerializable(typeof(EmbeddedResourceBlock))]\n [JsonSerializable(typeof(ResourceLinkBlock))]\n [JsonSerializable(typeof(PromptReference))]\n [JsonSerializable(typeof(ResourceTemplateReference))]\n [JsonSerializable(typeof(BlobResourceContents))]\n [JsonSerializable(typeof(TextResourceContents))]\n\n // Other MCP Types\n [JsonSerializable(typeof(IReadOnlyDictionary))]\n [JsonSerializable(typeof(ProgressToken))]\n\n [JsonSerializable(typeof(ProtectedResourceMetadata))]\n [JsonSerializable(typeof(AuthorizationServerMetadata))]\n [JsonSerializable(typeof(TokenContainer))]\n [JsonSerializable(typeof(DynamicClientRegistrationRequest))]\n [JsonSerializable(typeof(DynamicClientRegistrationResponse))]\n\n // Primitive types for use in consuming AIFunctions\n [JsonSerializable(typeof(string))]\n [JsonSerializable(typeof(byte))]\n [JsonSerializable(typeof(byte?))]\n [JsonSerializable(typeof(sbyte))]\n [JsonSerializable(typeof(sbyte?))]\n [JsonSerializable(typeof(ushort))]\n [JsonSerializable(typeof(ushort?))]\n [JsonSerializable(typeof(short))]\n [JsonSerializable(typeof(short?))]\n [JsonSerializable(typeof(uint))]\n [JsonSerializable(typeof(uint?))]\n [JsonSerializable(typeof(int))]\n [JsonSerializable(typeof(int?))]\n [JsonSerializable(typeof(ulong))]\n [JsonSerializable(typeof(ulong?))]\n [JsonSerializable(typeof(long))]\n [JsonSerializable(typeof(long?))]\n [JsonSerializable(typeof(nuint))]\n [JsonSerializable(typeof(nuint?))]\n [JsonSerializable(typeof(nint))]\n [JsonSerializable(typeof(nint?))]\n [JsonSerializable(typeof(bool))]\n [JsonSerializable(typeof(bool?))]\n [JsonSerializable(typeof(char))]\n [JsonSerializable(typeof(char?))]\n [JsonSerializable(typeof(float))]\n [JsonSerializable(typeof(float?))]\n [JsonSerializable(typeof(double))]\n [JsonSerializable(typeof(double?))]\n [JsonSerializable(typeof(decimal))]\n [JsonSerializable(typeof(decimal?))]\n [JsonSerializable(typeof(Guid))]\n [JsonSerializable(typeof(Guid?))]\n [JsonSerializable(typeof(Uri))]\n [JsonSerializable(typeof(Version))]\n [JsonSerializable(typeof(TimeSpan))]\n [JsonSerializable(typeof(TimeSpan?))]\n [JsonSerializable(typeof(DateTime))]\n [JsonSerializable(typeof(DateTime?))]\n [JsonSerializable(typeof(DateTimeOffset))]\n [JsonSerializable(typeof(DateTimeOffset?))]\n#if NET\n [JsonSerializable(typeof(DateOnly))]\n [JsonSerializable(typeof(DateOnly?))]\n [JsonSerializable(typeof(TimeOnly))]\n [JsonSerializable(typeof(TimeOnly?))]\n [JsonSerializable(typeof(Half))]\n [JsonSerializable(typeof(Half?))]\n [JsonSerializable(typeof(Int128))]\n [JsonSerializable(typeof(Int128?))]\n [JsonSerializable(typeof(UInt128))]\n [JsonSerializable(typeof(UInt128?))]\n#endif\n\n [ExcludeFromCodeCoverage]\n internal sealed partial class JsonContext : JsonSerializerContext;\n\n private static JsonElement ParseJsonElement(ReadOnlySpan utf8Json)\n {\n Utf8JsonReader reader = new(utf8Json);\n return JsonElement.ParseValue(ref reader);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's capability to provide predefined prompt templates that clients can use.\n/// \n/// \n/// \n/// The prompts capability allows a server to expose a collection of predefined prompt templates that clients\n/// can discover and use. These prompts can be static (defined in the ) or\n/// dynamically generated through handlers.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the prompt list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when prompts are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their prompt cache. This capability enables clients to stay synchronized with server-side changes \n /// to available prompts.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client requests a list of available prompts from the server\n /// via a request. Results from this handler are returned\n /// along with any prompts defined in .\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListPromptsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// \n /// This handler is invoked when a client requests details for a specific prompt by name and provides arguments \n /// for the prompt if needed. The handler receives the request context containing the prompt name and any arguments, \n /// and should return a with the prompt messages and other details.\n /// \n /// \n /// This handler will be invoked if the requested prompt name is not found in the ,\n /// allowing for dynamic prompt generation or retrieval from external sources.\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? GetPromptHandler { get; set; }\n\n /// \n /// Gets or sets a collection of prompts that will be served by the server.\n /// \n /// \n /// \n /// The contains the predefined prompts that clients can request from the server.\n /// This collection works in conjunction with and \n /// when those are provided:\n /// \n /// \n /// - For requests: The server returns all prompts from this collection \n /// plus any additional prompts provided by the if it's set.\n /// \n /// \n /// - For requests: The server first checks this collection for the requested prompt.\n /// If not found, it will invoke the as a fallback if one is set.\n /// \n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? PromptCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/SseClientTransportOptions.cs", "using ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class SseClientTransportOptions\n{\n /// \n /// Gets or sets the base address of the server for SSE connections.\n /// \n public required Uri Endpoint\n {\n get;\n set\n {\n if (value is null)\n {\n throw new ArgumentNullException(nameof(value), \"Endpoint cannot be null.\");\n }\n if (!value.IsAbsoluteUri)\n {\n throw new ArgumentException(\"Endpoint must be an absolute URI.\", nameof(value));\n }\n if (value.Scheme != Uri.UriSchemeHttp && value.Scheme != Uri.UriSchemeHttps)\n {\n throw new ArgumentException(\"Endpoint must use HTTP or HTTPS scheme.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the transport mode to use for the connection. Defaults to .\n /// \n /// \n /// \n /// When set to (the default), the client will first attempt to use\n /// Streamable HTTP transport and automatically fall back to SSE transport if the server doesn't support it.\n /// \n /// \n /// Streamable HTTP transport specification.\n /// HTTP with SSE transport specification.\n /// \n /// \n public HttpTransportMode TransportMode { get; set; } = HttpTransportMode.AutoDetect;\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets a timeout used to establish the initial connection to the SSE server. Defaults to 30 seconds.\n /// \n /// \n /// This timeout controls how long the client waits for:\n /// \n /// The initial HTTP connection to be established with the SSE server\n /// The endpoint event to be received, which indicates the message endpoint URL\n /// \n /// If the timeout expires before the connection is established, a will be thrown.\n /// \n public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);\n\n /// \n /// Gets custom HTTP headers to include in requests to the SSE server.\n /// \n /// \n /// Use this property to specify custom HTTP headers that should be sent with each request to the server.\n /// \n public IDictionary? AdditionalHeaders { get; set; }\n\n /// \n /// Gets sor sets the authorization provider to use for authentication.\n /// \n public ClientOAuthOptions? OAuth { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DestinationBoundMcpServer.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol.Server;\n\ninternal sealed class DestinationBoundMcpServer(McpServer server, ITransport? transport) : IMcpServer\n{\n public string EndpointName => server.EndpointName;\n public string? SessionId => transport?.SessionId ?? server.SessionId;\n public ClientCapabilities? ClientCapabilities => server.ClientCapabilities;\n public Implementation? ClientInfo => server.ClientInfo;\n public McpServerOptions ServerOptions => server.ServerOptions;\n public IServiceProvider? Services => server.Services;\n public LoggingLevel? LoggingLevel => server.LoggingLevel;\n\n public ValueTask DisposeAsync() => server.DisposeAsync();\n\n public IAsyncDisposable RegisterNotificationHandler(string method, Func handler) => server.RegisterNotificationHandler(method, handler);\n\n // This will throw because the server must already be running for this class to be constructed, but it should give us a good Exception message.\n public Task RunAsync(CancellationToken cancellationToken) => server.RunAsync(cancellationToken);\n\n public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Debug.Assert(message.RelatedTransport is null);\n message.RelatedTransport = transport;\n return server.SendMessageAsync(message, cancellationToken);\n }\n\n public Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)\n {\n Debug.Assert(request.RelatedTransport is null);\n request.RelatedTransport = transport;\n return server.SendRequestAsync(request, cancellationToken);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourcesCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the resources capability configuration.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ResourcesCapability\n{\n /// \n /// Gets or sets whether this server supports subscribing to resource updates.\n /// \n [JsonPropertyName(\"subscribe\")]\n public bool? Subscribe { get; set; }\n\n /// \n /// Gets or sets whether this server supports notifications for changes to the resource list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when resources are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their resource cache.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is called when clients request available resource templates that can be used\n /// to create resources within the Model Context Protocol server.\n /// Resource templates define the structure and URI patterns for resources accessible in the system,\n /// allowing clients to discover available resource types and their access patterns.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourceTemplatesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler responds to client requests for available resources and returns information about resources accessible through the server.\n /// The implementation should return a with the matching resources.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is responsible for retrieving the content of a specific resource identified by its URI in the Model Context Protocol.\n /// When a client sends a resources/read request, this handler is invoked with the resource URI.\n /// The handler should implement logic to locate and retrieve the requested resource, then return\n /// its contents in a ReadResourceResult object.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ReadResourceHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be subscribed to. The implementation should register the client's interest in receiving updates\n /// for the specified resource.\n /// Subscriptions allow clients to receive real-time notifications when resources change, without\n /// requiring polling.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SubscribeToResourcesHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// When a client sends a request, this handler is invoked with the resource URI\n /// to be unsubscribed from. The implementation should remove the client's registration for receiving updates\n /// about the specified resource.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? UnsubscribeFromResourcesHandler { get; set; }\n\n /// \n /// Gets or sets a collection of resources served by the server.\n /// \n /// \n /// \n /// Resources specified via augment the , \n /// and handlers, if provided. Resources with template expressions in their URI templates are considered resource templates\n /// and are listed via ListResourceTemplate, whereas resources without template parameters are considered static resources and are listed with ListResources.\n /// \n /// \n /// ReadResource requests will first check the for the exact resource being requested. If no match is found, they'll proceed to\n /// try to match the resource against each resource template in . If no match is still found, the request will fall back to\n /// any handler registered for .\n /// \n /// \n [JsonIgnore]\n public McpServerResourceCollection? ResourceCollection { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource defined on an MCP server. It allows\n/// retrieving the resource's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResource\n{\n private readonly IMcpClient _client;\n\n internal McpClientResource(IMcpClient client, Resource resource)\n {\n _client = client;\n ProtocolResource = resource;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public Resource ProtocolResource { get; }\n\n /// Gets the URI of the resource.\n public string Uri => ProtocolResource.Uri;\n\n /// Gets the name of the resource.\n public string Name => ProtocolResource.Name;\n\n /// Gets the title of the resource.\n public string? Title => ProtocolResource.Title;\n\n /// Gets a description of the resource.\n public string? Description => ProtocolResource.Description;\n\n /// Gets a media (MIME) type of the resource.\n public string? MimeType => ProtocolResource.MimeType;\n\n /// \n /// Gets this resource's content by sending a request to the server.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource's result with content and messages.\n /// \n /// \n /// This is a convenience method that internally calls .\n /// \n /// \n public ValueTask ReadAsync(\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(Uri, cancellationToken);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientResourceTemplate.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a named resource template that can be retrieved from an MCP server.\n/// \n/// \n/// \n/// This class provides a client-side wrapper around a resource template defined on an MCP server. It allows\n/// retrieving the resource template's content by sending a request to the server with the resource's URI.\n/// Instances of this class are typically obtained by calling \n/// or .\n/// \n/// \npublic sealed class McpClientResourceTemplate\n{\n private readonly IMcpClient _client;\n\n internal McpClientResourceTemplate(IMcpClient client, ResourceTemplate resourceTemplate)\n {\n _client = client;\n ProtocolResourceTemplate = resourceTemplate;\n }\n\n /// Gets the underlying protocol type for this instance.\n /// \n /// \n /// This property provides direct access to the underlying protocol representation of the resource template,\n /// which can be useful for advanced scenarios or when implementing custom MCP client extensions.\n /// \n /// \n /// For most common use cases, you can use the more convenient and \n /// properties instead of accessing the directly.\n /// \n /// \n public ResourceTemplate ProtocolResourceTemplate { get; }\n\n /// Gets the URI template of the resource template.\n public string UriTemplate => ProtocolResourceTemplate.UriTemplate;\n\n /// Gets the name of the resource template.\n public string Name => ProtocolResourceTemplate.Name;\n\n /// Gets the title of the resource template.\n public string? Title => ProtocolResourceTemplate.Title;\n\n /// Gets a description of the resource template.\n public string? Description => ProtocolResourceTemplate.Description;\n\n /// Gets a media (MIME) type of the resource template.\n public string? MimeType => ProtocolResourceTemplate.MimeType;\n\n /// \n /// Gets this resource template's content by formatting a URI from the template and supplied arguments\n /// and sending a request to the server.\n /// \n /// A dictionary of arguments to pass to the tool. Each key represents a parameter name,\n /// and its associated value represents the argument value.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// A containing the resource template's result with content and messages.\n public ValueTask ReadAsync(\n IReadOnlyDictionary arguments,\n CancellationToken cancellationToken = default) =>\n _client.ReadResourceAsync(UriTemplate, arguments, cancellationToken);\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Tasks/TaskExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class TaskExtensions\n{\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static Task WaitAsync(this Task task, CancellationToken cancellationToken)\n {\n return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n await WaitAsync((Task)task, timeout, cancellationToken).ConfigureAwait(false);\n return task.Result;\n }\n\n public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(task);\n\n if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan)\n {\n throw new ArgumentOutOfRangeException(nameof(timeout));\n }\n\n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n cts.CancelAfter(timeout);\n\n var cancellationTask = new TaskCompletionSource();\n using var _ = cts.Token.Register(tcs => ((TaskCompletionSource)tcs!).TrySetResult(true), cancellationTask);\n await Task.WhenAny(task, cancellationTask.Task).ConfigureAwait(false);\n \n if (!task.IsCompleted)\n {\n cancellationToken.ThrowIfCancellationRequested();\n throw new TimeoutException();\n }\n }\n\n await task.ConfigureAwait(false);\n }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/IO/StreamExtensions.cs", "using ModelContextProtocol;\nusing System.Buffers;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\n#if !NET\nnamespace System.IO;\n\ninternal static class StreamExtensions\n{\n public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return WriteAsyncCore(stream, buffer, cancellationToken);\n\n static async ValueTask WriteAsyncCore(Stream stream, ReadOnlyMemory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n buffer.Span.CopyTo(array);\n await stream.WriteAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n\n public static ValueTask ReadAsync(this Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n Throw.IfNull(stream);\n if (MemoryMarshal.TryGetArray(buffer, out ArraySegment segment))\n {\n return new ValueTask(stream.ReadAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));\n }\n else\n {\n return ReadAsyncCore(stream, buffer, cancellationToken);\n static async ValueTask ReadAsyncCore(Stream stream, Memory buffer, CancellationToken cancellationToken)\n {\n byte[] array = ArrayPool.Shared.Rent(buffer.Length);\n try\n {\n int bytesRead = await stream.ReadAsync(array, 0, buffer.Length, cancellationToken).ConfigureAwait(false);\n array.AsSpan(0, bytesRead).CopyTo(buffer.Span);\n return bytesRead;\n }\n finally\n {\n ArrayPool.Shared.Return(array);\n }\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerTool.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building tools that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner tool instance.\n/// \npublic abstract class DelegatingMcpServerTool : McpServerTool\n{\n private readonly McpServerTool _innerTool;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner tool wrapped by this delegating tool.\n protected DelegatingMcpServerTool(McpServerTool innerTool)\n {\n Throw.IfNull(innerTool);\n _innerTool = innerTool;\n }\n\n /// \n public override Tool ProtocolTool => _innerTool.ProtocolTool;\n\n /// \n public override ValueTask InvokeAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerTool.InvokeAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerTool.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Tool.cs", "using System.Text.Json;\nusing System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a tool that the server is capable of calling.\n/// \npublic sealed class Tool : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the tool.\n /// \n /// \n /// \n /// This description helps the AI model understand what the tool does and when to use it.\n /// It should be clear, concise, and accurately describe the tool's purpose and functionality.\n /// \n /// \n /// The description is typically presented to AI models to help them determine when\n /// and how to use the tool based on user requests.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a JSON Schema object defining the expected parameters for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema typically defines the properties (parameters) that the tool accepts, \n /// their types, and which ones are required. This helps AI models understand\n /// how to structure their calls to the tool.\n /// \n /// \n /// If not explicitly set, a default minimal schema of {\"type\":\"object\"} is used.\n /// \n /// \n [JsonPropertyName(\"inputSchema\")]\n public JsonElement InputSchema \n { \n get => field; \n set\n {\n if (!McpJsonUtilities.IsValidMcpToolSchema(value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool input JSON schema.\", nameof(InputSchema));\n }\n\n field = value;\n }\n\n } = McpJsonUtilities.DefaultMcpToolSchema;\n\n /// \n /// Gets or sets a JSON Schema object defining the expected structured outputs for the tool.\n /// \n /// \n /// \n /// The schema must be a valid JSON Schema object with the \"type\" property set to \"object\".\n /// This is enforced by validation in the setter which will throw an \n /// if an invalid schema is provided.\n /// \n /// \n /// The schema should describe the shape of the data as returned in .\n /// \n /// \n [JsonPropertyName(\"outputSchema\")]\n public JsonElement? OutputSchema\n {\n get => field;\n set\n {\n if (value is not null && !McpJsonUtilities.IsValidMcpToolSchema(value.Value))\n {\n throw new ArgumentException(\"The specified document is not a valid MCP tool output JSON schema.\", nameof(OutputSchema));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets optional additional tool information and behavior hints.\n /// \n /// \n /// These annotations provide metadata about the tool's behavior, such as whether it's read-only,\n /// destructive, idempotent, or operates in an open world. They also can include a human-readable title.\n /// Note that these are hints and should not be relied upon for security decisions.\n /// \n [JsonPropertyName(\"annotations\")]\n public ToolAnnotations? Annotations { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/samples/QuickstartClient/Program.cs", "using Anthropic.SDK;\nusing Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Client;\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Configuration\n .AddEnvironmentVariables()\n .AddUserSecrets();\n\nvar (command, arguments) = GetCommandAndArguments(args);\n\nvar clientTransport = new StdioClientTransport(new()\n{\n Name = \"Demo Server\",\n Command = command,\n Arguments = arguments,\n});\n\nawait using var mcpClient = await McpClientFactory.CreateAsync(clientTransport);\n\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\"Connected to server with tools: {tool.Name}\");\n}\n\nusing var anthropicClient = new AnthropicClient(new APIAuthentication(builder.Configuration[\"ANTHROPIC_API_KEY\"]))\n .Messages\n .AsBuilder()\n .UseFunctionInvocation()\n .Build();\n\nvar options = new ChatOptions\n{\n MaxOutputTokens = 1000,\n ModelId = \"claude-3-5-sonnet-20241022\",\n Tools = [.. tools]\n};\n\nConsole.ForegroundColor = ConsoleColor.Green;\nConsole.WriteLine(\"MCP Client Started!\");\nConsole.ResetColor();\n\nPromptForInput();\nwhile(Console.ReadLine() is string query && !\"exit\".Equals(query, StringComparison.OrdinalIgnoreCase))\n{\n if (string.IsNullOrWhiteSpace(query))\n {\n PromptForInput();\n continue;\n }\n\n await foreach (var message in anthropicClient.GetStreamingResponseAsync(query, options))\n {\n Console.Write(message);\n }\n Console.WriteLine();\n\n PromptForInput();\n}\n\nstatic void PromptForInput()\n{\n Console.WriteLine(\"Enter a command (or 'exit' to quit):\");\n Console.ForegroundColor = ConsoleColor.Cyan;\n Console.Write(\"> \");\n Console.ResetColor();\n}\n\n/// \n/// Determines the command (executable) to run and the script/path to pass to it. This allows different\n/// languages/runtime environments to be used as the MCP server.\n/// \n/// \n/// This method uses the file extension of the first argument to determine the command, if it's py, it'll run python,\n/// if it's js, it'll run node, if it's a directory or a csproj file, it'll run dotnet.\n/// \n/// If no arguments are provided, it defaults to running the QuickstartWeatherServer project from the current repo.\n/// \n/// This method would only be required if you're creating a generic client, such as we use for the quickstart.\n/// \nstatic (string command, string[] arguments) GetCommandAndArguments(string[] args)\n{\n return args switch\n {\n [var script] when script.EndsWith(\".py\") => (\"python\", args),\n [var script] when script.EndsWith(\".js\") => (\"node\", args),\n [var script] when Directory.Exists(script) || (File.Exists(script) && script.EndsWith(\".csproj\")) => (\"dotnet\", [\"run\", \"--project\", script]),\n _ => (\"dotnet\", [\"run\", \"--project\", Path.Combine(GetCurrentSourceDirectory(), \"../QuickstartWeatherServer\")])\n };\n}\n\nstatic string GetCurrentSourceDirectory([CallerFilePath] string? currentFile = null)\n{\n Debug.Assert(!string.IsNullOrWhiteSpace(currentFile));\n return Path.GetDirectoryName(currentFile) ?? throw new InvalidOperationException(\"Unable to determine source directory.\");\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the tools capability configuration.\n/// See the schema for details.\n/// \npublic sealed class ToolsCapability\n{\n /// \n /// Gets or sets whether this server supports notifications for changes to the tool list.\n /// \n /// \n /// When set to , the server will send notifications using \n /// when tools are added, \n /// removed, or modified. Clients can register handlers for these notifications to\n /// refresh their tool cache. This capability enables clients to stay synchronized with server-side \n /// changes to available tools.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// The handler should return a list of available tools when requested by a client.\n /// It supports pagination through the cursor mechanism, where the client can make\n /// repeated calls with the cursor returned by the previous call to retrieve more tools.\n /// When used in conjunction with , both the tools from this handler\n /// and the tools from the collection will be combined to form the complete list of available tools.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? ListToolsHandler { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client makes a call to a tool that isn't found in the .\n /// The handler should implement logic to execute the requested tool and return appropriate results. \n /// It receives a containing information about the tool \n /// being called and its arguments, and should return a with the execution results.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CallToolHandler { get; set; }\n\n /// \n /// Gets or sets a collection of tools served by the server.\n /// \n /// \n /// Tools will specified via augment the and\n /// , if provided. ListTools requests will output information about every tool\n /// in and then also any tools output by , if it's\n /// non-. CallTool requests will first check for the tool\n /// being requested, and if the tool is not found in the , any specified \n /// will be invoked as a fallback.\n /// \n [JsonIgnore]\n public McpServerPrimitiveCollection? ToolCollection { get; set; }\n}"], ["/csharp-sdk/samples/EverythingServer/LoggingUpdateMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\n\nnamespace EverythingServer;\n\npublic class LoggingUpdateMessageSender(IMcpServer server, Func getMinLevel) : BackgroundService\n{\n readonly Dictionary _loggingLevelMap = new()\n {\n { LoggingLevel.Debug, \"Debug-level message\" },\n { LoggingLevel.Info, \"Info-level message\" },\n { LoggingLevel.Notice, \"Notice-level message\" },\n { LoggingLevel.Warning, \"Warning-level message\" },\n { LoggingLevel.Error, \"Error-level message\" },\n { LoggingLevel.Critical, \"Critical-level message\" },\n { LoggingLevel.Alert, \"Alert-level message\" },\n { LoggingLevel.Emergency, \"Emergency-level message\" }\n };\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n var newLevel = (LoggingLevel)Random.Shared.Next(_loggingLevelMap.Count);\n\n var message = new\n {\n Level = newLevel.ToString().ToLower(),\n Data = _loggingLevelMap[newLevel],\n };\n\n if (newLevel > getMinLevel())\n {\n await server.SendNotificationAsync(\"notifications/message\", message, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(15000, stoppingToken);\n }\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Protocol;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of tools created with\n/// . They provide control over naming, description,\n/// tool properties, and dependency injection integration.\n/// \n/// \n/// When creating tools programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerToolCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisfied from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Destructive { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? Idempotent { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? OpenWorld { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool? ReadOnly { get; set; }\n\n /// \n /// Gets or sets whether the tool should report an output schema for structured content.\n /// \n /// \n /// \n /// When enabled, the tool will attempt to populate the \n /// and provide structured content in the property.\n /// \n /// \n /// The default is .\n /// \n /// \n public bool UseStructuredContent { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerToolCreateOptions Clone() =>\n new McpServerToolCreateOptions\n {\n Services = Services,\n Name = Name,\n Description = Description,\n Title = Title,\n Destructive = Destructive,\n Idempotent = Idempotent,\n OpenWorld = OpenWorld,\n ReadOnly = ReadOnly,\n UseStructuredContent = UseStructuredContent,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpServerTransportOptions.cs", "using Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol.AspNetCore;\n\n/// \n/// Configuration options for .\n/// which implements the Streaming HTTP transport for the Model Context Protocol.\n/// See the protocol specification for details on the Streamable HTTP transport. \n/// \npublic class HttpServerTransportOptions\n{\n /// \n /// Gets or sets an optional asynchronous callback to configure per-session \n /// with access to the of the request that initiated the session.\n /// \n public Func? ConfigureSessionOptions { get; set; }\n\n /// \n /// Gets or sets an optional asynchronous callback for running new MCP sessions manually.\n /// This is useful for running logic before a sessions starts and after it completes.\n /// \n public Func? RunSessionHandler { get; set; }\n\n /// \n /// Gets or sets whether the server should run in a stateless mode that does not require all requests for a given session\n /// to arrive to the same ASP.NET Core application process.\n /// \n /// \n /// If , the \"/sse\" endpoint will be disabled, and client information will be round-tripped as part\n /// of the \"MCP-Session-Id\" header instead of stored in memory. Unsolicited server-to-client messages and all server-to-client\n /// requests are also unsupported, because any responses may arrive at another ASP.NET Core application process.\n /// Client sampling and roots capabilities are also disabled in stateless mode, because the server cannot make requests.\n /// Defaults to .\n /// \n public bool Stateless { get; set; }\n\n /// \n /// Gets or sets whether the server should use a single execution context for the entire session.\n /// If , handlers like tools get called with the \n /// belonging to the corresponding HTTP request which can change throughout the MCP session.\n /// If , handlers will get called with the same \n /// used to call and .\n /// \n /// \n /// Enabling a per-session can be useful for setting variables\n /// that persist for the entire session, but it prevents you from using IHttpContextAccessor in handlers.\n /// Defaults to .\n /// \n public bool PerSessionExecutionContext { get; set; }\n\n /// \n /// Gets or sets the duration of time the server will wait between any active requests before timing out an MCP session.\n /// \n /// \n /// This is checked in background every 5 seconds. A client trying to resume a session will receive a 404 status code\n /// and should restart their session. A client can keep their session open by keeping a GET request open.\n /// Defaults to 2 hours.\n /// \n public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromHours(2);\n\n /// \n /// Gets or sets maximum number of idle sessions to track in memory. This is used to limit the number of sessions that can be idle at once.\n /// \n /// \n /// Past this limit, the server will log a critical error and terminate the oldest idle sessions even if they have not reached\n /// their until the idle session count is below this limit. Clients that keep their session open by\n /// keeping a GET request open will not count towards this limit.\n /// Defaults to 100,000 sessions.\n /// \n public int MaxIdleSessionCount { get; set; } = 100_000;\n\n /// \n /// Used for testing the .\n /// \n public TimeProvider TimeProvider { get; set; } = TimeProvider.System;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ITransport.cs", "using ModelContextProtocol.Client;\nusing ModelContextProtocol.Server;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a transport mechanism for MCP (Model Context Protocol) communication between clients and servers.\n/// \n/// \n/// \n/// The interface is the core abstraction for bidirectional communication.\n/// It provides methods for sending and receiving messages, abstracting away the underlying transport mechanism\n/// and allowing protocol implementations to be decoupled from communication details.\n/// \n/// \n/// Implementations of handle the serialization, transmission, and reception of\n/// messages over various channels like standard input/output streams and HTTP (Server-Sent Events).\n/// \n/// \n/// While is responsible for establishing a client's connection,\n/// represents an established session. Client implementations typically obtain an\n/// instance by calling .\n/// \n/// \npublic interface ITransport : IAsyncDisposable\n{\n /// Gets an identifier associated with the current MCP session.\n /// \n /// Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE.\n /// Can return if the session hasn't initialized or if the transport doesn't\n /// support multiple sessions (as is the case with STDIO).\n /// \n string? SessionId { get; }\n\n /// \n /// Gets a channel reader for receiving messages from the transport.\n /// \n /// \n /// \n /// The provides access to incoming JSON-RPC messages received by the transport.\n /// It returns a which allows consuming messages in a thread-safe manner.\n /// \n /// \n /// The reader will continue to provide messages as long as the transport is connected. When the transport\n /// is disconnected or disposed, the channel will be completed and no more messages will be available after\n /// any already transmitted messages are consumed.\n /// \n /// \n ChannelReader MessageReader { get; }\n\n /// \n /// Sends a JSON-RPC message through the transport.\n /// \n /// The JSON-RPC message to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task that represents the asynchronous send operation.\n /// The transport is not connected.\n /// \n /// \n /// This method serializes and sends the provided JSON-RPC message through the transport connection.\n /// \n /// \n /// This is a core method used by higher-level abstractions in the MCP protocol implementation.\n /// Most client code should use the higher-level methods provided by ,\n /// , , or ,\n /// rather than accessing this method directly.\n /// \n /// \n Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientTransportOptions.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Provides options for configuring instances.\n/// \npublic sealed class StdioClientTransportOptions\n{\n /// \n /// Gets or sets the command to execute to start the server process.\n /// \n public required string Command\n {\n get;\n set\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentException(\"Command cannot be null or empty.\", nameof(value));\n }\n\n field = value;\n }\n }\n\n /// \n /// Gets or sets the arguments to pass to the server process when it is started.\n /// \n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets a transport identifier used for logging purposes.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the working directory for the server process.\n /// \n public string? WorkingDirectory { get; set; }\n\n /// \n /// Gets or sets environment variables to set for the server process.\n /// \n /// \n /// \n /// This property allows you to specify environment variables that will be set in the server process's\n /// environment. This is useful for passing configuration, authentication information, or runtime flags\n /// to the server without modifying its code.\n /// \n /// \n /// By default, when starting the server process, the server process will inherit the current environment's variables,\n /// as discovered via . After those variables are found, the entries\n /// in this dictionary are used to augment and overwrite the entries read from the environment.\n /// That includes removing the variables for any of this collection's entries with a null value.\n /// \n /// \n public IDictionary? EnvironmentVariables { get; set; }\n\n /// \n /// Gets or sets the timeout to wait for the server to shut down gracefully.\n /// \n /// \n /// \n /// This property dictates how long the client should wait for the server process to exit cleanly during shutdown\n /// before forcibly terminating it. This balances between giving the server enough time to clean up \n /// resources and not hanging indefinitely if a server process becomes unresponsive.\n /// \n /// \n /// The default is five seconds.\n /// \n /// \n public TimeSpan ShutdownTimeout { get; set; } = TimeSpan.FromSeconds(5);\n\n /// \n /// Gets or sets a callback that is invoked for each line of stderr received from the server process.\n /// \n public Action? StandardErrorLines { get; set; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/LongRunningTool.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class LongRunningTool\n{\n [McpServerTool(Name = \"longRunningOperation\"), Description(\"Demonstrates a long running operation with progress updates\")]\n public static async Task LongRunningOperation(\n IMcpServer server,\n RequestContext context,\n int duration = 10,\n int steps = 5)\n {\n var progressToken = context.Params?.ProgressToken;\n var stepDuration = duration / steps;\n\n for (int i = 1; i <= steps + 1; i++)\n {\n await Task.Delay(stepDuration * 1000);\n \n if (progressToken is not null)\n {\n await server.SendNotificationAsync(\"notifications/progress\", new\n {\n Progress = i,\n Total = steps,\n progressToken\n });\n }\n }\n\n return $\"Long running operation completed. Duration: {duration} seconds. Steps: {steps}.\";\n }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses depenency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await thisServer.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerPrompt.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building prompts that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner prompt instance.\n/// \npublic abstract class DelegatingMcpServerPrompt : McpServerPrompt\n{\n private readonly McpServerPrompt _innerPrompt;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner prompt wrapped by this delegating prompt.\n protected DelegatingMcpServerPrompt(McpServerPrompt innerPrompt)\n {\n Throw.IfNull(innerPrompt);\n _innerPrompt = innerPrompt;\n }\n\n /// \n public override Prompt ProtocolPrompt => _innerPrompt.ProtocolPrompt;\n\n /// \n public override ValueTask GetAsync(\n RequestContext request, \n CancellationToken cancellationToken = default) =>\n _innerPrompt.GetAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerPrompt.ToString();\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace ProtectedMCPServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n private readonly IHttpClientFactory _httpClientFactory;\n\n public WeatherTools(IHttpClientFactory httpClientFactory)\n {\n _httpClientFactory = httpClientFactory;\n }\n\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public async Task GetAlerts(\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public async Task GetForecast(\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var client = _httpClientFactory.CreateClient(\"WeatherApi\");\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/DelegatingMcpServerResource.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Provides an that delegates all operations to an inner .\n/// \n/// This is recommended as a base type when building resources that can be chained around an underlying .\n/// The default implementation simply passes each call to the inner resource instance.\n/// \npublic abstract class DelegatingMcpServerResource : McpServerResource\n{\n private readonly McpServerResource _innerResource;\n\n /// Initializes a new instance of the class around the specified .\n /// The inner resource wrapped by this delegating resource.\n protected DelegatingMcpServerResource(McpServerResource innerResource)\n {\n Throw.IfNull(innerResource);\n _innerResource = innerResource;\n }\n\n /// \n public override Resource? ProtocolResource => _innerResource.ProtocolResource;\n\n /// \n public override ResourceTemplate ProtocolResourceTemplate => _innerResource.ProtocolResourceTemplate;\n\n /// \n public override ValueTask ReadAsync(RequestContext request, CancellationToken cancellationToken = default) => \n _innerResource.ReadAsync(request, cancellationToken);\n\n /// \n public override string ToString() => _innerResource.ToString();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpException.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents an exception that is thrown when an Model Context Protocol (MCP) error occurs.\n/// \n/// \n/// This exception is used to represent failures to do with protocol-level concerns, such as invalid JSON-RPC requests,\n/// invalid parameters, or internal errors. It is not intended to be used for application-level errors.\n/// or from a may be \n/// propagated to the remote endpoint; sensitive information should not be included. If sensitive details need\n/// to be included, a different exception type should be used.\n/// \npublic class McpException : Exception\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpException()\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message.\n /// \n /// The message that describes the error.\n public McpException(string message) : base(message)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n public McpException(string message, Exception? innerException) : base(message, innerException)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// A .\n public McpException(string message, McpErrorCode errorCode) : this(message, null, errorCode)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified error message, inner exception, and JSON-RPC error code.\n /// \n /// The message that describes the error.\n /// The exception that is the cause of the current exception, or a null reference if no inner exception is specified.\n /// A .\n public McpException(string message, Exception? innerException, McpErrorCode errorCode) : base(message, innerException)\n {\n ErrorCode = errorCode;\n }\n\n /// \n /// Gets the error code associated with this exception.\n /// \n /// \n /// This property contains a standard JSON-RPC error code as defined in the MCP specification. Common error codes include:\n /// \n /// -32700: Parse error - Invalid JSON received\n /// -32600: Invalid request - The JSON is not a valid Request object\n /// -32601: Method not found - The method does not exist or is not available\n /// -32602: Invalid params - Invalid method parameters\n /// -32603: Internal error - Internal JSON-RPC error\n /// \n /// \n public McpErrorCode ErrorCode { get; } = McpErrorCode.InternalError;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcRequest.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A request message in the JSON-RPC protocol.\n/// \n/// \n/// Requests are messages that require a response from the receiver. Each request includes a unique ID\n/// that will be included in the corresponding response message (either a success response or an error).\n/// \n/// The receiver of a request message is expected to execute the specified method with the provided parameters\n/// and return either a with the result, or a \n/// if the method execution fails.\n/// \npublic sealed class JsonRpcRequest : JsonRpcMessageWithId\n{\n /// \n /// Name of the method to invoke.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Optional parameters for the method.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n\n internal JsonRpcRequest WithId(RequestId id)\n {\n return new JsonRpcRequest\n {\n JsonRpc = JsonRpc,\n Id = id,\n Method = Method,\n Params = Params,\n RelatedTransport = RelatedTransport,\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpHttpClient.cs", "using ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\n#if NET\nusing System.Net.Http.Json;\n#else\nusing System.Text;\nusing System.Text.Json;\n#endif\n\nnamespace ModelContextProtocol.Client;\n\ninternal class McpHttpClient(HttpClient httpClient)\n{\n internal virtual async Task SendAsync(HttpRequestMessage request, JsonRpcMessage? message, CancellationToken cancellationToken)\n {\n Debug.Assert(request.Content is null, \"The request body should only be supplied as a JsonRpcMessage\");\n Debug.Assert(message is null || request.Method == HttpMethod.Post, \"All messages should be sent in POST requests.\");\n\n using var content = CreatePostBodyContent(message);\n request.Content = content;\n return await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);\n }\n\n private HttpContent? CreatePostBodyContent(JsonRpcMessage? message)\n {\n if (message is null)\n {\n return null;\n }\n\n#if NET\n return JsonContent.Create(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n#else\n return new StringContent(\n JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage),\n Encoding.UTF8,\n \"application/json\"\n );\n#endif\n }\n}\n"], ["/csharp-sdk/src/Common/Throw.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Runtime.CompilerServices;\n\nnamespace ModelContextProtocol;\n\n/// Provides helper methods for throwing exceptions.\ninternal static class Throw\n{\n // NOTE: Most of these should be replaced with extension statics for the relevant extension\n // type as downlevel polyfills once the C# 14 extension everything feature is available.\n\n public static void IfNull([NotNull] object? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n }\n\n public static void IfNullOrWhiteSpace([NotNull] string? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg is null || arg.AsSpan().IsWhiteSpace())\n {\n ThrowArgumentNullOrWhiteSpaceException(parameterName);\n }\n }\n\n public static void IfNegative(int arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)\n {\n if (arg < 0)\n {\n Throw(parameterName);\n static void Throw(string? parameterName) => throw new ArgumentOutOfRangeException(parameterName, \"must not be negative.\");\n }\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullOrWhiteSpaceException(string? parameterName)\n {\n if (parameterName is null)\n {\n ThrowArgumentNullException(parameterName);\n }\n\n throw new ArgumentException(\"Value cannot be empty or composed entirely of whitespace.\", parameterName);\n }\n\n [DoesNotReturn]\n private static void ThrowArgumentNullException(string? parameterName) => throw new ArgumentNullException(parameterName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceTemplate.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource template that the server is capable of reading.\n/// \n/// \n/// Resource templates provide metadata about resources available on the server,\n/// including how to construct URIs for those resources.\n/// \npublic sealed class ResourceTemplate : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI template (according to RFC 6570) that can be used to construct resource URIs.\n /// \n [JsonPropertyName(\"uriTemplate\")]\n public required string UriTemplate { get; init; }\n\n /// \n /// Gets or sets a description of what this resource template represents.\n /// \n /// \n /// \n /// This description helps clients understand the purpose and content of resources\n /// that can be generated from this template. It can be used by client applications\n /// to provide context about available resource types or to display in user interfaces.\n /// \n /// \n /// For AI models, this description can serve as a hint about when and how to use\n /// the resource template, enhancing the model's ability to generate appropriate URIs.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource template, if known.\n /// \n /// \n /// \n /// Specifies the expected format of resources that can be generated from this template.\n /// This helps clients understand what type of content to expect when accessing resources\n /// created using this template.\n /// \n /// \n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, or \"application/json\" for JSON data.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource template.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource template. Clients can use this information to filter\n /// or prioritize resource templates for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n\n /// Gets whether contains any template expressions.\n [JsonIgnore]\n public bool IsTemplated => UriTemplate.Contains('{');\n\n /// Converts the into a .\n /// A if is ; otherwise, .\n public Resource? AsResource()\n {\n if (IsTemplated)\n {\n return null;\n }\n\n return new()\n {\n Uri = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n Annotations = Annotations,\n Meta = Meta,\n };\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/HttpMcpServerBuilderExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing ModelContextProtocol.AspNetCore;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides methods for configuring HTTP MCP servers via dependency injection.\n/// \npublic static class HttpMcpServerBuilderExtensions\n{\n /// \n /// Adds the services necessary for \n /// to handle MCP requests and sessions using the MCP Streamable HTTP transport. For more information on configuring the underlying HTTP server\n /// to control things like port binding custom TLS certificates, see the Minimal APIs quick reference.\n /// \n /// The builder instance.\n /// Configures options for the Streamable HTTP transport. This allows configuring per-session\n /// and running logic before and after a session.\n /// The builder provided in .\n /// is .\n public static IMcpServerBuilder WithHttpTransport(this IMcpServerBuilder builder, Action? configureOptions = null)\n {\n ArgumentNullException.ThrowIfNull(builder);\n\n builder.Services.TryAddSingleton();\n builder.Services.TryAddSingleton();\n builder.Services.AddHostedService();\n builder.Services.AddDataProtection();\n\n if (configureOptions is not null)\n {\n builder.Services.Configure(configureOptions);\n }\n\n return builder;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of prompts created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating prompts programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerPromptCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the method,\n /// the name from the attribute will be used. If that's not present, a name based on the method's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the method,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerPromptCreateOptions Clone() =>\n new McpServerPromptCreateOptions\n {\n Services = Services,\n Name = Name,\n Title = Title,\n Description = Description,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/McpServerServiceCollectionExtensions.cs", "using Microsoft.Extensions.DependencyInjection.Extensions;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides extension methods for configuring MCP servers with dependency injection.\n/// \npublic static class McpServerServiceCollectionExtensions\n{\n /// \n /// Adds the Model Context Protocol (MCP) server to the service collection with default options.\n /// \n /// The to add the server to.\n /// Optional callback to configure the .\n /// An that can be used to further configure the MCP server.\n\n public static IMcpServerBuilder AddMcpServer(this IServiceCollection services, Action? configureOptions = null)\n {\n services.AddOptions();\n services.TryAddEnumerable(ServiceDescriptor.Transient, McpServerOptionsSetup>());\n if (configureOptions is not null)\n {\n services.Configure(configureOptions);\n }\n\n return new DefaultMcpServerBuilder(services);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol/SingleSessionMcpServerHostedService.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol.Server;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Hosted service for a single-session (e.g. stdio) MCP server.\n/// \n/// The server representing the session being hosted.\n/// \n/// The host's application lifetime. If available, it will have termination requested when the session's run completes.\n/// \ninternal sealed class SingleSessionMcpServerHostedService(IMcpServer session, IHostApplicationLifetime? lifetime = null) : BackgroundService\n{\n /// \n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n try\n {\n await session.RunAsync(stoppingToken).ConfigureAwait(false);\n }\n finally\n {\n lifetime?.StopApplication();\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCreateOptions.cs", "using Microsoft.Extensions.AI;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides options for controlling the creation of an .\n/// \n/// \n/// \n/// These options allow for customizing the behavior and metadata of resources created with\n/// . They provide control over naming, description,\n/// and dependency injection integration.\n/// \n/// \n/// When creating resources programmatically rather than using attributes, these options\n/// provide the same level of configuration flexibility.\n/// \n/// \npublic sealed class McpServerResourceCreateOptions\n{\n /// \n /// Gets or sets optional services used in the construction of the .\n /// \n /// \n /// These services will be used to determine which parameters should be satisifed from dependency injection. As such,\n /// what services are satisfied via this provider should match what's satisfied via the provider passed in at invocation time.\n /// \n public IServiceProvider? Services { get; set; }\n\n /// \n /// Gets or sets the URI template of the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the from the attribute will be used. If that's not present,\n /// a URI template will be inferred from the member's signature.\n /// \n public string? UriTemplate { get; set; }\n\n /// \n /// Gets or sets the name to use for the .\n /// \n /// \n /// If , but an is applied to the member,\n /// the name from the attribute will be used. If that's not present, a name based on the members's name will be used.\n /// \n public string? Name { get; set; }\n\n /// \n /// Gets or sets the title to use for the .\n /// \n public string? Title { get; set; }\n\n /// \n /// Gets or set the description to use for the .\n /// \n /// \n /// If , but a is applied to the member,\n /// the description from that attribute will be used.\n /// \n public string? Description { get; set; }\n\n /// \n /// Gets or sets the MIME (media) type of the .\n /// \n public string? MimeType { get; set; }\n\n /// \n /// Gets or sets the JSON serializer options to use when marshalling data to/from JSON.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public JsonSerializerOptions? SerializerOptions { get; set; }\n\n /// \n /// Gets or sets the JSON schema options when creating from a method.\n /// \n /// \n /// Defaults to if left unspecified.\n /// \n public AIJsonSchemaCreateOptions? SchemaCreateOptions { get; set; }\n\n /// \n /// Creates a shallow clone of the current instance.\n /// \n internal McpServerResourceCreateOptions Clone() =>\n new McpServerResourceCreateOptions\n {\n Services = Services,\n UriTemplate = UriTemplate,\n Name = Name,\n Title = Title,\n Description = Description,\n MimeType = MimeType,\n SerializerOptions = SerializerOptions,\n SchemaCreateOptions = SchemaCreateOptions,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerFactory.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides a factory for creating instances.\n/// \n/// \n/// This is the recommended way to create instances.\n/// The factory handles proper initialization of server instances with the required dependencies.\n/// \npublic static class McpServerFactory\n{\n /// \n /// Creates a new instance of an .\n /// \n /// Transport to use for the server representing an already-established MCP session.\n /// Configuration options for this server, including capabilities. \n /// Logger factory to use for logging. If null, logging will be disabled.\n /// Optional service provider to create new instances of tools and other dependencies.\n /// An instance that should be disposed when no longer needed.\n /// is .\n /// is .\n public static IMcpServer Create(\n ITransport transport,\n McpServerOptions serverOptions,\n ILoggerFactory? loggerFactory = null,\n IServiceProvider? serviceProvider = null)\n {\n Throw.IfNull(transport);\n Throw.IfNull(serverOptions);\n\n return new McpServer(transport, serverOptions, loggerFactory, serviceProvider);\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/ResourceGenerator.cs", "using ModelContextProtocol.Protocol;\n\nnamespace EverythingServer;\n\nstatic class ResourceGenerator\n{\n private static readonly List _resources = Enumerable.Range(1, 100).Select(i =>\n {\n var uri = $\"test://template/resource/{i}\";\n if (i % 2 != 0)\n {\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"text/plain\",\n Description = $\"Resource {i}: This is a plaintext resource\"\n };\n }\n else\n {\n var buffer = System.Text.Encoding.UTF8.GetBytes($\"Resource {i}: This is a base64 blob\");\n return new Resource\n {\n Uri = uri,\n Name = $\"Resource {i}\",\n MimeType = \"application/octet-stream\",\n Description = Convert.ToBase64String(buffer)\n };\n }\n }).ToList();\n\n public static IReadOnlyList Resources => _resources;\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/SampleLlmTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer server,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, \"sampleLLM\", maxTokens);\n var sampleResult = await server.SampleAsync(samplingParams, cancellationToken);\n\n return $\"LLM sampling result: {(sampleResult.Content as TextContentBlock)?.Text}\";\n }\n\n private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100)\n {\n return new CreateMessageRequestParams\n {\n Messages = [new SamplingMessage\n {\n Role = Role.User,\n Content = new TextContentBlock { Text = $\"Resource {uri} context: {context}\" },\n }],\n SystemPrompt = \"You are a helpful test server.\",\n MaxTokens = maxTokens,\n Temperature = 0.7f,\n IncludeContext = ContextInclusion.ThisServer\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common notification methods used in the MCP protocol.\n/// \npublic static class NotificationMethods\n{\n /// \n /// The name of notification sent by a server when the list of available tools changes.\n /// \n /// \n /// This notification informs clients that the set of available tools has been modified.\n /// Changes may include tools being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their tool list by calling the appropriate \n /// method to get the updated list of tools.\n /// \n public const string ToolListChangedNotification = \"notifications/tools/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available prompts changes.\n /// \n /// \n /// This notification informs clients that the set of available prompts has been modified.\n /// Changes may include prompts being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their prompt list by calling the appropriate \n /// method to get the updated list of prompts.\n /// \n public const string PromptListChangedNotification = \"notifications/prompts/list_changed\";\n\n /// \n /// The name of the notification sent by the server when the list of available resources changes.\n /// \n /// \n /// This notification informs clients that the set of available resources has been modified.\n /// Changes may include resources being added, removed, or updated. Upon receiving this \n /// notification, clients may refresh their resource list by calling the appropriate \n /// method to get the updated list of resources.\n /// \n public const string ResourceListChangedNotification = \"notifications/resources/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a resource is updated.\n /// \n /// \n /// This notification is used to inform clients about changes to a specific resource they have subscribed to.\n /// When a resource is updated, the server sends this notification to all clients that have subscribed to that resource.\n /// \n public const string ResourceUpdatedNotification = \"notifications/resources/updated\";\n\n /// \n /// The name of the notification sent by the client when roots have been updated.\n /// \n /// \n /// \n /// This notification informs the server that the client's \"roots\" have changed. \n /// Roots define the boundaries of where servers can operate within the filesystem, \n /// allowing them to understand which directories and files they have access to. Servers \n /// can request the list of roots from supporting clients and receive notifications when that list changes.\n /// \n /// \n /// After receiving this notification, servers may refresh their knowledge of roots by calling the appropriate \n /// method to get the updated list of roots from the client.\n /// \n /// \n public const string RootsListChangedNotification = \"notifications/roots/list_changed\";\n\n /// \n /// The name of the notification sent by the server when a log message is generated.\n /// \n /// \n /// \n /// This notification is used by the server to send log messages to clients. Log messages can include\n /// different severity levels, such as debug, info, warning, or error, and an optional logger name to\n /// identify the source component.\n /// \n /// \n /// The minimum logging level that triggers notifications can be controlled by clients using the\n /// request. If no level has been set by a client, \n /// the server may determine which messages to send based on its own configuration.\n /// \n /// \n public const string LoggingMessageNotification = \"notifications/message\";\n\n /// \n /// The name of the notification sent from the client to the server after initialization has finished.\n /// \n /// \n /// \n /// This notification is sent by the client after it has received and processed the server's response to the \n /// request. It signals that the client is ready to begin normal operation \n /// and that the initialization phase is complete.\n /// \n /// \n /// After receiving this notification, the server can begin sending notifications and processing\n /// further requests from the client.\n /// \n /// \n public const string InitializedNotification = \"notifications/initialized\";\n\n /// \n /// The name of the notification sent to inform the receiver of a progress update for a long-running request.\n /// \n /// \n /// \n /// This notification provides updates on the progress of long-running operations. It includes\n /// a progress token that associates the notification with a specific request, the current progress value,\n /// and optionally, a total value and a descriptive message.\n /// \n /// \n /// Progress notifications may be sent by either the client or the server, depending on the context.\n /// Progress notifications enable clients to display progress indicators for operations that might take\n /// significant time to complete, such as large file uploads, complex computations, or resource-intensive\n /// processing tasks.\n /// \n /// \n public const string ProgressNotification = \"notifications/progress\";\n\n /// \n /// The name of the notification sent to indicate that a previously-issued request should be canceled.\n /// \n /// \n /// \n /// From the issuer's perspective, the request should still be in-flight. However, due to communication latency,\n /// it is always possible that this notification may arrive after the request has already finished.\n /// \n /// \n /// This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n /// \n /// \n /// A client must not attempt to cancel its `initialize` request.\n /// \n /// \n public const string CancelledNotification = \"notifications/cancelled\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method or property should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods or properties that should be exposed as resources in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods or properties become available as resources that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// Read resource requests do not contain separate arguments, only a URI. However, for templated resources, portions of that URI may be considered\n/// as arguments and may be bound to parameters. Further, resource methods may accept parameters that will be bound to arguments based on their type.\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the resource to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the resource invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// All other parameters are bound from the data in the URI.\n/// \n/// \n/// \n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Wrapped in a list containing the single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// \n/// Converted to a list containing a single .\n/// \n/// \n/// of \n/// Returned directly as a list of .\n/// \n/// \n/// of \n/// Converted to a list containing a for each and a for each .\n/// \n/// \n/// of \n/// Converted to a list containing a , one for each .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerResourceAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerResourceAttribute()\n {\n }\n\n /// Gets or sets the URI template of the resource.\n /// \n /// If , a URI will be derived from and the method's parameter names.\n /// This template may, but doesn't have to, include parameters; if it does, this \n /// will be considered a \"resource template\", and if it doesn't, it will be considered a \"direct resource\".\n /// The former will be listed with requests and the latter\n /// with requests.\n /// \n public string? UriTemplate { get; set; }\n\n /// Gets or sets the name of the resource.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the resource.\n public string? Title { get; set; }\n\n /// Gets or sets the MIME (media) type of the resource.\n public string? MimeType { get; set; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/SubscriptionMessageSender.cs", "using Microsoft.Extensions.Hosting;\nusing ModelContextProtocol;\nusing ModelContextProtocol.Server;\n\ninternal class SubscriptionMessageSender(IMcpServer server, HashSet subscriptions) : BackgroundService\n{\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n while (!stoppingToken.IsCancellationRequested)\n {\n foreach (var uri in subscriptions)\n {\n await server.SendNotificationAsync(\"notifications/resource/updated\",\n new\n {\n Uri = uri,\n }, cancellationToken: stoppingToken);\n }\n\n await Task.Delay(5000, stoppingToken);\n }\n }\n}\n"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/WeatherTools.cs", "using ModelContextProtocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Globalization;\nusing System.Text.Json;\n\nnamespace QuickstartWeatherServer.Tools;\n\n[McpServerToolType]\npublic sealed class WeatherTools\n{\n [McpServerTool, Description(\"Get weather alerts for a US state.\")]\n public static async Task GetAlerts(\n HttpClient client,\n [Description(\"The US state to get alerts for. Use the 2 letter abbreviation for the state (e.g. NY).\")] string state)\n {\n using var jsonDocument = await client.ReadJsonDocumentAsync($\"/alerts/active/area/{state}\");\n var jsonElement = jsonDocument.RootElement;\n var alerts = jsonElement.GetProperty(\"features\").EnumerateArray();\n\n if (!alerts.Any())\n {\n return \"No active alerts for this state.\";\n }\n\n return string.Join(\"\\n--\\n\", alerts.Select(alert =>\n {\n JsonElement properties = alert.GetProperty(\"properties\");\n return $\"\"\"\n Event: {properties.GetProperty(\"event\").GetString()}\n Area: {properties.GetProperty(\"areaDesc\").GetString()}\n Severity: {properties.GetProperty(\"severity\").GetString()}\n Description: {properties.GetProperty(\"description\").GetString()}\n Instruction: {properties.GetProperty(\"instruction\").GetString()}\n \"\"\";\n }));\n }\n\n [McpServerTool, Description(\"Get weather forecast for a location.\")]\n public static async Task GetForecast(\n HttpClient client,\n [Description(\"Latitude of the location.\")] double latitude,\n [Description(\"Longitude of the location.\")] double longitude)\n {\n var pointUrl = string.Create(CultureInfo.InvariantCulture, $\"/points/{latitude},{longitude}\");\n using var jsonDocument = await client.ReadJsonDocumentAsync(pointUrl);\n var forecastUrl = jsonDocument.RootElement.GetProperty(\"properties\").GetProperty(\"forecast\").GetString()\n ?? throw new Exception($\"No forecast URL provided by {client.BaseAddress}points/{latitude},{longitude}\");\n\n using var forecastDocument = await client.ReadJsonDocumentAsync(forecastUrl);\n var periods = forecastDocument.RootElement.GetProperty(\"properties\").GetProperty(\"periods\").EnumerateArray();\n\n return string.Join(\"\\n---\\n\", periods.Select(period => $\"\"\"\n {period.GetProperty(\"name\").GetString()}\n Temperature: {period.GetProperty(\"temperature\").GetInt32()}°F\n Wind: {period.GetProperty(\"windSpeed\").GetString()} {period.GetProperty(\"windDirection\").GetString()}\n Forecast: {period.GetProperty(\"detailedForecast\").GetString()}\n \"\"\"));\n }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/AnnotatedMessageTool.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AnnotatedMessageTool\n{\n public enum MessageType\n {\n Error,\n Success,\n Debug,\n }\n\n [McpServerTool(Name = \"annotatedMessage\"), Description(\"Generates an annotated message\")]\n public static IEnumerable AnnotatedMessage(MessageType messageType, bool includeImage = true)\n {\n List contents = messageType switch\n {\n MessageType.Error => [new TextContentBlock\n {\n Text = \"Error: Operation failed\",\n Annotations = new() { Audience = [Role.User, Role.Assistant], Priority = 1.0f }\n }],\n MessageType.Success => [new TextContentBlock\n {\n Text = \"Operation completed successfully\",\n Annotations = new() { Audience = [Role.User], Priority = 0.7f }\n }],\n MessageType.Debug => [new TextContentBlock\n {\n Text = \"Debug: Cache hit ratio 0.95, latency 150ms\",\n Annotations = new() { Audience = [Role.Assistant], Priority = 0.3f }\n }],\n _ => throw new ArgumentOutOfRangeException(nameof(messageType), messageType, null)\n };\n\n if (includeImage)\n {\n contents.Add(new ImageContentBlock\n {\n Data = TinyImageTool.MCP_TINY_IMAGE.Split(\",\").Last(),\n MimeType = \"image/png\",\n Annotations = new() { Audience = [Role.User], Priority = 0.5f }\n });\n }\n\n return contents;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptAttribute.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Used to indicate that a method should be considered an .\n/// \n/// \n/// \n/// This attribute is applied to methods that should be exposed as prompts in the Model Context Protocol. When a class \n/// containing methods marked with this attribute is registered with McpServerBuilderExtensions,\n/// these methods become available as prompts that can be called by MCP clients.\n/// \n/// \n/// When methods are provided directly to , the attribute is not required.\n/// \n/// \n/// By default, parameters are sourced from the dictionary, which is a collection\n/// of key/value pairs. Those parameters are deserialized from the\n/// values in that collection. There are a few exceptions to this:\n/// \n/// \n/// \n/// parameters are automatically bound to a provided by the\n/// and that respects any s sent by the client for this operation's\n/// .\n/// \n/// \n/// \n/// \n/// parameters are bound from the for this request.\n/// \n/// \n/// \n/// \n/// parameters are bound directly to the instance associated\n/// with this request's . Such parameters may be used to understand\n/// what server is being used to process the request, and to interact with the client issuing the request to that server.\n/// \n/// \n/// \n/// \n/// parameters accepting values\n/// are bound to an instance manufactured to forward progress notifications\n/// from the prompt to the client. If the client included a in their request, progress reports issued\n/// to this instance will propagate to the client as notifications with\n/// that token. If the client did not include a , the instance will ignore any progress reports issued to it.\n/// \n/// \n/// \n/// \n/// When the is constructed, it may be passed an via \n/// . Any parameter that can be satisfied by that \n/// according to will be resolved from the provided to the \n/// prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// Any parameter attributed with will similarly be resolved from the \n/// provided to the prompt invocation rather than from the argument collection.\n/// \n/// \n/// \n/// \n/// \n/// All other parameters are deserialized from the s in the dictionary.\n/// \n/// \n/// In general, the data supplied via the 's dictionary is passed along from the caller and\n/// should thus be considered unvalidated and untrusted. To provide validated and trusted data to the invocation of the prompt, consider having \n/// the prompt be an instance method, referring to data stored in the instance, or using an instance or parameters resolved from the \n/// to provide data to the method.\n/// \n/// \n/// Return values from a method are used to create the that is sent back to the client:\n/// \n/// \n/// \n/// \n/// Converted to a list containing a single with its set to contain the .\n/// \n/// \n/// \n/// Converted to a list containing the single .\n/// \n/// \n/// of \n/// Converted to a list containing all of the returned instances.\n/// \n/// \n/// \n/// Converted to a list of instances derived from the with .\n/// \n/// \n/// of \n/// Converted to a list of instances derived from all of the instances with .\n/// \n/// \n/// \n/// Other returned types will result in an being thrown.\n/// \n/// \n[AttributeUsage(AttributeTargets.Method)]\npublic sealed class McpServerPromptAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class.\n /// \n public McpServerPromptAttribute()\n {\n }\n\n /// Gets the name of the prompt.\n /// If , the method name will be used.\n public string? Name { get; set; }\n\n /// Gets or sets the title of the prompt.\n public string? Title { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationExtensions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.AspNetCore.Authentication;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Extension methods for adding MCP authorization support to ASP.NET Core applications.\n/// \npublic static class McpAuthenticationExtensions\n{\n /// \n /// Adds MCP authorization support to the application.\n /// \n /// The authentication builder.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n Action? configureOptions = null)\n {\n return AddMcp(\n builder,\n McpAuthenticationDefaults.AuthenticationScheme,\n McpAuthenticationDefaults.DisplayName,\n configureOptions);\n }\n\n /// \n /// Adds MCP authorization support to the application with a custom scheme name.\n /// \n /// The authentication builder.\n /// The authentication scheme name to use.\n /// The display name for the authentication scheme.\n /// An action to configure MCP authentication options.\n /// The authentication builder for chaining.\n public static AuthenticationBuilder AddMcp(\n this AuthenticationBuilder builder,\n string authenticationScheme,\n string displayName,\n Action? configureOptions = null)\n {\n return builder.AddScheme(\n authenticationScheme,\n displayName,\n configureOptions);\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMembersAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that certain members on a specified are accessed dynamically,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which members are being accessed during the execution\n/// of a program.\n///\n/// This attribute is valid on members whose type is or .\n///\n/// When this attribute is applied to a location of type , the assumption is\n/// that the string represents a fully qualified type name.\n///\n/// When this attribute is applied to a class, interface, or struct, the members specified\n/// can be accessed dynamically on instances returned from calling\n/// on instances of that class, interface, or struct.\n///\n/// If the attribute is applied to a method it's treated as a special case and it implies\n/// the attribute should be applied to the \"this\" parameter of the method. As such the attribute\n/// should only be used on instance methods of types assignable to System.Type (or string, but no methods\n/// will use it there).\n/// \n[AttributeUsage(\n AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |\n AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |\n AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,\n Inherited = false)]\ninternal sealed class DynamicallyAccessedMembersAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified member types.\n /// \n /// The types of members dynamically accessed.\n public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)\n {\n MemberTypes = memberTypes;\n }\n\n /// \n /// Gets the which specifies the type\n /// of members dynamically accessed.\n /// \n public DynamicallyAccessedMemberTypes MemberTypes { get; }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/UnconditionalSuppressMessageAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a\n/// single code artifact.\n/// \n/// \n/// is different than\n/// in that it doesn't have a\n/// . So it is always preserved in the compiled assembly.\n/// \n[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\ninternal sealed class UnconditionalSuppressMessageAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the \n /// class, specifying the category of the tool and the identifier for an analysis rule.\n /// \n /// The category for the attribute.\n /// The identifier of the analysis rule the attribute applies to.\n public UnconditionalSuppressMessageAttribute(string category, string checkId)\n {\n Category = category;\n CheckId = checkId;\n }\n\n /// \n /// Gets the category identifying the classification of the attribute.\n /// \n /// \n /// The property describes the tool or tool analysis category\n /// for which a message suppression attribute applies.\n /// \n public string Category { get; }\n\n /// \n /// Gets the identifier of the analysis tool rule to be suppressed.\n /// \n /// \n /// Concatenated together, the and \n /// properties form a unique check identifier.\n /// \n public string CheckId { get; }\n\n /// \n /// Gets or sets the scope of the code that is relevant for the attribute.\n /// \n /// \n /// The Scope property is an optional argument that specifies the metadata scope for which\n /// the attribute is relevant.\n /// \n public string? Scope { get; set; }\n\n /// \n /// Gets or sets a fully qualified path that represents the target of the attribute.\n /// \n /// \n /// The property is an optional argument identifying the analysis target\n /// of the attribute. An example value is \"System.IO.Stream.ctor():System.Void\".\n /// Because it is fully qualified, it can be long, particularly for targets such as parameters.\n /// The analysis tool user interface should be capable of automatically formatting the parameter.\n /// \n public string? Target { get; set; }\n\n /// \n /// Gets or sets an optional argument expanding on exclusion criteria.\n /// \n /// \n /// The property is an optional argument that specifies additional\n /// exclusion where the literal metadata target is not sufficiently precise. For example,\n /// the cannot be applied within a method,\n /// and it may be desirable to suppress a violation against a statement in the method that will\n /// give a rule violation, but not against all statements in the method.\n /// \n public string? MessageId { get; set; }\n\n /// \n /// Gets or sets the justification for suppressing the code analysis message.\n /// \n public string? Justification { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/AugmentedServiceProvider.cs", "using Microsoft.Extensions.DependencyInjection;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// Augments a service provider with additional request-related services.\ninternal sealed class RequestServiceProvider(\n RequestContext request, IServiceProvider? innerServices) :\n IServiceProvider, IKeyedServiceProvider,\n IServiceProviderIsService, IServiceProviderIsKeyedService,\n IDisposable, IAsyncDisposable\n where TRequestParams : RequestParams\n{\n /// Gets the request associated with this instance.\n public RequestContext Request => request;\n\n /// Gets whether the specified type is in the list of additional types this service provider wraps around the one in a provided request's services.\n public static bool IsAugmentedWith(Type serviceType) =>\n serviceType == typeof(RequestContext) ||\n serviceType == typeof(IMcpServer) ||\n serviceType == typeof(IProgress);\n\n /// \n public object? GetService(Type serviceType) =>\n serviceType == typeof(RequestContext) ? request :\n serviceType == typeof(IMcpServer) ? request.Server :\n serviceType == typeof(IProgress) ?\n (request.Params?.ProgressToken is { } progressToken ? new TokenProgress(request.Server, progressToken) : NullProgress.Instance) :\n innerServices?.GetService(serviceType);\n\n /// \n public bool IsService(Type serviceType) =>\n IsAugmentedWith(serviceType) ||\n (innerServices as IServiceProviderIsService)?.IsService(serviceType) is true;\n\n /// \n public bool IsKeyedService(Type serviceType, object? serviceKey) =>\n (serviceKey is null && IsService(serviceType)) ||\n (innerServices as IServiceProviderIsKeyedService)?.IsKeyedService(serviceType, serviceKey) is true;\n\n /// \n public object? GetKeyedService(Type serviceType, object? serviceKey) =>\n serviceKey is null ? GetService(serviceType) :\n (innerServices as IKeyedServiceProvider)?.GetKeyedService(serviceType, serviceKey);\n\n /// \n public object GetRequiredKeyedService(Type serviceType, object? serviceKey) =>\n GetKeyedService(serviceType, serviceKey) ??\n throw new InvalidOperationException($\"No service of type '{serviceType}' with key '{serviceKey}' is registered.\");\n\n /// \n public void Dispose() =>\n (innerServices as IDisposable)?.Dispose();\n\n /// \n public ValueTask DisposeAsync() =>\n innerServices is IAsyncDisposable asyncDisposable ? asyncDisposable.DisposeAsync() : default;\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationOptions.cs", "using Microsoft.AspNetCore.Authentication;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Options for the MCP authentication handler.\n/// \npublic class McpAuthenticationOptions : AuthenticationSchemeOptions\n{\n private static readonly Uri DefaultResourceMetadataUri = new(\"/.well-known/oauth-protected-resource\", UriKind.Relative);\n\n /// \n /// Initializes a new instance of the class.\n /// \n public McpAuthenticationOptions()\n {\n // \"Bearer\" is JwtBearerDefaults.AuthenticationScheme, but we don't have a reference to the JwtBearer package here.\n ForwardAuthenticate = \"Bearer\";\n ResourceMetadataUri = DefaultResourceMetadataUri;\n Events = new McpAuthenticationEvents();\n }\n\n /// \n /// Gets or sets the events used to handle authentication events.\n /// \n public new McpAuthenticationEvents Events\n {\n get { return (McpAuthenticationEvents)base.Events!; }\n set { base.Events = value; }\n }\n\n /// \n /// The URI to the resource metadata document.\n /// \n /// \n /// This URI will be included in the WWW-Authenticate header when a 401 response is returned.\n /// \n public Uri ResourceMetadataUri { get; set; }\n\n /// \n /// Gets or sets the protected resource metadata.\n /// \n /// \n /// This contains the OAuth metadata for the protected resource, including authorization servers,\n /// supported scopes, and other information needed for clients to authenticate.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol/DefaultMcpServerBuilder.cs", "using ModelContextProtocol;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Default implementation of that enables fluent configuration\n/// of the Model Context Protocol (MCP) server. This builder is returned by the\n/// extension method and\n/// provides access to the service collection for registering additional MCP components.\n/// \ninternal sealed class DefaultMcpServerBuilder : IMcpServerBuilder\n{\n /// \n public IServiceCollection Services { get; }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The service collection to which MCP server services will be added. This collection\n /// is exposed through the property to allow additional configuration.\n /// Thrown when is null.\n public DefaultMcpServerBuilder(IServiceCollection services)\n {\n Throw.IfNull(services);\n\n Services = services;\n }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CompilerFeatureRequiredAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Indicates that compiler support for a particular feature is required for the location where this attribute is applied.\n /// \n [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]\n internal sealed class CompilerFeatureRequiredAttribute : Attribute\n {\n public CompilerFeatureRequiredAttribute(string featureName)\n {\n FeatureName = featureName;\n }\n\n /// \n /// The name of the compiler feature.\n /// \n public string FeatureName { get; }\n\n /// \n /// If true, the compiler can choose to allow access to the location where this attribute is applied if it does not understand .\n /// \n public bool IsOptional { get; init; }\n\n /// \n /// The used for the required members C# feature.\n /// \n public const string RequiredMembers = nameof(RequiredMembers);\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IClientTransport.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents a transport mechanism for Model Context Protocol (MCP) client-to-server communication.\n/// \n/// \n/// \n/// The interface abstracts the communication layer between MCP clients\n/// and servers, allowing different transport protocols to be used interchangeably.\n/// \n/// \n/// When creating an , is typically used, and is\n/// provided with the based on expected server configuration.\n/// \n/// \npublic interface IClientTransport\n{\n /// \n /// Gets a transport identifier, used for logging purposes.\n /// \n string Name { get; }\n\n /// \n /// Asynchronously establishes a transport session with an MCP server and returns a transport for the duplex message stream.\n /// \n /// The to monitor for cancellation requests. The default is .\n /// Returns an interface for the duplex message stream.\n /// \n /// \n /// This method is responsible for initializing the connection to the server using the specific transport \n /// mechanism implemented by the derived class. The returned interface \n /// provides methods to send and receive messages over the established connection.\n /// \n /// \n /// The lifetime of the returned instance is typically managed by the \n /// that uses this transport. When the client is disposed, it will dispose\n /// the transport session as well.\n /// \n /// \n /// This method is used by to initialize the connection.\n /// \n /// \n /// The transport connection could not be established.\n Task ConnectAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/SampleLlmTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n/// \n/// This tool uses dependency injection and async method\n/// \n[McpServerToolType]\npublic sealed class SampleLlmTool\n{\n [McpServerTool(Name = \"sampleLLM\"), Description(\"Samples from an LLM using MCP's sampling feature\")]\n public static async Task SampleLLM(\n IMcpServer thisServer,\n [Description(\"The prompt to send to the LLM\")] string prompt,\n [Description(\"Maximum number of tokens to generate\")] int maxTokens,\n CancellationToken cancellationToken)\n {\n ChatOptions options = new()\n {\n Instructions = \"You are a helpful test server.\",\n MaxOutputTokens = maxTokens,\n Temperature = 0.7f,\n };\n\n var samplingResponse = await thisServer.AsSamplingChatClient().GetResponseAsync(prompt, options, cancellationToken);\n\n return $\"LLM sampling result: {samplingResponse}\";\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingCapability.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Client;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to generate text or other content using an AI model.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to sampling requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to generate content\n/// using an AI model. The client must set a to process these requests.\n/// \n/// \npublic sealed class SamplingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to generate content\n /// using an AI model. The client must set this property for the sampling capability to work.\n /// \n /// \n /// The handler receives message parameters, a progress reporter for updates, and a \n /// cancellation token. It should return a containing the \n /// generated content.\n /// \n /// \n /// You can create a handler using the extension\n /// method with any implementation of .\n /// \n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SamplingHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides configuration options for the MCP server.\n/// \npublic sealed class McpServerOptions\n{\n /// \n /// Gets or sets information about this server implementation, including its name and version.\n /// \n /// \n /// This information is sent to the client during initialization to identify the server.\n /// It's displayed in client logs and can be used for debugging and compatibility checks.\n /// \n public Implementation? ServerInfo { get; set; }\n\n /// \n /// Gets or sets server capabilities to advertise to the client.\n /// \n /// \n /// These determine which features will be available when a client connects.\n /// Capabilities can include \"tools\", \"prompts\", \"resources\", \"logging\", and other \n /// protocol-specific functionality.\n /// \n public ServerCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version supported by this server, using a date-based versioning scheme.\n /// \n /// \n /// The protocol version defines which features and message formats this server supports.\n /// This uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// If , the server will advertize to the client the version requested\n /// by the client if that version is known to be supported, and otherwise will advertize the latest\n /// version supported by the server.\n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout used for the client-server initialization handshake sequence.\n /// \n /// \n /// This timeout determines how long the server will wait for client responses during\n /// the initialization protocol handshake. If the client doesn't respond within this timeframe,\n /// the initialization process will be aborted.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n\n /// \n /// Gets or sets optional server instructions to send to clients.\n /// \n /// \n /// These instructions are sent to clients during the initialization handshake and provide\n /// guidance on how to effectively use the server's capabilities. They can include details\n /// about available tools, expected input formats, limitations, or other helpful information.\n /// Client applications typically use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n public string? ServerInstructions { get; set; }\n\n /// \n /// Gets or sets whether to create a new service provider scope for each handled request.\n /// \n /// \n /// The default is . When , each invocation of a request\n /// handler will be invoked within a new service scope.\n /// \n public bool ScopeRequests { get; set; } = true;\n\n /// \n /// Gets or sets preexisting knowledge about the client including its name and version to help support\n /// stateless Streamable HTTP servers that encode this knowledge in the mcp-session-id header.\n /// \n /// \n /// \n /// When not specified, this information is sourced from the client's initialize request.\n /// \n /// \n public Implementation? KnownClientInfo { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ClientOAuthOptions.cs", "namespace ModelContextProtocol.Authentication;\n\n/// \n/// Provides configuration options for the .\n/// \npublic sealed class ClientOAuthOptions\n{\n /// \n /// Gets or sets the OAuth redirect URI.\n /// \n public required Uri RedirectUri { get; set; }\n\n /// \n /// Gets or sets the OAuth client ID. If not provided, the client will attempt to register dynamically.\n /// \n public string? ClientId { get; set; }\n\n /// \n /// Gets or sets the OAuth client secret.\n /// \n /// \n /// This is optional for public clients or when using PKCE without client authentication.\n /// \n public string? ClientSecret { get; set; }\n\n /// \n /// Gets or sets the OAuth scopes to request.\n /// \n /// \n /// \n /// When specified, these scopes will be used instead of the scopes advertised by the protected resource.\n /// If not specified, the provider will use the scopes from the protected resource metadata.\n /// \n /// \n /// Common OAuth scopes include \"openid\", \"profile\", \"email\", etc.\n /// \n /// \n public IEnumerable? Scopes { get; set; }\n\n /// \n /// Gets or sets the authorization redirect delegate for handling the OAuth authorization flow.\n /// \n /// \n /// \n /// This delegate is responsible for handling the OAuth authorization URL and obtaining the authorization code.\n /// If not specified, a default implementation will be used that prompts the user to enter the code manually.\n /// \n /// \n /// Custom implementations might open a browser, start an HTTP listener, or use other mechanisms to capture\n /// the authorization code from the OAuth redirect.\n /// \n /// \n public AuthorizationRedirectDelegate? AuthorizationRedirectDelegate { get; set; }\n\n /// \n /// Gets or sets the authorization server selector function.\n /// \n /// \n /// \n /// This function is used to select which authorization server to use when multiple servers are available.\n /// If not specified, the first available server will be selected.\n /// \n /// \n /// The function receives a list of available authorization server URIs and should return the selected server,\n /// or null if no suitable server is found.\n /// \n /// \n public Func, Uri?>? AuthServerSelector { get; set; }\n\n /// \n /// Gets or sets the client name to use during dynamic client registration.\n /// \n /// \n /// This is a human-readable name for the client that may be displayed to users during authorization.\n /// Only used when a is not specified.\n /// \n public string? ClientName { get; set; }\n\n /// \n /// Gets or sets the client URI to use during dynamic client registration.\n /// \n /// \n /// This should be a URL pointing to the client's home page or information page.\n /// Only used when a is not specified.\n /// \n public Uri? ClientUri { get; set; }\n\n /// \n /// Gets or sets additional parameters to include in the query string of the OAuth authorization request\n /// providing extra information or fulfilling specific requirements of the OAuth provider.\n /// \n /// \n /// \n /// Parameters specified cannot override or append to any automatically set parameters like the \"redirect_uri\"\n /// which should instead be configured via .\n /// \n /// \n public IDictionary AdditionalAuthorizationParameters { get; set; } = new Dictionary();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClientOptions.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides configuration options for creating instances.\n/// \n/// \n/// These options are typically passed to when creating a client.\n/// They define client capabilities, protocol version, and other client-specific settings.\n/// \npublic sealed class McpClientOptions\n{\n /// \n /// Gets or sets information about this client implementation, including its name and version.\n /// \n /// \n /// \n /// This information is sent to the server during initialization to identify the client.\n /// It's often displayed in server logs and can be used for debugging and compatibility checks.\n /// \n /// \n /// When not specified, information sourced from the current process will be used.\n /// \n /// \n public Implementation? ClientInfo { get; set; }\n\n /// \n /// Gets or sets the client capabilities to advertise to the server.\n /// \n public ClientCapabilities? Capabilities { get; set; }\n\n /// \n /// Gets or sets the protocol version to request from the server, using a date-based versioning scheme.\n /// \n /// \n /// \n /// The protocol version is a key part of the initialization handshake. The client and server must \n /// agree on a compatible protocol version to communicate successfully.\n /// \n /// \n /// If non-, this version will be sent to the server, and the handshake\n /// will fail if the version in the server's response does not match this version.\n /// If , the client will request the latest version supported by the server\n /// but will allow any supported version that the server advertizes in its response.\n /// \n /// \n public string? ProtocolVersion { get; set; }\n\n /// \n /// Gets or sets a timeout for the client-server initialization handshake sequence.\n /// \n /// \n /// \n /// This timeout determines how long the client will wait for the server to respond during\n /// the initialization protocol handshake. If the server doesn't respond within this timeframe,\n /// an exception will be thrown.\n /// \n /// \n /// Setting an appropriate timeout prevents the client from hanging indefinitely when\n /// connecting to unresponsive servers.\n /// \n /// The default value is 60 seconds.\n /// \n public TimeSpan InitializationTimeout { get; set; } = TimeSpan.FromSeconds(60);\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresUnreferencedCode.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires dynamic access to code that is not referenced\n/// statically, for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when removing unreferenced\n/// code from an application.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresUnreferencedCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of unreferenced code.\n /// \n public RequiresUnreferencedCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of unreferenced code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires unreferenced code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client capability that enables root resource discovery in the Model Context Protocol.\n/// \n/// \n/// \n/// When present in , it indicates that the client supports listing\n/// root URIs that serve as entry points for resource navigation.\n/// \n/// \n/// The roots capability establishes a mechanism for servers to discover and access the hierarchical \n/// structure of resources provided by a client. Root URIs represent top-level entry points from which\n/// servers can navigate to access specific resources.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsCapability\n{\n /// \n /// Gets or sets whether the client supports notifications for changes to the roots list.\n /// \n /// \n /// When set to , the client can notify servers when roots are added, \n /// removed, or modified, allowing servers to refresh their roots cache accordingly.\n /// This enables servers to stay synchronized with client-side changes to available roots.\n /// \n [JsonPropertyName(\"listChanged\")]\n public bool? ListChanged { get; set; }\n\n /// \n /// Gets or sets the handler for requests.\n /// \n /// \n /// This handler is invoked when a client sends a request to retrieve available roots.\n /// The handler receives request parameters and should return a containing the collection of available roots.\n /// \n [JsonIgnore]\n public Func>? RootsHandler { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/RequiresDynamicCodeAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Indicates that the specified method requires the ability to generate new code at runtime,\n/// for example through .\n/// \n/// \n/// This allows tools to understand which methods are unsafe to call when compiling ahead of time.\n/// \n[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]\ninternal sealed class RequiresDynamicCodeAttribute : Attribute\n{\n /// \n /// Initializes a new instance of the class\n /// with the specified message.\n /// \n /// \n /// A message that contains information about the usage of dynamic code.\n /// \n public RequiresDynamicCodeAttribute(string message)\n {\n Message = message;\n }\n\n /// \n /// Gets a message that contains information about the usage of dynamic code.\n /// \n public string Message { get; }\n\n /// \n /// Gets or sets an optional URL that contains more information about the method,\n /// why it requires dynamic code, and what options a consumer has to deal with it.\n /// \n public string? Url { get; set; }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolAnnotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional properties describing a to clients.\n/// \n/// \n/// All properties in are hints.\n/// They are not guaranteed to provide a faithful description of tool behavior (including descriptive properties like `title`).\n/// Clients should never make tool use decisions based on received from untrusted servers.\n/// \npublic sealed class ToolAnnotations\n{\n /// \n /// Gets or sets a human-readable title for the tool that can be displayed to users.\n /// \n /// \n /// \n /// The title provides a more descriptive, user-friendly name for the tool than the tool's\n /// programmatic name. It is intended for display purposes and to help users understand\n /// the tool's purpose at a glance.\n /// \n /// \n /// Unlike the tool name (which follows programmatic naming conventions), the title can\n /// include spaces, special characters, and be phrased in a more natural language style.\n /// \n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets whether the tool may perform destructive updates to its environment.\n /// \n /// \n /// \n /// If , the tool may perform destructive updates to its environment.\n /// If , the tool performs only additive updates.\n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"destructiveHint\")]\n public bool? DestructiveHint { get; set; }\n\n /// \n /// Gets or sets whether calling the tool repeatedly with the same arguments \n /// will have no additional effect on its environment.\n /// \n /// \n /// \n /// This property is most relevant when the tool modifies its environment (ReadOnly = false).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"idempotentHint\")]\n public bool? IdempotentHint { get; set; }\n\n /// \n /// Gets or sets whether this tool may interact with an \"open world\" of external entities.\n /// \n /// \n /// \n /// If , the tool may interact with an unpredictable or dynamic set of entities (like web search).\n /// If , the tool's domain of interaction is closed and well-defined (like memory access).\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"openWorldHint\")]\n public bool? OpenWorldHint { get; set; }\n\n /// \n /// Gets or sets whether this tool does not modify its environment.\n /// \n /// \n /// \n /// If , the tool only performs read operations without changing state.\n /// If , the tool may make modifications to its environment.\n /// \n /// \n /// Read-only tools do not have side effects beyond computational resource usage.\n /// They don't create, update, or delete data in any system.\n /// \n /// \n /// The default is .\n /// \n /// \n [JsonPropertyName(\"readOnlyHint\")]\n public bool? ReadOnlyHint { get; set; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/StringSyntaxAttribute.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// Specifies the syntax used in a string.\n[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\ninternal sealed class StringSyntaxAttribute : Attribute\n{\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n public StringSyntaxAttribute(string syntax)\n {\n Syntax = syntax;\n Arguments = Array.Empty();\n }\n\n /// Initializes the with the identifier of the syntax used.\n /// The syntax identifier.\n /// Optional arguments associated with the specific syntax employed.\n public StringSyntaxAttribute(string syntax, params object?[] arguments)\n {\n Syntax = syntax;\n Arguments = arguments;\n }\n\n /// Gets the identifier of the syntax used.\n public string Syntax { get; }\n\n /// Optional arguments associated with the specific syntax employed.\n public object?[] Arguments { get; }\n\n /// The syntax identifier for strings containing composite formats for string formatting.\n public const string CompositeFormat = nameof(CompositeFormat);\n\n /// The syntax identifier for strings containing date format specifiers.\n public const string DateOnlyFormat = nameof(DateOnlyFormat);\n\n /// The syntax identifier for strings containing date and time format specifiers.\n public const string DateTimeFormat = nameof(DateTimeFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string EnumFormat = nameof(EnumFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string GuidFormat = nameof(GuidFormat);\n\n /// The syntax identifier for strings containing JavaScript Object Notation (JSON).\n public const string Json = nameof(Json);\n\n /// The syntax identifier for strings containing numeric format specifiers.\n public const string NumericFormat = nameof(NumericFormat);\n\n /// The syntax identifier for strings containing regular expressions.\n public const string Regex = nameof(Regex);\n\n /// The syntax identifier for strings containing time format specifiers.\n public const string TimeOnlyFormat = nameof(TimeOnlyFormat);\n\n /// The syntax identifier for strings containing format specifiers.\n public const string TimeSpanFormat = nameof(TimeSpanFormat);\n\n /// The syntax identifier for strings containing URIs.\n public const string Uri = nameof(Uri);\n\n /// The syntax identifier for strings containing XML.\n public const string Xml = nameof(Xml);\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompletionsCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the completions capability for providing auto-completion suggestions\n/// for prompt arguments and resource references.\n/// \n/// \n/// \n/// When enabled, this capability allows a Model Context Protocol server to provide \n/// auto-completion suggestions. This capability is advertised to clients during the initialize handshake.\n/// \n/// \n/// The primary function of this capability is to improve the user experience by offering\n/// contextual suggestions for argument values or resource identifiers based on partial input.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompletionsCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for completion requests.\n /// \n /// \n /// This handler provides auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.\n /// The handler receives a reference type (e.g., \"ref/prompt\" or \"ref/resource\") and the current argument value,\n /// and should return appropriate completion suggestions.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? CompleteHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads that support cursor-based pagination.\n/// \n/// \n/// \n/// Pagination allows API responses to be broken into smaller, manageable chunks when\n/// there are potentially many results to return or when dynamically-computed results\n/// may incur measurable latency.\n/// \n/// \n/// Classes that inherit from implement cursor-based pagination,\n/// where the property serves as an opaque token pointing to the next \n/// set of results.\n/// \n/// \npublic abstract class PaginatedResult : Result\n{\n private protected PaginatedResult()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the pagination position after the last returned result.\n /// \n /// \n /// When a paginated result has more data available, the \n /// property will contain a non- token that can be used in subsequent requests\n /// to fetch the next page. When there are no more results to return, the property\n /// will be .\n /// \n public string? NextCursor { get; set; }\n}"], ["/csharp-sdk/samples/ProtectedMCPServer/Program.cs", "using Microsoft.AspNetCore.Authentication.JwtBearer;\nusing Microsoft.IdentityModel.Tokens;\nusing ModelContextProtocol.AspNetCore.Authentication;\nusing ProtectedMCPServer.Tools;\nusing System.Net.Http.Headers;\nusing System.Security.Claims;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nvar serverUrl = \"http://localhost:7071/\";\nvar inMemoryOAuthServerUrl = \"https://localhost:7029\";\n\nbuilder.Services.AddAuthentication(options =>\n{\n options.DefaultChallengeScheme = McpAuthenticationDefaults.AuthenticationScheme;\n options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;\n})\n.AddJwtBearer(options =>\n{\n // Configure to validate tokens from our in-memory OAuth server\n options.Authority = inMemoryOAuthServerUrl;\n options.TokenValidationParameters = new TokenValidationParameters\n {\n ValidateIssuer = true,\n ValidateAudience = true,\n ValidateLifetime = true,\n ValidateIssuerSigningKey = true,\n ValidAudience = serverUrl, // Validate that the audience matches the resource metadata as suggested in RFC 8707\n ValidIssuer = inMemoryOAuthServerUrl,\n NameClaimType = \"name\",\n RoleClaimType = \"roles\"\n };\n\n options.Events = new JwtBearerEvents\n {\n OnTokenValidated = context =>\n {\n var name = context.Principal?.Identity?.Name ?? \"unknown\";\n var email = context.Principal?.FindFirstValue(\"preferred_username\") ?? \"unknown\";\n Console.WriteLine($\"Token validated for: {name} ({email})\");\n return Task.CompletedTask;\n },\n OnAuthenticationFailed = context =>\n {\n Console.WriteLine($\"Authentication failed: {context.Exception.Message}\");\n return Task.CompletedTask;\n },\n OnChallenge = context =>\n {\n Console.WriteLine($\"Challenging client to authenticate with Entra ID\");\n return Task.CompletedTask;\n }\n };\n})\n.AddMcp(options =>\n{\n options.ResourceMetadata = new()\n {\n Resource = new Uri(serverUrl),\n ResourceDocumentation = new Uri(\"https://docs.example.com/api/weather\"),\n AuthorizationServers = { new Uri(inMemoryOAuthServerUrl) },\n ScopesSupported = [\"mcp:tools\"],\n };\n});\n\nbuilder.Services.AddAuthorization();\n\nbuilder.Services.AddHttpContextAccessor();\nbuilder.Services.AddMcpServer()\n .WithTools()\n .WithHttpTransport();\n\n// Configure HttpClientFactory for weather.gov API\nbuilder.Services.AddHttpClient(\"WeatherApi\", client =>\n{\n client.BaseAddress = new Uri(\"https://api.weather.gov\");\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n});\n\nvar app = builder.Build();\n\napp.UseAuthentication();\napp.UseAuthorization();\n\n// Use the default MCP policy name that we've configured\napp.MapMcp().RequireAuthorization();\n\nConsole.WriteLine($\"Starting MCP server with authorization at {serverUrl}\");\nConsole.WriteLine($\"Using in-memory OAuth server at {inMemoryOAuthServerUrl}\");\nConsole.WriteLine($\"Protected Resource Metadata URL: {serverUrl}.well-known/oauth-protected-resource\");\nConsole.WriteLine(\"Press Ctrl+C to stop the server\");\n\napp.Run(serverUrl);\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcNotification.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification message in the JSON-RPC protocol.\n/// \n/// \n/// Notifications are messages that do not require a response and are not matched with a response message.\n/// They are useful for one-way communication, such as log notifications and progress updates.\n/// Unlike requests, notifications do not include an ID field, since there will be no response to match with it.\n/// \npublic sealed class JsonRpcNotification : JsonRpcMessage\n{\n /// \n /// Gets or sets the name of the notification method.\n /// \n [JsonPropertyName(\"method\")]\n public required string Method { get; init; }\n\n /// \n /// Gets or sets optional parameters for the notification.\n /// \n [JsonPropertyName(\"params\")]\n public JsonNode? Params { get; init; }\n}\n"], ["/csharp-sdk/samples/EverythingServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource(UriTemplate = \"test://direct/text/resource\", Name = \"Direct Text Resource\", MimeType = \"text/plain\")]\n [Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n\n [McpServerResource(UriTemplate = \"test://template/resource/{id}\", Name = \"Template Resource\")]\n [Description(\"A template resource with a numeric ID\")]\n public static ResourceContents TemplateResource(RequestContext requestContext, int id)\n {\n int index = id - 1;\n if ((uint)index >= ResourceGenerator.Resources.Count)\n {\n throw new NotSupportedException($\"Unknown resource: {requestContext.Params?.Uri}\");\n }\n\n var resource = ResourceGenerator.Resources[index];\n return resource.MimeType == \"text/plain\" ?\n new TextResourceContents\n {\n Text = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n } :\n new BlobResourceContents\n {\n Blob = resource.Description!,\n MimeType = resource.MimeType,\n Uri = resource.Uri,\n };\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestMethods.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides constants with the names of common request methods used in the MCP protocol.\n/// \npublic static class RequestMethods\n{\n /// \n /// The name of the request method sent from the client to request a list of the server's tools.\n /// \n public const string ToolsList = \"tools/list\";\n\n /// \n /// The name of the request method sent from the client to request that the server invoke a specific tool.\n /// \n public const string ToolsCall = \"tools/call\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's prompts.\n /// \n public const string PromptsList = \"prompts/list\";\n\n /// \n /// The name of the request method sent by the client to get a prompt provided by the server.\n /// \n public const string PromptsGet = \"prompts/get\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resources.\n /// \n public const string ResourcesList = \"resources/list\";\n\n /// \n /// The name of the request method sent from the client to read a specific server resource.\n /// \n public const string ResourcesRead = \"resources/read\";\n\n /// \n /// The name of the request method sent from the client to request a list of the server's resource templates.\n /// \n public const string ResourcesTemplatesList = \"resources/templates/list\";\n\n /// \n /// The name of the request method sent from the client to request \n /// notifications from the server whenever a particular resource changes.\n /// \n public const string ResourcesSubscribe = \"resources/subscribe\";\n\n /// \n /// The name of the request method sent from the client to request unsubscribing from \n /// notifications from the server.\n /// \n public const string ResourcesUnsubscribe = \"resources/unsubscribe\";\n\n /// \n /// The name of the request method sent from the server to request a list of the client's roots.\n /// \n public const string RootsList = \"roots/list\";\n\n /// \n /// The name of the request method sent by either endpoint to check that the connected endpoint is still alive.\n /// \n public const string Ping = \"ping\";\n\n /// \n /// The name of the request method sent from the client to the server to adjust the logging level.\n /// \n /// \n /// This request allows clients to control which log messages they receive from the server\n /// by setting a minimum severity threshold. After processing this request, the server will\n /// send log messages with severity at or above the specified level to the client as\n /// notifications.\n /// \n public const string LoggingSetLevel = \"logging/setLevel\";\n\n /// \n /// The name of the request method sent from the client to the server to ask for completion suggestions.\n /// \n /// \n /// This is used to provide autocompletion-like functionality for arguments in a resource reference or a prompt template.\n /// The client provides a reference (resource or prompt), argument name, and partial value, and the server \n /// responds with matching completion options.\n /// \n public const string CompletionComplete = \"completion/complete\";\n\n /// \n /// The name of the request method sent from the server to sample an large language model (LLM) via the client.\n /// \n /// \n /// This request allows servers to utilize an LLM available on the client side to generate text or image responses\n /// based on provided messages. It is part of the sampling capability in the Model Context Protocol and enables servers to access\n /// client-side AI models without needing direct API access to those models.\n /// \n public const string SamplingCreateMessage = \"sampling/createMessage\";\n\n /// \n /// The name of the request method sent from the client to the server to elicit additional information from the user via the client.\n /// \n /// \n /// This request is used when the server needs more information from the client to proceed with a task or interaction.\n /// Servers can request structured data from users, with optional JSON schemas to validate responses.\n /// \n public const string ElicitationCreate = \"elicitation/create\";\n\n /// \n /// The name of the request method sent from the client to the server when it first connects, asking it initialize.\n /// \n /// \n /// The initialize request is the first request sent by the client to the server. It provides client information\n /// and capabilities to the server during connection establishment. The server responds with its own capabilities\n /// and information, establishing the protocol version and available features for the session.\n /// \n public const string Initialize = \"initialize\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/TokenProgress.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Provides an tied to a specific progress token and that will issue\n/// progress notifications on the supplied endpoint.\n/// \ninternal sealed class TokenProgress(IMcpEndpoint endpoint, ProgressToken progressToken) : IProgress\n{\n /// \n public void Report(ProgressNotificationValue value)\n {\n _ = endpoint.NotifyProgressAsync(progressToken, value, CancellationToken.None);\n }\n}\n"], ["/csharp-sdk/samples/ChatWithTools/Program.cs", "using Microsoft.Extensions.AI;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Client;\nusing OpenAI;\nusing OpenTelemetry;\nusing OpenTelemetry.Logs;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\n\nusing var tracerProvider = Sdk.CreateTracerProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddSource(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var metricsProvider = Sdk.CreateMeterProviderBuilder()\n .AddHttpClientInstrumentation()\n .AddMeter(\"*\")\n .AddOtlpExporter()\n .Build();\nusing var loggerFactory = LoggerFactory.Create(builder => builder.AddOpenTelemetry(opt => opt.AddOtlpExporter()));\n\n// Connect to an MCP server\nConsole.WriteLine(\"Connecting client to MCP 'everything' server\");\n\n// Create OpenAI client (or any other compatible with IChatClient)\n// Provide your own OPENAI_API_KEY via an environment variable.\nvar openAIClient = new OpenAIClient(Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")).GetChatClient(\"gpt-4o-mini\");\n\n// Create a sampling client.\nusing IChatClient samplingClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\nvar mcpClient = await McpClientFactory.CreateAsync(\n new StdioClientTransport(new()\n {\n Command = \"npx\",\n Arguments = [\"-y\", \"--verbose\", \"@modelcontextprotocol/server-everything\"],\n Name = \"Everything\",\n }),\n clientOptions: new()\n {\n Capabilities = new() { Sampling = new() { SamplingHandler = samplingClient.CreateSamplingHandler() } },\n },\n loggerFactory: loggerFactory);\n\n// Get all available tools\nConsole.WriteLine(\"Tools available:\");\nvar tools = await mcpClient.ListToolsAsync();\nforeach (var tool in tools)\n{\n Console.WriteLine($\" {tool}\");\n}\n\nConsole.WriteLine();\n\n// Create an IChatClient that can use the tools.\nusing IChatClient chatClient = openAIClient.AsIChatClient()\n .AsBuilder()\n .UseFunctionInvocation()\n .UseOpenTelemetry(loggerFactory: loggerFactory, configure: o => o.EnableSensitiveData = true)\n .Build();\n\n// Have a conversation, making all tools available to the LLM.\nList messages = [];\nwhile (true)\n{\n Console.Write(\"Q: \");\n messages.Add(new(ChatRole.User, Console.ReadLine()));\n\n List updates = [];\n await foreach (var update in chatClient.GetStreamingResponseAsync(messages, new() { Tools = [.. tools] }))\n {\n Console.Write(update);\n updates.Add(update);\n }\n Console.WriteLine();\n\n messages.AddMessages(updates);\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/Channels/ChannelExtensions.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading.Channels;\n\ninternal static class ChannelExtensions\n{\n public static async IAsyncEnumerable ReadAllAsync(this ChannelReader reader, [EnumeratorCancellation] CancellationToken cancellationToken)\n {\n while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))\n {\n while (reader.TryRead(out var item))\n {\n yield return item;\n }\n }\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/ProgressNotificationValue.cs", "namespace ModelContextProtocol;\n\n/// Provides a progress value that can be sent using .\npublic sealed class ProgressNotificationValue\n{\n /// \n /// Gets or sets the progress thus far.\n /// \n /// \n /// \n /// This value typically represents either a percentage (0-100) or the number of items processed so far (when used with the property).\n /// \n /// \n /// When reporting progress, this value should increase monotonically as the operation proceeds.\n /// Values are typically between 0 and 100 when representing percentages, or can be any positive number\n /// when representing completed items in combination with the property.\n /// \n /// \n public required float Progress { get; init; }\n\n /// Gets or sets the total number of items to process (or total progress required), if known.\n public float? Total { get; init; }\n\n /// Gets or sets an optional message describing the current progress.\n public string? Message { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ProtectedResourceMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the resource metadata for OAuth authorization as defined in RFC 9396.\n/// Defined by RFC 9728.\n/// \npublic sealed class ProtectedResourceMetadata\n{\n /// \n /// The resource URI.\n /// \n /// \n /// REQUIRED. The protected resource's resource identifier.\n /// \n [JsonPropertyName(\"resource\")]\n public required Uri Resource { get; set; }\n\n /// \n /// The list of authorization server URIs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of OAuth authorization server issuer identifiers\n /// for authorization servers that can be used with this protected resource.\n /// \n [JsonPropertyName(\"authorization_servers\")]\n public List AuthorizationServers { get; set; } = [];\n\n /// \n /// The supported bearer token methods.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the supported methods of sending an OAuth 2.0 bearer token\n /// to the protected resource. Defined values are [\"header\", \"body\", \"query\"].\n /// \n [JsonPropertyName(\"bearer_methods_supported\")]\n public List BearerMethodsSupported { get; set; } = [\"header\"];\n\n /// \n /// The supported scopes.\n /// \n /// \n /// RECOMMENDED. JSON array containing a list of scope values that are used in authorization\n /// requests to request access to this protected resource.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List ScopesSupported { get; set; } = [];\n\n /// \n /// URL of the protected resource's JSON Web Key (JWK) Set document.\n /// \n /// \n /// OPTIONAL. This contains public keys belonging to the protected resource, such as signing key(s)\n /// that the resource server uses to sign resource responses. This URL MUST use the https scheme.\n /// \n [JsonPropertyName(\"jwks_uri\")]\n public Uri? JwksUri { get; set; }\n\n /// \n /// List of the JWS signing algorithms supported by the protected resource for signing resource responses.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS signing algorithms (alg values) supported by the protected resource\n /// for signing resource responses. No default algorithms are implied if this entry is omitted. The value none MUST NOT be used.\n /// \n [JsonPropertyName(\"resource_signing_alg_values_supported\")]\n public List? ResourceSigningAlgValuesSupported { get; set; }\n\n /// \n /// Human-readable name of the protected resource intended for display to the end user.\n /// \n /// \n /// RECOMMENDED. It is recommended that protected resource metadata include this field.\n /// The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_name\")]\n public string? ResourceName { get; set; }\n\n /// \n /// The URI to the resource documentation.\n /// \n /// \n /// OPTIONAL. URL of a page containing human-readable information that developers might want or need to know\n /// when using the protected resource.\n /// \n [JsonPropertyName(\"resource_documentation\")]\n public Uri? ResourceDocumentation { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's requirements.\n /// \n /// \n /// OPTIONAL. Information about how the client can use the data provided by the protected resource.\n /// \n [JsonPropertyName(\"resource_policy_uri\")]\n public Uri? ResourcePolicyUri { get; set; }\n\n /// \n /// URL of a page containing human-readable information about the protected resource's terms of service.\n /// \n /// \n /// OPTIONAL. The value of this field MAY be internationalized.\n /// \n [JsonPropertyName(\"resource_tos_uri\")]\n public Uri? ResourceTosUri { get; set; }\n\n /// \n /// Boolean value indicating protected resource support for mutual-TLS client certificate-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"tls_client_certificate_bound_access_tokens\")]\n public bool? TlsClientCertificateBoundAccessTokens { get; set; }\n\n /// \n /// List of the authorization details type values supported by the resource server.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the authorization details type values supported by the resource server\n /// when the authorization_details request parameter is used.\n /// \n [JsonPropertyName(\"authorization_details_types_supported\")]\n public List? AuthorizationDetailsTypesSupported { get; set; }\n\n /// \n /// List of the JWS algorithm values supported by the resource server for validating DPoP proof JWTs.\n /// \n /// \n /// OPTIONAL. JSON array containing a list of the JWS alg values supported by the resource server\n /// for validating Demonstrating Proof of Possession (DPoP) proof JWTs.\n /// \n [JsonPropertyName(\"dpop_signing_alg_values_supported\")]\n public List? DpopSigningAlgValuesSupported { get; set; }\n\n /// \n /// Boolean value specifying whether the protected resource always requires the use of DPoP-bound access tokens.\n /// \n /// \n /// OPTIONAL. If omitted, the default value is false.\n /// \n [JsonPropertyName(\"dpop_bound_access_tokens_required\")]\n public bool? DpopBoundAccessTokensRequired { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServer.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) server that connects to and communicates with an MCP client.\n/// \npublic interface IMcpServer : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the client.\n /// \n /// \n /// \n /// These capabilities are established during the initialization handshake and indicate\n /// which features the client supports, such as sampling, roots, and other\n /// protocol-specific functionality.\n /// \n /// \n /// Server implementations can check these capabilities to determine which features\n /// are available when interacting with the client.\n /// \n /// \n ClientCapabilities? ClientCapabilities { get; }\n\n /// \n /// Gets the version and implementation information of the connected client.\n /// \n /// \n /// \n /// This property contains identification information about the client that has connected to this server,\n /// including its name and version. This information is provided by the client during initialization.\n /// \n /// \n /// Server implementations can use this information for logging, tracking client versions, \n /// or implementing client-specific behaviors.\n /// \n /// \n Implementation? ClientInfo { get; }\n\n /// \n /// Gets the options used to construct this server.\n /// \n /// \n /// These options define the server's capabilities, protocol version, and other configuration\n /// settings that were used to initialize the server.\n /// \n McpServerOptions ServerOptions { get; }\n\n /// \n /// Gets the service provider for the server.\n /// \n IServiceProvider? Services { get; }\n\n /// Gets the last logging level set by the client, or if it's never been set.\n LoggingLevel? LoggingLevel { get; }\n\n /// \n /// Runs the server, listening for and handling client requests.\n /// \n Task RunAsync(CancellationToken cancellationToken = default);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/ResourceMetadataRequestContext.cs", "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Http;\nusing ModelContextProtocol.Authentication;\n\nnamespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Context for resource metadata request events.\n/// \npublic class ResourceMetadataRequestContext : HandleRequestContext\n{\n /// \n /// Initializes a new instance of the class.\n /// \n /// The HTTP context.\n /// The authentication scheme.\n /// The authentication options.\n public ResourceMetadataRequestContext(\n HttpContext context,\n AuthenticationScheme scheme,\n McpAuthenticationOptions options)\n : base(context, scheme, options)\n {\n }\n\n /// \n /// Gets or sets the protected resource metadata for the current request.\n /// \n public ProtectedResourceMetadata? ResourceMetadata { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitationCapability.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the capability for a client to provide server-requested additional information during interactions.\n/// \n/// \n/// \n/// This capability enables the MCP client to respond to elicitation requests from an MCP server.\n/// \n/// \n/// When this capability is enabled, an MCP server can request the client to provide additional information\n/// during interactions. The client must set a to process these requests.\n/// \n/// \npublic sealed class ElicitationCapability\n{\n // Currently empty in the spec, but may be extended in the future.\n\n /// \n /// Gets or sets the handler for processing requests.\n /// \n /// \n /// \n /// This handler function is called when an MCP server requests the client to provide additional\n /// information during interactions. The client must set this property for the elicitation capability to work.\n /// \n /// \n /// The handler receives message parameters and a cancellation token.\n /// It should return a containing the response to the elicitation request.\n /// \n /// \n [JsonIgnore]\n public Func>? ElicitationHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationRedirectDelegate.cs", "\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a method that handles the OAuth authorization URL and returns the authorization code.\n/// \n/// The authorization URL that the user needs to visit.\n/// The redirect URI where the authorization code will be sent.\n/// The cancellation token.\n/// A task that represents the asynchronous operation. The task result contains the authorization code if successful, or null if the operation failed or was cancelled.\n/// \n/// \n/// This delegate provides SDK consumers with full control over how the OAuth authorization flow is handled.\n/// Implementers can choose to:\n/// \n/// \n/// Start a local HTTP server and open a browser (default behavior)\n/// Display the authorization URL to the user for manual handling\n/// Integrate with a custom UI or authentication flow\n/// Use a different redirect mechanism altogether\n/// \n/// \n/// The implementation should handle user interaction to visit the authorization URL and extract\n/// the authorization code from the callback. The authorization code is typically provided as\n/// a query parameter in the redirect URI callback.\n/// \n/// \npublic delegate Task AuthorizationRedirectDelegate(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken);"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolResult.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// \n/// Any errors that originate from the tool should be reported inside the result\n/// object, with set to true, rather than as a .\n/// \n/// \n/// However, any errors in finding the tool, an error indicating that the\n/// server does not support tool calls, or any other exceptional conditions,\n/// should be reported as an MCP error response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CallToolResult : Result\n{\n /// \n /// Gets or sets the response content from the tool call.\n /// \n [JsonPropertyName(\"content\")]\n public IList Content { get; set; } = [];\n\n /// \n /// Gets or sets an optional JSON object representing the structured result of the tool call.\n /// \n [JsonPropertyName(\"structuredContent\")]\n public JsonNode? StructuredContent { get; set; }\n\n /// \n /// Gets or sets an indication of whether the tool call was unsuccessful.\n /// \n /// \n /// When set to , it signifies that the tool execution failed.\n /// Tool errors are reported with this property set to and details in the \n /// property, rather than as protocol-level errors. This allows LLMs to see that an error occurred\n /// and potentially self-correct in subsequent requests.\n /// \n [JsonPropertyName(\"isError\")]\n public bool? IsError { get; set; }\n}\n"], ["/csharp-sdk/src/Common/CancellableStreamReader/TextReaderExtensions.cs", "namespace System.IO;\n\ninternal static class TextReaderExtensions\n{\n public static ValueTask ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)\n {\n if (reader is CancellableStreamReader cancellableReader)\n {\n return cancellableReader.ReadLineAsync(cancellationToken)!;\n }\n\n cancellationToken.ThrowIfCancellationRequested();\n return new ValueTask(reader.ReadLineAsync());\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request sent by a client to a server during the protocol handshake.\n/// \n/// \n/// \n/// The is the first message sent in the Model Context Protocol\n/// communication flow. It establishes the connection between client and server, negotiates the protocol\n/// version, and declares the client's capabilities.\n/// \n/// \n/// After sending this request, the client should wait for an response\n/// before sending an notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the client wants to use.\n /// \n /// \n /// \n /// Protocol version is specified using a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// The client and server must agree on a protocol version to communicate successfully.\n /// \n /// \n /// During initialization, the server will check if it supports this requested version. If there's a \n /// mismatch, the server will reject the connection with a version mismatch error.\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the client's capabilities.\n /// \n /// \n /// Capabilities define the features the client supports, such as \"sampling\" or \"roots\".\n /// \n [JsonPropertyName(\"capabilities\")]\n public ClientCapabilities? Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the client implementation, including its name and version.\n /// \n /// \n /// This information is required during the initialization handshake to identify the client.\n /// Servers may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"clientInfo\")]\n public required Implementation ClientInfo { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingMessageNotificationParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a log message is generated.\n/// \n/// \n/// \n/// Logging notifications allow servers to communicate diagnostic information to clients with varying severity levels.\n/// Clients can filter these messages based on the and properties.\n/// \n/// \n/// If no request has been sent from the client, the server may decide which\n/// messages to send automatically.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class LoggingMessageNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the severity of this log message.\n /// \n [JsonPropertyName(\"level\")]\n public LoggingLevel Level { get; init; }\n\n /// \n /// Gets or sets an optional name of the logger issuing this message.\n /// \n /// \n /// \n /// typically represents a category or component in the server's logging system.\n /// The logger name is useful for filtering and routing log messages in client applications.\n /// \n /// \n /// When implementing custom servers, choose clear, hierarchical logger names to help\n /// clients understand the source of log messages.\n /// \n /// \n [JsonPropertyName(\"logger\")]\n public string? Logger { get; init; }\n\n /// \n /// Gets or sets the data to be logged, such as a string message.\n /// \n [JsonPropertyName(\"data\")]\n public JsonElement? Data { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// request from a server to sample an LLM via the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageRequestParams : RequestParams\n{\n /// \n /// Gets or sets an indication as to which server contexts should be included in the prompt.\n /// \n /// \n /// The client may ignore this request.\n /// \n [JsonPropertyName(\"includeContext\")]\n public ContextInclusion? IncludeContext { get; init; }\n\n /// \n /// Gets or sets the maximum number of tokens to generate in the LLM response, as requested by the server.\n /// \n /// \n /// A token is generally a word or part of a word in the text. Setting this value helps control \n /// response length and computation time. The client may choose to sample fewer tokens than requested.\n /// \n [JsonPropertyName(\"maxTokens\")]\n public int? MaxTokens { get; init; }\n\n /// \n /// Gets or sets the messages requested by the server to be included in the prompt.\n /// \n [JsonPropertyName(\"messages\")]\n public required IReadOnlyList Messages { get; init; }\n\n /// \n /// Gets or sets optional metadata to pass through to the LLM provider.\n /// \n /// \n /// The format of this metadata is provider-specific and can include model-specific settings or\n /// configuration that isn't covered by standard parameters. This allows for passing custom parameters \n /// that are specific to certain AI models or providers.\n /// \n [JsonPropertyName(\"metadata\")]\n public JsonElement? Metadata { get; init; }\n\n /// \n /// Gets or sets the server's preferences for which model to select.\n /// \n /// \n /// \n /// The client may ignore these preferences.\n /// \n /// \n /// These preferences help the client make an appropriate model selection based on the server's priorities\n /// for cost, speed, intelligence, and specific model hints.\n /// \n /// \n /// When multiple dimensions are specified (cost, speed, intelligence), the client should balance these\n /// based on their relative values. If specific model hints are provided, the client should evaluate them\n /// in order and prioritize them over numeric priorities.\n /// \n /// \n [JsonPropertyName(\"modelPreferences\")]\n public ModelPreferences? ModelPreferences { get; init; }\n\n /// \n /// Gets or sets optional sequences of characters that signal the LLM to stop generating text when encountered.\n /// \n /// \n /// \n /// When the model generates any of these sequences during sampling, text generation stops immediately,\n /// even if the maximum token limit hasn't been reached. This is useful for controlling generation \n /// endings or preventing the model from continuing beyond certain points.\n /// \n /// \n /// Stop sequences are typically case-sensitive, and typically the LLM will only stop generation when a produced\n /// sequence exactly matches one of the provided sequences. Common uses include ending markers like \"END\", punctuation\n /// like \".\", or special delimiter sequences like \"###\".\n /// \n /// \n [JsonPropertyName(\"stopSequences\")]\n public IReadOnlyList? StopSequences { get; init; }\n\n /// \n /// Gets or sets an optional system prompt the server wants to use for sampling.\n /// \n /// \n /// The client may modify or omit this prompt.\n /// \n [JsonPropertyName(\"systemPrompt\")]\n public string? SystemPrompt { get; init; }\n\n /// \n /// Gets or sets the temperature to use for sampling, as requested by the server.\n /// \n [JsonPropertyName(\"temperature\")]\n public float? Temperature { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializeResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request sent to the server during connection establishment.\n/// \n/// \n/// \n/// The is sent by the server in response to an \n/// message from the client. It contains information about the server, its capabilities, and the protocol version\n/// that will be used for the session.\n/// \n/// \n/// After receiving this response, the client should send an \n/// notification to complete the handshake.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class InitializeResult : Result\n{\n /// \n /// Gets or sets the version of the Model Context Protocol that the server will use for this session.\n /// \n /// \n /// \n /// This is the protocol version the server has agreed to use, which should match the client's \n /// requested version. If there's a mismatch, the client should throw an exception to prevent \n /// communication issues due to incompatible protocol versions.\n /// \n /// \n /// The protocol uses a date-based versioning scheme in the format \"YYYY-MM-DD\".\n /// \n /// \n /// See the protocol specification for version details.\n /// \n /// \n [JsonPropertyName(\"protocolVersion\")]\n public required string ProtocolVersion { get; init; }\n\n /// \n /// Gets or sets the server's capabilities.\n /// \n /// \n /// This defines the features the server supports, such as \"tools\", \"prompts\", \"resources\", or \"logging\", \n /// and other protocol-specific functionality.\n /// \n [JsonPropertyName(\"capabilities\")]\n public required ServerCapabilities Capabilities { get; init; }\n\n /// \n /// Gets or sets information about the server implementation, including its name and version.\n /// \n /// \n /// This information identifies the server during the initialization handshake.\n /// Clients may use this information for logging, debugging, or compatibility checks.\n /// \n [JsonPropertyName(\"serverInfo\")]\n public required Implementation ServerInfo { get; init; }\n\n /// \n /// Gets or sets optional instructions for using the server and its features.\n /// \n /// \n /// \n /// These instructions provide guidance to clients on how to effectively use the server's capabilities.\n /// They can include details about available tools, expected input formats, limitations,\n /// or any other information that helps clients interact with the server properly.\n /// \n /// \n /// Client applications often use these instructions as system messages for LLM interactions\n /// to provide context about available functionality.\n /// \n /// \n [JsonPropertyName(\"instructions\")]\n public string? Instructions { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Completion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a completion object in the server's response to a request.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Completion\n{\n /// \n /// Gets or sets an array of completion values (auto-suggestions) for the requested input.\n /// \n /// \n /// This collection contains the actual text strings to be presented to users as completion suggestions.\n /// The array will be empty if no suggestions are available for the current input.\n /// Per the specification, this should not exceed 100 items.\n /// \n [JsonPropertyName(\"values\")]\n public IList Values { get; set; } = [];\n\n /// \n /// Gets or sets the total number of completion options available.\n /// \n /// \n /// This can exceed the number of values actually sent in the response.\n /// \n [JsonPropertyName(\"total\")]\n public int? Total { get; set; }\n\n /// \n /// Gets or sets an indicator as to whether there are additional completion options beyond \n /// those provided in the current response, even if the exact total is unknown.\n /// \n [JsonPropertyName(\"hasMore\")]\n public bool? HasMore { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CancelledNotificationParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a notification indicating that a request has been cancelled by the client,\n/// and that any associated processing should cease immediately.\n/// \n/// \n/// This class is typically used in conjunction with the \n/// method identifier. When a client sends this notification, the server should attempt to\n/// cancel any ongoing operations associated with the specified request ID.\n/// \npublic sealed class CancelledNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the ID of the request to cancel.\n /// \n /// \n /// This must match the ID of an in-flight request that the sender wishes to cancel.\n /// \n [JsonPropertyName(\"requestId\")]\n public RequestId RequestId { get; set; }\n\n /// \n /// Gets or sets an optional string describing the reason for the cancellation request.\n /// \n [JsonPropertyName(\"reason\")]\n public string? Reason { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Prompt.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a prompt that the server offers.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Prompt : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets an optional description of what this prompt provides.\n /// \n /// \n /// \n /// This description helps developers understand the purpose and use cases for the prompt.\n /// It should explain what the prompt is designed to accomplish and any important context.\n /// \n /// \n /// The description is typically used in documentation, UI displays, and for providing context\n /// to client applications that may need to choose between multiple available prompts.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets a list of arguments that this prompt accepts for templating and customization.\n /// \n /// \n /// \n /// This list defines the arguments that can be provided when requesting the prompt.\n /// Each argument specifies metadata like name, description, and whether it's required.\n /// \n /// \n /// When a client makes a request, it can provide values for these arguments\n /// which will be substituted into the prompt template or otherwise used to render the prompt.\n /// \n /// \n [JsonPropertyName(\"arguments\")]\n public IList? Arguments { get; set; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptMessage.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message within the Model Context Protocol (MCP) system, used for communication between clients and AI models.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be\n/// text, images, audio, or embedded resources.\n/// \n/// \n/// This class is similar to , but with enhanced support for embedding resources from the MCP server.\n/// It serves as a core data structure in the MCP message exchange flow, particularly in prompt formation and model responses.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent complete conversations or prompt sequences. They can be converted to and from \n/// objects using the extension methods and\n/// .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptMessage\n{\n /// \n /// Gets or sets the content of the message, which can be text, image, audio, or an embedded resource.\n /// \n /// \n /// The object contains all the message payload, whether it's simple text,\n /// base64-encoded binary data (for images/audio), or a reference to an embedded resource.\n /// The property indicates the specific content type.\n /// \n [JsonPropertyName(\"content\")]\n public ContentBlock Content { get; set; } = new TextContentBlock { Text = \"\" };\n\n /// \n /// Gets or sets the role of the message sender, specifying whether it's from a \"user\" or an \"assistant\".\n /// \n /// \n /// In the Model Context Protocol, each message must have a clear role assignment to maintain\n /// the conversation flow. User messages represent queries or inputs from users, while assistant\n /// messages represent responses generated by AI models.\n /// \n [JsonPropertyName(\"role\")]\n public Role Role { get; set; } = Role.User;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptArgument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument that a prompt can accept for templating and customization.\n/// \n/// \n/// \n/// The class defines metadata for arguments that can be provided\n/// to a prompt. These arguments are used to customize or parameterize prompts when they are \n/// retrieved using requests.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptArgument : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets a human-readable description of the argument's purpose and expected values.\n /// \n /// \n /// This description helps developers understand what information should be provided\n /// for this argument and how it will affect the generated prompt.\n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; } = string.Empty;\n\n /// \n /// Gets or sets an indication as to whether this argument must be provided when requesting the prompt.\n /// \n /// \n /// When set to , the client must include this argument when making a request.\n /// If a required argument is missing, the server should respond with an error.\n /// \n [JsonPropertyName(\"required\")]\n public bool? Required { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing members that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing members that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithResourcesFromAssembly, it enables automatic registration of resources without explicitly listing each\n/// resource class. The attribute is not necessary when a reference to the type is provided directly to a method\n/// like McpServerBuilderExtensions.WithResources.\n/// \n/// \n/// Within a class marked with this attribute, individual members that should be exposed as\n/// resources must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerResourceTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Resource.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a known resource that the server is capable of reading.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class Resource : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the URI of this resource.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a description of what this resource represents.\n /// \n /// \n /// \n /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \\\"hint\\\" to the model.\n /// \n /// \n /// The description should provide clear context about the resource's content, format, and purpose.\n /// This helps AI models make better decisions about when to access or reference the resource.\n /// \n /// \n /// Client applications can also use this description for display purposes in user interfaces\n /// or to help users understand the available resources.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; init; }\n\n /// \n /// Gets or sets the MIME type of this resource.\n /// \n /// \n /// \n /// specifies the format of the resource content, helping clients to properly interpret and display the data.\n /// Common MIME types include \"text/plain\" for plain text, \"application/pdf\" for PDF documents,\n /// \"image/png\" for PNG images, and \"application/json\" for JSON data.\n /// \n /// \n /// This property may be if the MIME type is unknown or not applicable for the resource.\n /// \n /// \n [JsonPropertyName(\"mimeType\")]\n public string? MimeType { get; init; }\n\n /// \n /// Gets or sets optional annotations for the resource.\n /// \n /// \n /// These annotations can be used to specify the intended audience (, , or both)\n /// and the priority level of the resource. Clients can use this information to filter or prioritize resources for different roles.\n /// \n [JsonPropertyName(\"annotations\")]\n public Annotations? Annotations { get; init; }\n\n /// \n /// Gets or sets the size of the raw resource content (before base64 encoding), in bytes, if known.\n /// \n /// \n /// This can be used by applications to display file sizes and estimate context window usage.\n /// \n [JsonPropertyName(\"size\")]\n public long? Size { get; init; }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpErrorCode.cs", "namespace ModelContextProtocol;\n\n/// \n/// Represents standard JSON-RPC error codes as defined in the MCP specification.\n/// \npublic enum McpErrorCode\n{\n /// \n /// Indicates that the JSON received could not be parsed.\n /// \n /// \n /// This error occurs when the input contains malformed JSON or incorrect syntax.\n /// \n ParseError = -32700,\n\n /// \n /// Indicates that the JSON payload does not conform to the expected Request object structure.\n /// \n /// \n /// The request is considered invalid if it lacks required fields or fails to follow the JSON-RPC protocol.\n /// \n InvalidRequest = -32600,\n\n /// \n /// Indicates that the requested method does not exist or is not available on the server.\n /// \n /// \n /// This error is returned when the method name specified in the request cannot be found.\n /// \n MethodNotFound = -32601,\n\n /// \n /// Indicates that one or more parameters provided in the request are invalid.\n /// \n /// \n /// This error is returned when the parameters do not match the expected method signature or constraints.\n /// This includes cases where required parameters are missing or not understood, such as when a name for\n /// a tool or prompt is not recognized.\n /// \n InvalidParams = -32602,\n\n /// \n /// Indicates that an internal error occurred while processing the request.\n /// \n /// \n /// This error is used when the endpoint encounters an unexpected condition that prevents it from fulfilling the request.\n /// \n InternalError = -32603,\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/IBaseMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// Provides a base interface for metadata with name (identifier) and title (display name) properties.\npublic interface IBaseMetadata\n{\n /// \n /// Gets or sets the unique identifier for this item.\n /// \n [JsonPropertyName(\"name\")]\n string Name { get; set; }\n\n /// \n /// Gets or sets a title.\n /// \n /// \n /// This is intended for UI and end-user contexts. It is optimized to be human-readable and easily understood,\n /// even by those unfamiliar with domain-specific terminology.\n /// If not provided, may be used for display (except for tools, where , if present, \n /// should be given precedence over using ).\n /// \n [JsonPropertyName(\"title\")]\n string? Title { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol/IMcpServerBuilder.cs", "using ModelContextProtocol.Server;\n\nnamespace Microsoft.Extensions.DependencyInjection;\n\n/// \n/// Provides a builder for configuring instances.\n/// \n/// \n/// \n/// The interface provides a fluent API for configuring Model Context Protocol (MCP) servers\n/// when using dependency injection. It exposes methods for registering tools, prompts, custom request handlers,\n/// and server transports, allowing for comprehensive server configuration through a chain of method calls.\n/// \n/// \n/// The builder is obtained from the extension\n/// method and provides access to the underlying service collection via the property.\n/// \n/// \npublic interface IMcpServerBuilder\n{\n /// \n /// Gets the associated service collection.\n /// \n IServiceCollection Services { get; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerToolTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithToolsFromAssembly, it enables automatic registration of tools without explicitly listing each tool\n/// class. The attribute is not necessary when a reference to the type is provided directly to a method like WithTools.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// tools must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerToolTypeAttribute : Attribute;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerPromptTypeAttribute.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Used to attribute a type containing methods that should be exposed as s.\n/// \n/// \n/// \n/// This attribute is used to mark a class containing methods that should be automatically\n/// discovered and registered as s. When combined with discovery methods like\n/// WithPromptsFromAssembly, it enables automatic registration of prompts without explicitly listing each prompt class.\n/// The attribute is not necessary when a reference to the type is provided directly to a method like WithPrompts.\n/// \n/// \n/// Within a class marked with this attribute, individual methods that should be exposed as\n/// prompts must be marked with the .\n/// \n/// \n[AttributeUsage(AttributeTargets.Class)]\npublic sealed class McpServerPromptTypeAttribute : Attribute;\n"], ["/csharp-sdk/samples/EverythingServer/Prompts/ComplexPromptType.cs", "using EverythingServer.Tools;\nusing Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class ComplexPromptType\n{\n [McpServerPrompt(Name = \"complex_prompt\"), Description(\"A prompt with arguments\")]\n public static IEnumerable ComplexPrompt(\n [Description(\"Temperature setting\")] int temperature,\n [Description(\"Output style\")] string? style = null)\n {\n return [\n new ChatMessage(ChatRole.User,$\"This is a complex prompt with arguments: temperature={temperature}, style={style}\"),\n new ChatMessage(ChatRole.Assistant, \"I understand. You've provided a complex prompt with temperature and style arguments. How would you like me to proceed?\"),\n new ChatMessage(ChatRole.User, [new DataContent(TinyImageTool.MCP_TINY_IMAGE)])\n ];\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceUpdatedNotificationParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification sent whenever a subscribed resource changes.\n/// \n/// \n/// \n/// When a client subscribes to resource updates using , the server will\n/// send notifications with this payload whenever the subscribed resource is modified. These notifications\n/// allow clients to maintain synchronized state without needing to poll the server for changes.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceUpdatedNotificationParams : NotificationParams\n{\n /// \n /// Gets or sets the URI of the resource that was updated.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/NopProgress.cs", "namespace ModelContextProtocol;\n\n/// Provides an that's a nop.\ninternal sealed class NullProgress : IProgress\n{\n /// \n /// Gets the singleton instance of the class that performs no operations when progress is reported.\n /// \n /// \n /// Use this property when you need to provide an implementation \n /// but don't need to track or report actual progress.\n /// \n public static NullProgress Instance { get; } = new();\n\n /// \n public void Report(ProgressNotificationValue value)\n {\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CallToolRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to invoke a tool provided by the server.\n/// \n/// \n/// The server will respond with a containing the result of the tool invocation.\n/// See the schema for details.\n/// \npublic sealed class CallToolRequestParams : RequestParams\n{\n /// Gets or sets the name of the tool to invoke.\n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets optional arguments to pass to the tool when invoking it on the server.\n /// \n /// \n /// This dictionary contains the parameter values to be passed to the tool. Each key-value pair represents \n /// a parameter name and its corresponding argument value.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client,\n/// containing available resource templates.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover \n/// available resource templates on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resource templates.\n/// The server can provide the property to indicate there are more\n/// resource templates available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourceTemplatesResult : PaginatedResult\n{\n /// \n /// Gets or sets a list of resource templates that the server offers.\n /// \n /// \n /// This collection contains all the resource templates returned in the current page of results.\n /// Each provides metadata about resources available on the server,\n /// including URI templates, names, descriptions, and MIME types.\n /// \n [JsonPropertyName(\"resourceTemplates\")]\n public IList ResourceTemplates { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Annotations.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents annotations that can be attached to content, resources, and resource templates.\n/// \n/// \n/// Annotations enable filtering and prioritization of content for different audiences.\n/// See the schema for details.\n/// \npublic sealed class Annotations\n{\n /// \n /// Gets or sets the intended audience for this content as an array of values.\n /// \n [JsonPropertyName(\"audience\")]\n public IList? Audience { get; init; }\n\n /// \n /// Gets or sets a value indicating how important this data is for operating the server.\n /// \n /// \n /// The value is a floating-point number between 0 and 1, where 0 represents the lowest priority\n /// 1 represents highest priority.\n /// \n [JsonPropertyName(\"priority\")]\n public float? Priority { get; init; }\n\n /// \n /// Gets or sets the moment the resource was last modified.\n /// \n /// \n /// The corresponding JSON should be an ISO 8601 formatted string (e.g., \\\"2025-01-12T15:00:58Z\\\").\n /// Examples: last activity timestamp in an open file, timestamp when the resource was attached, etc.\n /// \n [JsonPropertyName(\"lastModified\")]\n public DateTimeOffset? LastModified { get; set; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/IMcpClient.cs", "using ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Represents an instance of a Model Context Protocol (MCP) client that connects to and communicates with an MCP server.\n/// \npublic interface IMcpClient : IMcpEndpoint\n{\n /// \n /// Gets the capabilities supported by the connected server.\n /// \n /// The client is not connected.\n ServerCapabilities ServerCapabilities { get; }\n\n /// \n /// Gets the implementation information of the connected server.\n /// \n /// \n /// \n /// This property provides identification details about the connected server, including its name and version.\n /// It is populated during the initialization handshake and is available after a successful connection.\n /// \n /// \n /// This information can be useful for logging, debugging, compatibility checks, and displaying server\n /// information to users.\n /// \n /// \n /// The client is not connected.\n Implementation ServerInfo { get; }\n\n /// \n /// Gets any instructions describing how to use the connected server and its features.\n /// \n /// \n /// \n /// This property contains instructions provided by the server during initialization that explain\n /// how to effectively use its capabilities. These instructions can include details about available\n /// tools, expected input formats, limitations, or any other helpful information.\n /// \n /// \n /// This can be used by clients to improve an LLM's understanding of available tools, prompts, and resources. \n /// It can be thought of like a \"hint\" to the model and may be added to a system prompt.\n /// \n /// \n string? ServerInstructions { get; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptResult.cs", "using Microsoft.Extensions.AI;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// \n/// For integration with AI client libraries, can be converted to\n/// a collection of objects using the extension method.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class GetPromptResult : Result\n{\n /// \n /// Gets or sets an optional description for the prompt.\n /// \n /// \n /// \n /// This description provides contextual information about the prompt's purpose and use cases.\n /// It helps developers understand what the prompt is designed for and how it should be used.\n /// \n /// \n /// When returned from a server in response to a request,\n /// this description can be used by client applications to provide context about the prompt or to\n /// display in user interfaces.\n /// \n /// \n [JsonPropertyName(\"description\")]\n public string? Description { get; set; }\n\n /// \n /// Gets or sets the prompt that the server offers.\n /// \n [JsonPropertyName(\"messages\")]\n public IList Messages { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcMessageWithId.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a JSON-RPC message used in the Model Context Protocol (MCP) and that includes an ID.\n/// \n/// \n/// In the JSON-RPC protocol, messages with an ID require a response from the receiver.\n/// This includes request messages (which expect a matching response) and response messages\n/// (which include the ID of the original request they're responding to).\n/// The ID is used to correlate requests with their responses, allowing asynchronous\n/// communication where multiple requests can be sent without waiting for responses.\n/// \npublic abstract class JsonRpcMessageWithId : JsonRpcMessage\n{\n /// Prevent external derivations.\n private protected JsonRpcMessageWithId()\n {\n }\n\n /// \n /// Gets the message identifier.\n /// \n /// \n /// Each ID is expected to be unique within the context of a given session.\n /// \n [JsonPropertyName(\"id\")]\n public RequestId Id { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcErrorDetail.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents detailed error information for JSON-RPC error responses.\n/// \n/// \n/// This class is used as part of the message to provide structured \n/// error information when a request cannot be fulfilled. The JSON-RPC 2.0 specification defines\n/// a standard format for error responses that includes a numeric code, a human-readable message,\n/// and optional additional data.\n/// \npublic sealed class JsonRpcErrorDetail\n{\n /// \n /// Gets an integer error code according to the JSON-RPC specification.\n /// \n [JsonPropertyName(\"code\")]\n public required int Code { get; init; }\n\n /// \n /// Gets a short description of the error.\n /// \n /// \n /// This is expected to be a brief, human-readable explanation of what went wrong.\n /// For standard error codes, it's recommended to use the descriptions defined \n /// in the JSON-RPC 2.0 specification.\n /// \n [JsonPropertyName(\"message\")]\n public required string Message { get; init; }\n\n /// \n /// Gets optional additional error data.\n /// \n /// \n /// This property can contain any additional information that might help the client\n /// understand or resolve the error. Common examples include validation errors,\n /// stack traces (in development environments), or contextual information about\n /// the error condition.\n /// \n [JsonPropertyName(\"data\")]\n public object? Data { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration request for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationRequest\n{\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public required string[] RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the human-readable name of the client.\n /// \n [JsonPropertyName(\"client_name\")]\n public string? ClientName { get; init; }\n\n /// \n /// Gets or sets the URL of the client's home page.\n /// \n [JsonPropertyName(\"client_uri\")]\n public string? ClientUri { get; init; }\n\n /// \n /// Gets or sets the scope values that the client will use.\n /// \n [JsonPropertyName(\"scope\")]\n public string? Scope { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelPreferences.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's preferences for model selection, requested of the client during sampling.\n/// \n/// \n/// \n/// Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n/// rarely straightforward. Different models excel in different areas—some are\n/// faster but less capable, others are more capable but more expensive, and so\n/// on. This class allows servers to express their priorities across multiple\n/// dimensions to help clients make an appropriate selection for their use case.\n/// \n/// \n/// These preferences are always advisory. The client may ignore them. It is also\n/// up to the client to decide how to interpret these preferences and how to\n/// balance them against other considerations.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelPreferences\n{\n /// \n /// Gets or sets how much to prioritize cost when selecting a model.\n /// \n /// \n /// A value of 0 means cost is not important, while a value of 1 means cost is the most important factor.\n /// \n [JsonPropertyName(\"costPriority\")]\n public float? CostPriority { get; init; }\n\n /// \n /// Gets or sets optional hints to use for model selection.\n /// \n [JsonPropertyName(\"hints\")]\n public IReadOnlyList? Hints { get; init; }\n\n /// \n /// Gets or sets how much to prioritize sampling speed (latency) when selecting a model.\n /// \n /// \n /// A value of 0 means speed is not important, while a value of 1 means speed is the most important factor.\n /// \n [JsonPropertyName(\"speedPriority\")]\n public float? SpeedPriority { get; init; }\n\n /// \n /// Gets or sets how much to prioritize intelligence and capabilities when selecting a model.\n /// \n /// \n /// A value of 0 means intelligence is not important, while a value of 1 means intelligence is the most important factor.\n /// \n [JsonPropertyName(\"intelligencePriority\")]\n public float? IntelligencePriority { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingCapability.cs", "using ModelContextProtocol.Server;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the logging capability configuration for a Model Context Protocol server.\n/// \n/// \n/// This capability allows clients to set the logging level and receive log messages from the server.\n/// See the schema for details.\n/// \npublic sealed class LoggingCapability\n{\n // Currently empty in the spec, but may be extended in the future\n\n /// \n /// Gets or sets the handler for set logging level requests from clients.\n /// \n [JsonIgnore]\n public Func, CancellationToken, ValueTask>? SetLoggingLevelHandler { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the server's response to a request, \n/// containing suggested values for a given argument.\n/// \n/// \n/// \n/// is returned by the server in response to a \n/// request from the client. It provides suggested completions or valid values for a specific argument in a tool or resource reference.\n/// \n/// \n/// The result contains a object with suggested values, pagination information,\n/// and the total number of available completions. This is similar to auto-completion functionality in code editors.\n/// \n/// \n/// Clients typically use this to implement auto-suggestion features when users are inputting parameters\n/// for tool calls or resource references.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteResult : Result\n{\n /// \n /// Gets or sets the completion object containing the suggested values and pagination information.\n /// \n /// \n /// If no completions are available for the given input, the \n /// collection will be empty.\n /// \n [JsonPropertyName(\"completion\")]\n public Completion Completion { get; set; } = new Completion();\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/GetPromptRequestParams.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a prompt provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting prompt.\n/// See the schema for details.\n/// \npublic sealed class GetPromptRequestParams : RequestParams\n{\n /// \n /// Gets or sets the name of the prompt.\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; init; }\n\n /// \n /// Gets or sets arguments to use for templating the prompt when retrieving it from the server.\n /// \n /// \n /// Typically, these arguments are used to replace placeholders in prompt templates. The keys in this dictionary\n /// should match the names defined in the prompt's list. However, the server may\n /// choose to use these arguments in any way it deems appropriate to generate the prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IReadOnlyDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CreateMessageResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a from the server.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class CreateMessageResult : Result\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the name of the model that generated the message.\n /// \n /// \n /// \n /// This should contain the specific model identifier such as \"claude-3-5-sonnet-20241022\" or \"o3-mini\".\n /// \n /// \n /// This property allows the server to know which model was used to generate the response,\n /// enabling appropriate handling based on the model's capabilities and characteristics.\n /// \n /// \n [JsonPropertyName(\"model\")]\n public required string Model { get; init; }\n\n /// \n /// Gets or sets the reason why message generation (sampling) stopped, if known.\n /// \n /// \n /// Common values include:\n /// \n /// endTurnThe model naturally completed its response.\n /// maxTokensThe response was truncated due to reaching token limits.\n /// stopSequenceA specific stop sequence was encountered during generation.\n /// \n /// \n [JsonPropertyName(\"stopReason\")]\n public string? StopReason { get; init; }\n\n /// \n /// Gets or sets the role of the user who generated the message.\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcResponse.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// A successful response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Response messages are sent in reply to a request message and contain the result of the method execution.\n/// Each response includes the same ID as the original request, allowing the sender to match responses\n/// with their corresponding requests.\n/// \n/// \n/// This class represents a successful response with a result. For error responses, see .\n/// \n/// \npublic sealed class JsonRpcResponse : JsonRpcMessageWithId\n{\n /// \n /// Gets the result of the method invocation.\n /// \n /// \n /// This property contains the result data returned by the server in response to the JSON-RPC method request.\n /// \n [JsonPropertyName(\"result\")]\n public required JsonNode? Result { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/UnsubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Sent from the client to cancel resource update notifications from the server for a specific resource.\n/// \n/// \n/// \n/// After a client has subscribed to resource updates using , \n/// this message can be sent to stop receiving notifications for a specific resource. \n/// This is useful for conserving resources and network bandwidth when \n/// the client no longer needs to track changes to a particular resource.\n/// \n/// \n/// The unsubscribe operation is idempotent, meaning it can be called multiple times \n/// for the same resource without causing errors, even if there is no active subscription.\n/// \n/// \npublic sealed class UnsubscribeRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to unsubscribe from. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/samples/TestServerWithHosting/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Serilog;\nusing TestServerWithHosting.Tools;\n\nLog.Logger = new LoggerConfiguration()\n .MinimumLevel.Verbose() // Capture all log levels\n .WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"logs\", \"TestServer_.log\"),\n rollingInterval: RollingInterval.Day,\n outputTemplate: \"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}\")\n .WriteTo.Debug()\n .WriteTo.Console(standardErrorFromLevel: Serilog.Events.LogEventLevel.Verbose)\n .CreateLogger();\n\ntry\n{\n Log.Information(\"Starting server...\");\n\n var builder = Host.CreateApplicationBuilder(args);\n builder.Services.AddSerilog();\n builder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools()\n .WithTools();\n\n var app = builder.Build();\n\n await app.RunAsync();\n return 0;\n}\ncatch (Exception ex)\n{\n Log.Fatal(ex, \"Host terminated unexpectedly\");\n return 1;\n}\nfinally\n{\n Log.CloseAndFlush();\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/DynamicClientRegistrationResponse.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a client registration response for OAuth 2.0 Dynamic Client Registration (RFC 7591).\n/// \ninternal sealed class DynamicClientRegistrationResponse\n{\n /// \n /// Gets or sets the client identifier.\n /// \n [JsonPropertyName(\"client_id\")]\n public required string ClientId { get; init; }\n\n /// \n /// Gets or sets the client secret.\n /// \n [JsonPropertyName(\"client_secret\")]\n public string? ClientSecret { get; init; }\n\n /// \n /// Gets or sets the redirect URIs for the client.\n /// \n [JsonPropertyName(\"redirect_uris\")]\n public string[]? RedirectUris { get; init; }\n\n /// \n /// Gets or sets the token endpoint authentication method.\n /// \n [JsonPropertyName(\"token_endpoint_auth_method\")]\n public string? TokenEndpointAuthMethod { get; init; }\n\n /// \n /// Gets or sets the grant types that the client will use.\n /// \n [JsonPropertyName(\"grant_types\")]\n public string[]? GrantTypes { get; init; }\n\n /// \n /// Gets or sets the response types that the client will use.\n /// \n [JsonPropertyName(\"response_types\")]\n public string[]? ResponseTypes { get; init; }\n\n /// \n /// Gets or sets the client ID issued timestamp.\n /// \n [JsonPropertyName(\"client_id_issued_at\")]\n public long? ClientIdIssuedAt { get; init; }\n\n /// \n /// Gets or sets the client secret expiration time.\n /// \n [JsonPropertyName(\"client_secret_expires_at\")]\n public long? ClientSecretExpiresAt { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SubscribeRequestParams.cs", "using System.Diagnostics.CodeAnalysis;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to request real-time notifications from the server whenever a particular resource changes.\n/// \n/// \n/// \n/// The subscription mechanism allows clients to be notified about changes to specific resources\n/// identified by their URI. When a subscribed resource changes, the server sends a notification\n/// to the client with the updated resource information.\n/// \n/// \n/// Subscriptions remain active until explicitly canceled using \n/// or until the connection is terminated.\n/// \n/// \n/// The server may refuse or limit subscriptions based on its capabilities or resource constraints.\n/// \n/// \npublic sealed class SubscribeRequestParams : RequestParams\n{\n /// \n /// Gets or sets the URI of the resource to subscribe to.\n /// \n /// \n /// The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n [StringSyntax(StringSyntaxAttribute.Uri)]\n public string? Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a client's response to a request from the server,\n/// containing available roots.\n/// \n/// \n/// \n/// This result is returned when a server sends a request to discover \n/// available roots on the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListRootsResult : Result\n{\n /// \n /// Gets or sets the list of root URIs provided by the client.\n /// \n /// \n /// This collection contains all available root URIs and their associated metadata.\n /// Each root serves as an entry point for resource navigation in the Model Context Protocol.\n /// \n [JsonPropertyName(\"roots\")]\n public required IReadOnlyList Roots { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available prompts.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available prompts on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many prompts.\n/// The server can provide the property to indicate there are more\n/// prompts available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListPromptsResult : PaginatedResult\n{\n /// \n /// A list of prompts or prompt templates that the server offers.\n /// \n [JsonPropertyName(\"prompts\")]\n public IList Prompts { get; set; } = [];\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from \n/// a client to ask a server for auto-completion suggestions.\n/// \n/// \n/// \n/// is used in the Model Context Protocol completion workflow\n/// to provide intelligent suggestions for partial inputs related to resources, prompts, or other referenceable entities.\n/// The completion mechanism in MCP allows clients to request suggestions based on partial inputs.\n/// The server will respond with a containing matching values.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class CompleteRequestParams : RequestParams\n{\n /// \n /// Gets or sets the reference's information.\n /// \n [JsonPropertyName(\"ref\")]\n public required Reference Ref { get; init; }\n\n /// \n /// Gets or sets the argument information for the completion request, specifying what is being completed\n /// and the current partial input.\n /// \n [JsonPropertyName(\"argument\")]\n public required Argument Argument { get; init; }\n\n /// \n /// Gets or sets additional, optional context for completions.\n /// \n [JsonPropertyName(\"context\")]\n public CompleteContext? Context { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available resources.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available resources on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many resources.\n/// The server can provide the property to indicate there are more\n/// resources available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListResourcesResult : PaginatedResult\n{\n /// \n /// A list of resources that the server offers.\n /// \n [JsonPropertyName(\"resources\")]\n public IList Resources { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PaginatedRequest.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for paginated requests.\n/// \n/// \n/// See the schema for details\n/// \npublic abstract class PaginatedRequestParams : RequestParams\n{\n /// Prevent external derivations.\n private protected PaginatedRequestParams()\n {\n }\n\n /// \n /// Gets or sets an opaque token representing the current pagination position.\n /// \n /// \n /// If provided, the server should return results starting after this cursor.\n /// This value should be obtained from the \n /// property of a previous request's response.\n /// \n [JsonPropertyName(\"cursor\")]\n public string? Cursor { get; init; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Implementation.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides the name and version of an MCP implementation.\n/// \n/// \n/// \n/// The class is used to identify MCP clients and servers during the initialization handshake.\n/// It provides version and name information that can be used for compatibility checks, logging, and debugging.\n/// \n/// \n/// Both clients and servers provide this information during connection establishment.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class Implementation : IBaseMetadata\n{\n /// \n [JsonPropertyName(\"name\")]\n public required string Name { get; set; }\n\n /// \n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n\n /// \n /// Gets or sets the version of the implementation.\n /// \n /// \n /// The version is used during client-server handshake to identify implementation versions,\n /// which can be important for troubleshooting compatibility issues or when reporting bugs.\n /// \n [JsonPropertyName(\"version\")]\n public required string Version { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SamplingMessage.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a message issued to or received from an LLM API within the Model Context Protocol.\n/// \n/// \n/// \n/// A encapsulates content sent to or received from AI models in the Model Context Protocol.\n/// Each message has a specific role ( or ) and contains content which can be text or images.\n/// \n/// \n/// objects are typically used in collections within \n/// to represent prompts or queries for LLM sampling. They form the core data structure for text generation requests\n/// within the Model Context Protocol.\n/// \n/// \n/// While similar to , the is focused on direct LLM sampling\n/// operations rather than the enhanced resource embedding capabilities provided by .\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class SamplingMessage\n{\n /// \n /// Gets or sets the content of the message.\n /// \n [JsonPropertyName(\"content\")]\n public required ContentBlock Content { get; init; }\n\n /// \n /// Gets or sets the role of the message sender, indicating whether it's from a \"user\" or an \"assistant\".\n /// \n [JsonPropertyName(\"role\")]\n public required Role Role { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Collections/Generic/CollectionExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Collections.Generic;\n\ninternal static class CollectionExtensions\n{\n public static TValue? GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key)\n {\n return dictionary.GetValueOrDefault(key, default!);\n }\n\n public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key, TValue defaultValue)\n {\n Throw.IfNull(dictionary);\n\n return dictionary.TryGetValue(key, out TValue? value) ? value : defaultValue;\n }\n\n public static Dictionary ToDictionary(this IEnumerable> source) =>\n source.ToDictionary(kv => kv.Key, kv => kv.Value);\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ResourceListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of resources it can read from has changed. \n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ResourceListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/NotificationParams.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for notification parameters.\n/// \npublic abstract class NotificationParams\n{\n /// Prevent external derivations.\n private protected NotificationParams()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Argument.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an argument used in completion requests to provide context for auto-completion functionality.\n/// \n/// \n/// This class is used when requesting completion suggestions for a particular field or parameter.\n/// See the schema for details.\n/// \npublic sealed class Argument\n{\n /// \n /// Gets or sets the name of the argument being completed.\n /// \n [JsonPropertyName(\"name\")]\n public string Name { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the current partial text value for which completion suggestions are requested.\n /// \n /// \n /// This represents the text that has been entered so far and for which completion\n /// options should be generated.\n /// \n [JsonPropertyName(\"value\")]\n public string Value { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PromptListChangedNotification .cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of prompts it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class PromptListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/BlobResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the binary contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when binary data needs to be exchanged through\n/// the Model Context Protocol. The binary data is represented as a base64-encoded string\n/// in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for text-based resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class BlobResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the base64-encoded string representing the binary data of the item.\n /// \n [JsonPropertyName(\"blob\")]\n public string Blob { get; set; } = string.Empty;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/TextResourceContents.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents text-based contents of a resource in the Model Context Protocol.\n/// \n/// \n/// \n/// is used when textual data needs to be exchanged through\n/// the Model Context Protocol. The text is stored directly in the property.\n/// \n/// \n/// This class inherits from , which also has a sibling implementation\n/// for binary resources. When working with resources, the\n/// appropriate type is chosen based on the nature of the content.\n/// \n/// \n/// See the schema for more details.\n/// \n/// \npublic sealed class TextResourceContents : ResourceContents\n{\n /// \n /// Gets or sets the text of the item.\n /// \n [JsonPropertyName(\"text\")]\n public string Text { get; set; } = string.Empty;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client, containing available tools.\n/// \n/// \n/// \n/// This result is returned when a client sends a request to discover available tools on the server.\n/// \n/// \n/// It inherits from , allowing for paginated responses when there are many tools.\n/// The server can provide the property to indicate there are more\n/// tools available beyond what was returned in the current response.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ListToolsResult : PaginatedResult\n{\n /// \n /// The server's response to a tools/list request from the client.\n /// \n [JsonPropertyName(\"tools\")]\n public IList Tools { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ElicitResult.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the client's response to an elicitation request.\n/// \npublic sealed class ElicitResult : Result\n{\n /// \n /// Gets or sets the user action in response to the elicitation.\n /// \n /// \n /// \n /// \n /// \"accept\"\n /// User submitted the form/confirmed the action\n /// \n /// \n /// \"decline\"\n /// User explicitly declined the action\n /// \n /// \n /// \"cancel\"\n /// User dismissed without making an explicit choice\n /// \n /// \n /// \n [JsonPropertyName(\"action\")]\n public string Action { get; set; } = \"cancel\";\n\n /// \n /// Gets or sets the submitted form data.\n /// \n /// \n /// \n /// This is typically omitted if the action is \"cancel\" or \"decline\".\n /// \n /// \n /// Values in the dictionary should be of types , ,\n /// , or .\n /// \n /// \n [JsonPropertyName(\"content\")]\n public IDictionary? Content { get; set; }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ModelHint.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides hints to use for model selection.\n/// \n/// \n/// \n/// When multiple hints are specified in , they are evaluated in order,\n/// with the first match taking precedence. Clients should prioritize these hints over numeric priorities.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ModelHint\n{\n /// \n /// Gets or sets a hint for a model name.\n /// \n /// \n /// The specified string can be a partial or full model name. Clients may also \n /// map hints to equivalent models from different providers. Clients make the final model\n /// selection based on these preferences and their available models.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Net/Http/HttpClientExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Net.Http;\n\ninternal static class HttpClientExtensions\n{\n public static async Task ReadAsStreamAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStreamAsync();\n }\n\n public static async Task ReadAsStringAsync(this HttpContent content, CancellationToken cancellationToken)\n {\n Throw.IfNull(content);\n\n cancellationToken.ThrowIfCancellationRequested();\n return await content.ReadAsStringAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the server to the client, informing it that the list of tools it offers has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class ToolListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RootsListChangedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// notification from the client to the server, informing it that the list of roots has changed.\n/// \n/// \n/// \n/// This may be issued by servers without any previous subscription from the client.\n/// \n/// \n/// See the schema for details.\n/// \n/// \npublic sealed class RootsListChangedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/JsonRpcError.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an error response message in the JSON-RPC protocol.\n/// \n/// \n/// \n/// Error responses are sent when a request cannot be fulfilled or encounters an error during processing.\n/// Like successful responses, error messages include the same ID as the original request, allowing the\n/// sender to match errors with their corresponding requests.\n/// \n/// \n/// Each error response contains a structured error detail object with a numeric code, descriptive message,\n/// and optional additional data to provide more context about the error.\n/// \n/// \npublic sealed class JsonRpcError : JsonRpcMessageWithId\n{\n /// \n /// Gets detailed error information for the failed request, containing an error code, \n /// message, and optional additional data\n /// \n [JsonPropertyName(\"error\")]\n public required JsonRpcErrorDetail Error { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/AuthorizationServerMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents the metadata about an OAuth authorization server.\n/// \ninternal sealed class AuthorizationServerMetadata\n{\n /// \n /// The authorization endpoint URI.\n /// \n [JsonPropertyName(\"authorization_endpoint\")]\n public Uri AuthorizationEndpoint { get; set; } = null!;\n\n /// \n /// The token endpoint URI.\n /// \n [JsonPropertyName(\"token_endpoint\")]\n public Uri TokenEndpoint { get; set; } = null!;\n\n /// \n /// The registration endpoint URI.\n /// \n [JsonPropertyName(\"registration_endpoint\")]\n public Uri? RegistrationEndpoint { get; set; }\n\n /// \n /// The revocation endpoint URI.\n /// \n [JsonPropertyName(\"revocation_endpoint\")]\n public Uri? RevocationEndpoint { get; set; }\n\n /// \n /// The response types supported by the authorization server.\n /// \n [JsonPropertyName(\"response_types_supported\")]\n public List? ResponseTypesSupported { get; set; }\n\n /// \n /// The grant types supported by the authorization server.\n /// \n [JsonPropertyName(\"grant_types_supported\")]\n public List? GrantTypesSupported { get; set; }\n\n /// \n /// The token endpoint authentication methods supported by the authorization server.\n /// \n [JsonPropertyName(\"token_endpoint_auth_methods_supported\")]\n public List? TokenEndpointAuthMethodsSupported { get; set; }\n\n /// \n /// The code challenge methods supported by the authorization server.\n /// \n [JsonPropertyName(\"code_challenge_methods_supported\")]\n public List? CodeChallengeMethodsSupported { get; set; }\n\n /// \n /// The issuer URI of the authorization server.\n /// \n [JsonPropertyName(\"issuer\")]\n public Uri? Issuer { get; set; }\n\n /// \n /// The scopes supported by the authorization server.\n /// \n [JsonPropertyName(\"scopes_supported\")]\n public List? ScopesSupported { get; set; }\n}\n"], ["/csharp-sdk/samples/ProtectedMCPServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/samples/QuickstartWeatherServer/Tools/HttpClientExt.cs", "using System.Text.Json;\n\nnamespace ModelContextProtocol;\n\ninternal static class HttpClientExt\n{\n public static async Task ReadJsonDocumentAsync(this HttpClient client, string requestUri)\n {\n using var response = await client.GetAsync(requestUri);\n response.EnsureSuccessStatusCode();\n return await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationEvents.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Represents the authentication events for Model Context Protocol.\n/// \npublic class McpAuthenticationEvents\n{\n /// \n /// Gets or sets the function that is invoked when resource metadata is requested.\n /// \n /// \n /// This function is called when a resource metadata request is made to the protected resource metadata endpoint.\n /// The implementer should set the property\n /// to provide the appropriate metadata for the current request.\n /// \n public Func OnResourceMetadataRequest { get; set; } = context => Task.CompletedTask;\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a server's response to a request from the client.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class ReadResourceResult : Result\n{\n /// \n /// Gets or sets a list of objects that this resource contains.\n /// \n /// \n /// This property contains the actual content of the requested resource, which can be\n /// either text-based () or binary ().\n /// The type of content included depends on the resource being accessed.\n /// \n [JsonPropertyName(\"contents\")]\n public IList Contents { get; set; } = [];\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/LoggingLevel.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Indicates the severity of a log message.\n/// \n/// \n/// These map to syslog message severities, as specified in RFC-5424.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum LoggingLevel\n{\n /// Detailed debug information, typically only valuable to developers.\n [JsonStringEnumMemberName(\"debug\")]\n Debug,\n\n /// Normal operational messages that require no action.\n [JsonStringEnumMemberName(\"info\")]\n Info,\n\n /// Normal but significant events that might deserve attention.\n [JsonStringEnumMemberName(\"notice\")]\n Notice,\n\n /// Warning conditions that don't represent an error but indicate potential issues.\n [JsonStringEnumMemberName(\"warning\")]\n Warning,\n\n /// Error conditions that should be addressed but don't require immediate action.\n [JsonStringEnumMemberName(\"error\")]\n Error,\n\n /// Critical conditions that require immediate attention.\n [JsonStringEnumMemberName(\"critical\")]\n Critical,\n\n /// Action must be taken immediately to address the condition.\n [JsonStringEnumMemberName(\"alert\")]\n Alert,\n\n /// System is unusable and requires immediate attention.\n [JsonStringEnumMemberName(\"emergency\")]\n Emergency\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/PingResult.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the result of a request in the Model Context Protocol.\n/// \n/// \n/// \n/// The is returned in response to a request, \n/// which is used to verify that the connection between client and server is still alive and responsive. \n/// Since this is a simple connectivity check, the result is an empty object containing no data.\n/// \n/// \n/// Ping requests can be initiated by either the client or the server to check if the other party\n/// is still responsive.\n/// \n/// \npublic sealed class PingResult : Result;"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Root.cs", "using System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents a root URI and its metadata in the Model Context Protocol.\n/// \n/// \n/// Root URIs serve as entry points for resource navigation, typically representing\n/// top-level directories or container resources that can be accessed and traversed.\n/// Roots provide a hierarchical structure for organizing and accessing resources within the protocol.\n/// Each root has a URI that uniquely identifies it and optional metadata like a human-readable name.\n/// \npublic sealed class Root\n{\n /// \n /// Gets or sets the URI of the root.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n\n /// \n /// Gets or sets a human-readable name for the root.\n /// \n [JsonPropertyName(\"name\")]\n public string? Name { get; init; }\n\n /// \n /// Gets or sets additional metadata for the root.\n /// \n /// \n /// This is reserved by the protocol for future use.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonElement? Meta { get; init; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/CancellationTokenSourceExtensions.cs", "#if !NET\nusing ModelContextProtocol;\n\nnamespace System.Threading.Tasks;\n\ninternal static class CancellationTokenSourceExtensions\n{\n public static Task CancelAsync(this CancellationTokenSource cancellationTokenSource)\n {\n Throw.IfNull(cancellationTokenSource);\n\n cancellationTokenSource.Cancel();\n return Task.CompletedTask;\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/SetLevelRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client\n/// to enable or adjust logging.\n/// \n/// \n/// This request allows clients to configure the level of logging information they want to receive from the server.\n/// The server will send notifications for log events at the specified level and all higher (more severe) levels.\n/// \npublic sealed class SetLevelRequestParams : RequestParams\n{\n /// \n /// Gets or sets the level of logging that the client wants to receive from the server. \n /// \n [JsonPropertyName(\"level\")]\n public required LoggingLevel Level { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/DynamicallyAccessedMemberTypes.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\n#if !NET\nnamespace System.Diagnostics.CodeAnalysis;\n\n/// \n/// Specifies the types of members that are dynamically accessed.\n///\n/// This enumeration has a attribute that allows a\n/// bitwise combination of its member values.\n/// \n[Flags]\ninternal enum DynamicallyAccessedMemberTypes\n{\n /// \n /// Specifies no members.\n /// \n None = 0,\n\n /// \n /// Specifies the default, parameterless public constructor.\n /// \n PublicParameterlessConstructor = 0x0001,\n\n /// \n /// Specifies all public constructors.\n /// \n PublicConstructors = 0x0002 | PublicParameterlessConstructor,\n\n /// \n /// Specifies all non-public constructors.\n /// \n NonPublicConstructors = 0x0004,\n\n /// \n /// Specifies all public methods.\n /// \n PublicMethods = 0x0008,\n\n /// \n /// Specifies all non-public methods.\n /// \n NonPublicMethods = 0x0010,\n\n /// \n /// Specifies all public fields.\n /// \n PublicFields = 0x0020,\n\n /// \n /// Specifies all non-public fields.\n /// \n NonPublicFields = 0x0040,\n\n /// \n /// Specifies all public nested types.\n /// \n PublicNestedTypes = 0x0080,\n\n /// \n /// Specifies all non-public nested types.\n /// \n NonPublicNestedTypes = 0x0100,\n\n /// \n /// Specifies all public properties.\n /// \n PublicProperties = 0x0200,\n\n /// \n /// Specifies all non-public properties.\n /// \n NonPublicProperties = 0x0400,\n\n /// \n /// Specifies all public events.\n /// \n PublicEvents = 0x0800,\n\n /// \n /// Specifies all non-public events.\n /// \n NonPublicEvents = 0x1000,\n\n /// \n /// Specifies all interfaces implemented by the type.\n /// \n Interfaces = 0x2000,\n\n /// \n /// Specifies all non-public constructors, including those inherited from base classes.\n /// \n NonPublicConstructorsWithInherited = NonPublicConstructors | 0x4000,\n\n /// \n /// Specifies all non-public methods, including those inherited from base classes.\n /// \n NonPublicMethodsWithInherited = NonPublicMethods | 0x8000,\n\n /// \n /// Specifies all non-public fields, including those inherited from base classes.\n /// \n NonPublicFieldsWithInherited = NonPublicFields | 0x10000,\n\n /// \n /// Specifies all non-public nested types, including those inherited from base classes.\n /// \n NonPublicNestedTypesWithInherited = NonPublicNestedTypes | 0x20000,\n\n /// \n /// Specifies all non-public properties, including those inherited from base classes.\n /// \n NonPublicPropertiesWithInherited = NonPublicProperties | 0x40000,\n\n /// \n /// Specifies all non-public events, including those inherited from base classes.\n /// \n NonPublicEventsWithInherited = NonPublicEvents | 0x80000,\n\n /// \n /// Specifies all public constructors, including those inherited from base classes.\n /// \n PublicConstructorsWithInherited = PublicConstructors | 0x100000,\n\n /// \n /// Specifies all public nested types, including those inherited from base classes.\n /// \n PublicNestedTypesWithInherited = PublicNestedTypes | 0x200000,\n\n /// \n /// Specifies all constructors, including those inherited from base classes.\n /// \n AllConstructors = PublicConstructorsWithInherited | NonPublicConstructorsWithInherited,\n\n /// \n /// Specifies all methods, including those inherited from base classes.\n /// \n AllMethods = PublicMethods | NonPublicMethodsWithInherited,\n\n /// \n /// Specifies all fields, including those inherited from base classes.\n /// \n AllFields = PublicFields | NonPublicFieldsWithInherited,\n\n /// \n /// Specifies all nested types, including those inherited from base classes.\n /// \n AllNestedTypes = PublicNestedTypesWithInherited | NonPublicNestedTypesWithInherited,\n\n /// \n /// Specifies all properties, including those inherited from base classes.\n /// \n AllProperties = PublicProperties | NonPublicPropertiesWithInherited,\n\n /// \n /// Specifies all events, including those inherited from base classes.\n /// \n AllEvents = PublicEvents | NonPublicEventsWithInherited,\n\n /// \n /// Specifies all members.\n /// \n All = ~None\n}\n#endif"], ["/csharp-sdk/samples/EverythingServer/Tools/PrintEnvTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\nusing System.Text.Json;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class PrintEnvTool\n{\n private static readonly JsonSerializerOptions options = new()\n {\n WriteIndented = true\n };\n\n [McpServerTool(Name = \"printEnv\"), Description(\"Prints all environment variables, helpful for debugging MCP server configuration\")]\n public static string PrintEnv() =>\n JsonSerializer.Serialize(Environment.GetEnvironmentVariables(), options);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ReadResourceRequestParams.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to get a resource provided by a server.\n/// \n/// \n/// The server will respond with a containing the resulting resource data.\n/// See the schema for details.\n/// \npublic sealed class ReadResourceRequestParams : RequestParams\n{\n /// \n /// The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n /// \n [JsonPropertyName(\"uri\")]\n public required string Uri { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ContextInclusion.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Specifies the context inclusion options for a request in the Model Context Protocol (MCP).\n/// \n/// \n/// See the schema for details.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum ContextInclusion\n{\n /// \n /// Indicates that no context should be included.\n /// \n [JsonStringEnumMemberName(\"none\")]\n None,\n\n /// \n /// Indicates that context from the server that sent the request should be included.\n /// \n [JsonStringEnumMemberName(\"thisServer\")]\n ThisServer,\n\n /// \n /// Indicates that context from all servers that the client is connected to should be included.\n /// \n [JsonStringEnumMemberName(\"allServers\")]\n AllServers\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/IO/TextWriterExtensions.cs", "#if !NET\nnamespace System.IO;\n\ninternal static class TextWriterExtensions\n{\n public static async Task FlushAsync(this TextWriter writer, CancellationToken cancellationToken)\n {\n cancellationToken.ThrowIfCancellationRequested();\n await writer.FlushAsync();\n }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Result.cs", "using System.Text.Json.Nodes;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for result payloads.\n/// \npublic abstract class Result\n{\n /// Prevent external derivations.\n private protected Result()\n {\n }\n\n /// \n /// Gets or sets metadata reserved by MCP for protocol-level metadata.\n /// \n /// \n /// Implementations must not make assumptions about its contents.\n /// \n [JsonPropertyName(\"_meta\")]\n public JsonObject? Meta { get; init; }\n}"], ["/csharp-sdk/src/Common/Polyfills/System/Threading/ForceYielding.cs", "#if !NET\nusing System.Runtime.CompilerServices;\n\nnamespace System.Threading;\n\n/// \n/// await default(ForceYielding) to provide the same behavior as\n/// await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding).\n/// \ninternal readonly struct ForceYielding : INotifyCompletion, ICriticalNotifyCompletion\n{\n public ForceYielding GetAwaiter() => this;\n\n public bool IsCompleted => false;\n public void OnCompleted(Action continuation) => ThreadPool.QueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void UnsafeOnCompleted(Action continuation) => ThreadPool.UnsafeQueueUserWorkItem(a => ((Action)a!)(), continuation);\n public void GetResult() { }\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/RequestParamsMetadata.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides metadata related to the request that provides additional protocol-level information.\n/// \n/// \n/// This class contains properties that are used by the Model Context Protocol\n/// for features like progress tracking and other protocol-specific capabilities.\n/// \npublic sealed class RequestParamsMetadata\n{\n /// \n /// Gets or sets an opaque token that will be attached to any subsequent progress notifications.\n /// \n /// \n /// The receiver is not obligated to provide these notifications.\n /// \n [JsonPropertyName(\"progressToken\")]\n public ProgressToken? ProgressToken { get; set; } = default!;\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/TokenContainer.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// Represents a token response from the OAuth server.\n/// \ninternal sealed class TokenContainer\n{\n /// \n /// Gets or sets the access token.\n /// \n [JsonPropertyName(\"access_token\")]\n public string AccessToken { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the refresh token.\n /// \n [JsonPropertyName(\"refresh_token\")]\n public string? RefreshToken { get; set; }\n\n /// \n /// Gets or sets the number of seconds until the access token expires.\n /// \n [JsonPropertyName(\"expires_in\")]\n public int ExpiresIn { get; set; }\n\n /// \n /// Gets or sets the extended expiration time in seconds.\n /// \n [JsonPropertyName(\"ext_expires_in\")]\n public int ExtExpiresIn { get; set; }\n\n /// \n /// Gets or sets the token type (typically \"Bearer\").\n /// \n [JsonPropertyName(\"token_type\")]\n public string TokenType { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the scope of the access token.\n /// \n [JsonPropertyName(\"scope\")]\n public string Scope { get; set; } = string.Empty;\n\n /// \n /// Gets or sets the timestamp when the token was obtained.\n /// \n [JsonIgnore]\n public DateTimeOffset ObtainedAt { get; set; }\n\n /// \n /// Gets the timestamp when the token expires, calculated from ObtainedAt and ExpiresIn.\n /// \n [JsonIgnore]\n public DateTimeOffset ExpiresAt => ObtainedAt.AddSeconds(ExpiresIn);\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/CallerArgumentExpressionAttribute.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\n#if !NET\nnamespace System.Runtime.CompilerServices;\n\n[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]\ninternal sealed class CallerArgumentExpressionAttribute : Attribute\n{\n public CallerArgumentExpressionAttribute(string parameterName)\n {\n ParameterName = parameterName;\n }\n\n public string ParameterName { get; }\n}\n#endif"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/IsExternalInit.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// \n /// Reserved to be used by the compiler for tracking metadata.\n /// This class should not be used by developers in source code.\n /// \n [EditorBrowsable(EditorBrowsableState.Never)]\n internal static class IsExternalInit;\n}\n#else\n// The compiler emits a reference to the internal copy of this type in the non-.NET builds,\n// so we must include a forward to be compatible.\n[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExternalInit))]\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/HttpTransportMode.cs", "namespace ModelContextProtocol.Client;\n\n/// \n/// Specifies the transport mode for HTTP client connections.\n/// \npublic enum HttpTransportMode\n{\n /// \n /// Automatically detect the appropriate transport by trying Streamable HTTP first, then falling back to SSE if that fails.\n /// This is the recommended mode for maximum compatibility.\n /// \n AutoDetect,\n\n /// \n /// Use only the Streamable HTTP transport.\n /// \n StreamableHttp,\n\n /// \n /// Use only the HTTP with SSE transport.\n /// \n Sse\n}"], ["/csharp-sdk/samples/TestServerWithHosting/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/samples/AspNetCoreSseServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Tools;\n\n[McpServerToolType]\npublic sealed class EchoTool\n{\n [McpServerTool, Description(\"Echoes the input back to the client.\")]\n public static string Echo(string message)\n {\n return \"hello \" + message;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/CompleteContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents additional context information for completion requests.\n/// \n/// \n/// This context provides information that helps the server generate more relevant \n/// completion suggestions, such as previously resolved variables in a template.\n/// \npublic sealed class CompleteContext\n{\n /// \n /// Gets or sets previously-resolved variables in a URI template or prompt.\n /// \n [JsonPropertyName(\"arguments\")]\n public IDictionary? Arguments { get; init; }\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Runtime/CompilerServices/RequiredMemberAttribute.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\n#if !NET\nusing System.ComponentModel;\n\nnamespace System.Runtime.CompilerServices\n{\n /// Specifies that a type has required members or that a member is required.\n [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]\n [EditorBrowsable(EditorBrowsableState.Never)]\n internal sealed class RequiredMemberAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListPromptsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of prompts available from the server.\n/// \n/// \n/// The server responds with a containing the available prompts.\n/// See the schema for details.\n/// \npublic sealed class ListPromptsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListRootsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a server to request\n/// a list of roots available from the client.\n/// \n/// \n/// The client responds with a containing the client's roots.\n/// See the schema for details.\n/// \npublic sealed class ListRootsRequestParams : RequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/InitializedNotificationParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a \n/// sent from the client to the server after initialization has finished.\n/// \n/// \n/// See the schema for details.\n/// \npublic sealed class InitializedNotificationParams : NotificationParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListToolsRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of tools available from the server.\n/// \n/// \n/// The server responds with a containing the available tools.\n/// See the schema for details.\n/// \npublic sealed class ListToolsRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourcesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resources available from the server.\n/// \n/// \n/// The server responds with a containing the available resources.\n/// See the schema for details.\n/// \npublic sealed class ListResourcesRequestParams : PaginatedRequestParams;\n"], ["/csharp-sdk/samples/EverythingServer/Tools/TinyImageTool.cs", "using Microsoft.Extensions.AI;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class TinyImageTool\n{\n [McpServerTool(Name = \"getTinyImage\"), Description(\"Get a tiny image from the server\")]\n public static IEnumerable GetTinyImage() => [\n new TextContent(\"This is a tiny image:\"),\n new DataContent(MCP_TINY_IMAGE),\n new TextContent(\"The image above is the MCP tiny image.\")\n ];\n\n internal const string MCP_TINY_IMAGE =\n \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAKsGlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgOfe9JDQEiIgJfQmSCeAlBBaAAXpYCMkAUKJMRBU7MriClZURLCs6KqIgo0idizYFsWC3QVZBNR1sWDDlXeBQ9jdd9575805c+a7c+efmf+e/z9nLgCdKZDJMlF1gCxpjjwyyI8dn5DIJvUABRiY0kBdIMyWcSMiwgCTUft3+dgGyJC9YzuU69/f/1fREImzhQBIBMbJomxhFsbHMe0TyuQ5ALg9mN9kbo5siK9gzJRjDWL8ZIhTR7hviJOHGY8fjomO5GGsDUCmCQTyVACaKeZn5wpTsTw0f4ztpSKJFGPsGbyzsmaLMMbqgiUWI8N4KD8n+S95Uv+WM1mZUyBIVfLIXoaF7C/JlmUK5v+fn+N/S1amYrSGOaa0NHlwJGaxvpAHGbNDlSxNnhI+yhLRcPwwpymCY0ZZmM1LHGWRwD9UuTZzStgop0gC+co8OfzoURZnB0SNsnx2pLJWipzHHWWBfKyuIiNG6U8T85X589Ki40Y5VxI7ZZSzM6JCx2J4Sr9cEansXywN8hurG6jce1b2X/Yr4SvX5qRFByv3LhjrXyzljuXMjlf2JhL7B4zFxCjjZTl+ylqyzAhlvDgzSOnPzo1Srs3BDuTY2gjlN0wXhESMMoRBELAhBjIhB+QggECQgBTEOeJ5Q2cUeLNl8+WS1LQcNhe7ZWI2Xyq0m8B2tHd0Bhi6syNH4j1r+C4irGtjvhWVAF4nBgcHT475Qm4BHEkCoNaO+SxnAKh3A1w5JVTIc0d8Q9cJCEAFNWCCDhiACViCLTiCK3iCLwRACIRDNCTATBBCGmRhnc+FhbAMCqAI1sNmKIOdsBv2wyE4CvVwCs7DZbgOt+AePIZ26IJX0AcfYQBBEBJCRxiIDmKImCE2iCPCQbyRACQMiUQSkCQkFZEiCmQhsgIpQoqRMmQXUokcQU4g55GrSCvyEOlAepF3yFcUh9JQJqqPmqMTUQ7KRUPRaHQGmorOQfPQfHQtWopWoAfROvQ8eh29h7ajr9B+HOBUcCycEc4Wx8HxcOG4RFwKTo5bjCvEleAqcNW4Rlwz7g6uHfca9wVPxDPwbLwt3hMfjI/BC/Fz8Ivxq/Fl+P34OvxF/B18B74P/51AJ+gRbAgeBD4hnpBKmEsoIJQQ9hJqCZcI9whdhI9EIpFFtCC6EYOJCcR04gLiauJ2Yg3xHLGV2EnsJ5FIOiQbkhcpnCQg5ZAKSFtJB0lnSbdJXaTPZBWyIdmRHEhOJEvJy8kl5APkM+Tb5G7yAEWdYkbxoIRTRJT5lHWUPZRGyk1KF2WAqkG1oHpRo6np1GXUUmo19RL1CfW9ioqKsYq7ylQVicpSlVKVwypXVDpUvtA0adY0Hm06TUFbS9tHO0d7SHtPp9PN6b70RHoOfS29kn6B/oz+WZWhaqfKVxWpLlEtV61Tva36Ro2iZqbGVZuplqdWonZM7abaa3WKurk6T12gvli9XP2E+n31fg2GhoNGuEaWxmqNAxpXNXo0SZrmmgGaIs18zd2aFzQ7GTiGCYPHEDJWMPYwLjG6mESmBZPPTGcWMQ8xW5h9WppazlqxWvO0yrVOa7WzcCxzFp+VyVrHOspqY30dpz+OO048btW46nG3x33SHq/tqy3WLtSu0b6n/VWHrROgk6GzQade56kuXtdad6ruXN0dupd0X49njvccLxxfOP7o+Ed6qJ61XqTeAr3dejf0+vUN9IP0Zfpb9S/ovzZgGfgapBtsMjhj0GvIMPQ2lBhuMjxr+JKtxeayM9ml7IvsPiM9o2AjhdEuoxajAWML4xjj5cY1xk9NqCYckxSTTSZNJn2mhqaTTReaVpk+MqOYcczSzLaYNZt9MrcwjzNfaV5v3mOhbcG3yLOosnhiSbf0sZxjWWF514poxbHKsNpudcsatXaxTrMut75pg9q42khsttu0TiBMcJ8gnVAx4b4tzZZrm2tbZdthx7ILs1tuV2/3ZqLpxMSJGyY2T/xu72Kfab/H/rGDpkOIw3KHRod3jtaOQsdyx7tOdKdApyVODU5vnW2cxc47nB+4MFwmu6x0aXL509XNVe5a7drrZuqW5LbN7T6HyYngrOZccSe4+7kvcT/l/sXD1SPH46jHH562nhmeBzx7JllMEk/aM6nTy9hL4LXLq92b7Z3k/ZN3u4+Rj8Cnwue5r4mvyHevbzfXipvOPch942fvJ/er9fvE8+At4p3zx/kH+Rf6twRoBsQElAU8CzQOTA2sCuwLcglaEHQumBAcGrwh+D5fny/kV/L7QtxCFoVcDKWFRoWWhT4Psw6ThzVORieHTN44+ckUsynSKfXhEM4P3xj+NMIiYk7EyanEqRFTy6e+iHSIXBjZHMWImhV1IOpjtF/0uujHMZYxipimWLXY6bGVsZ/i/OOK49rjJ8Yvir+eoJsgSWhIJCXGJu5N7J8WMG3ztK7pLtMLprfNsJgxb8bVmbozM2eenqU2SzDrWBIhKS7pQNI3QbigQtCfzE/eltwn5Am3CF+JfEWbRL1iL3GxuDvFK6U4pSfVK3Vjam+aT1pJ2msJT1ImeZsenL4z/VNGeMa+jMHMuMyaLHJWUtYJqaY0Q3pxtsHsebNbZTayAln7HI85m+f0yUPle7OR7BnZDTlMbDi6obBU/KDoyPXOLc/9PDd27rF5GvOk827Mt56/an53XmDezwvwC4QLmhYaLVy2sGMRd9Guxcji5MVNS0yW5C/pWhq0dP8y6rKMZb8st19evPzDirgVjfn6+UvzO38I+qGqQLVAXnB/pefKnT/if5T82LLKadXWVd8LRYXXiuyLSoq+rRauvrbGYU3pmsG1KWtb1rmu27GeuF66vm2Dz4b9xRrFecWdGydvrNvE3lS46cPmWZuvljiX7NxC3aLY0l4aVtqw1XTr+q3fytLK7pX7ldds09u2atun7aLtt3f47qjeqb+zaOfXnyQ/PdgVtKuuwryiZDdxd+7uF3ti9zT/zPm5cq/u3qK9f+6T7mvfH7n/YqVbZeUBvQPrqtAqRVXvwekHbx3yP9RQbVu9q4ZVU3QYDisOvzySdKTtaOjRpmOcY9XHzY5vq2XUFtYhdfPr+urT6tsbEhpaT4ScaGr0bKw9aXdy3ymjU+WntU6vO0M9k39m8Gze2f5zsnOvz6ee72ya1fT4QvyFuxenXmy5FHrpyuXAyxeauc1nr3hdOXXV4+qJa5xr9dddr9fdcLlR+4vLL7Utri11N91uNtzyv9XYOqn1zG2f2+fv+N+5fJd/9/q9Kfda22LaHtyffr/9gehBz8PMh28f5T4aeLz0CeFJ4VP1pyXP9J5V/Gr1a027a/vpDv+OG8+jnj/uFHa++i37t29d+S/oL0q6Dbsrexx7TvUG9t56Oe1l1yvZq4HXBb9r/L7tjeWb43/4/nGjL76v66387eC71e913u/74PyhqT+i/9nHrI8Dnwo/63ze/4Xzpflr3NfugbnfSN9K/7T6s/F76Pcng1mDgzKBXDA8CuAwRVNSAN7tA6AnADCwGYI6bWSmHhZk5D9gmOA/8cjcPSyuANWYGRqNeOcADmNqvhRAzRdgaCyK9gXUyUmpo/Pv8Kw+JAbYv8K0HECi2x6tebQU/iEjc/xf+v6nBWXWv9l/AV0EC6JTIblRAAAAeGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAJAAAAABAAAAkAAAAAEAAqACAAQAAAABAAAAFKADAAQAAAABAAAAFAAAAAAXNii1AAAACXBIWXMAABYlAAAWJQFJUiTwAAAB82lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOllSZXNvbHV0aW9uPjE0NDwvdGlmZjpZUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgICAgPHRpZmY6WFJlc29sdXRpb24+MTQ0PC90aWZmOlhSZXNvbHV0aW9uPgogICAgICAgICA8dGlmZjpSZXNvbHV0aW9uVW5pdD4yPC90aWZmOlJlc29sdXRpb25Vbml0PgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KReh49gAAAjRJREFUOBGFlD2vMUEUx2clvoNCcW8hCqFAo1dKhEQpvsF9KrWEBh/ALbQ0KkInBI3SWyGPCCJEQliXgsTLefaca/bBWjvJzs6cOf/fnDkzOQJIjWm06/XKBEGgD8c6nU5VIWgBtQDPZPWtJE8O63a7LBgMMo/Hw0ql0jPjcY4RvmqXy4XMjUYDUwLtdhtmsxnYbDbI5/O0djqdFFKmsEiGZ9jP9gem0yn0ej2Yz+fg9XpfycimAD7DttstQTDKfr8Po9GIIg6Hw1Cr1RTgB+A72GAwgMPhQLBMJgNSXsFqtUI2myUo18pA6QJogefsPrLBX4QdCVatViklw+EQRFGEj88P2O12pEUGATmsXq+TaLPZ0AXgMRF2vMEqlQoJTSYTpNNpApvNZliv1/+BHDaZTAi2Wq1A3Ig0xmMej7+RcZjdbodUKkWAaDQK+GHjHPnImB88JrZIJAKFQgH2+z2BOczhcMiwRCIBgUAA+NN5BP6mj2DYff35gk6nA61WCzBn2JxO5wPM7/fLz4vD0E+OECfn8xl/0Gw2KbLxeAyLxQIsFgt8p75pDSO7h/HbpUWpewCike9WLpfB7XaDy+WCYrFI/slk8i0MnRRAUt46hPMI4vE4+Hw+ec7t9/44VgWigEeby+UgFArJWjUYOqhWG6x50rpcSfR6PVUfNOgEVRlTX0HhrZBKz4MZjUYWi8VoA+lc9H/VaRZYjBKrtXR8tlwumcFgeMWRbZpA9ORQWfVm8A/FsrLaxebd5wAAAABJRU5ErkJggg==\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ListResourceTemplatesRequestParams.cs", "namespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the parameters used with a request from a client to request\n/// a list of resource templates available from the server.\n/// \n/// \n/// The server responds with a containing the available resource templates.\n/// See the schema for details.\n/// \npublic sealed class ListResourceTemplatesRequestParams : PaginatedRequestParams;"], ["/csharp-sdk/samples/AspNetCoreSseServer/Program.cs", "using OpenTelemetry;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Trace;\nusing TestServerWithHosting.Tools;\nusing TestServerWithHosting.Resources;\n\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Services.AddMcpServer()\n .WithHttpTransport()\n .WithTools()\n .WithTools()\n .WithResources();\n\nbuilder.Services.AddOpenTelemetry()\n .WithTracing(b => b.AddSource(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithMetrics(b => b.AddMeter(\"*\")\n .AddAspNetCoreInstrumentation()\n .AddHttpClientInstrumentation())\n .WithLogging()\n .UseOtlpExporter();\n\nvar app = builder.Build();\n\napp.MapMcp();\n\napp.Run();\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Authentication/McpAuthenticationDefaults.cs", "namespace ModelContextProtocol.AspNetCore.Authentication;\n\n/// \n/// Default values used by MCP authentication.\n/// \npublic static class McpAuthenticationDefaults\n{\n /// \n /// The default value used for authentication scheme name.\n /// \n public const string AuthenticationScheme = \"McpAuth\";\n\n /// \n /// The default value used for authentication scheme display name.\n /// \n public const string DisplayName = \"MCP Authentication\";\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/IMcpServerPrimitive.cs", "namespace ModelContextProtocol.Server;\n\n/// \n/// Represents an MCP server primitive, like a tool or a prompt.\n/// \npublic interface IMcpServerPrimitive\n{\n /// Gets the unique identifier of the primitive.\n string Id { get; }\n}\n"], ["/csharp-sdk/samples/QuickstartWeatherServer/Program.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing QuickstartWeatherServer.Tools;\nusing System.Net.Http.Headers;\n\nvar builder = Host.CreateApplicationBuilder(args);\n\nbuilder.Services.AddMcpServer()\n .WithStdioServerTransport()\n .WithTools();\n\nbuilder.Logging.AddConsole(options =>\n{\n options.LogToStandardErrorThreshold = LogLevel.Trace;\n});\n\nbuilder.Services.AddSingleton(_ =>\n{\n var client = new HttpClient { BaseAddress = new Uri(\"https://api.weather.gov\") };\n client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(\"weather-tool\", \"1.0\"));\n return client;\n});\n\nawait builder.Build().RunAsync();\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/Role.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents the type of role in the Model Context Protocol conversation.\n/// \n[JsonConverter(typeof(CustomizableJsonStringEnumConverter))]\npublic enum Role\n{\n /// \n /// Corresponds to a human user in the conversation.\n /// \n [JsonStringEnumMemberName(\"user\")]\n User,\n\n /// \n /// Corresponds to the AI assistant in the conversation.\n /// \n [JsonStringEnumMemberName(\"assistant\")]\n Assistant\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServerResourceCollection.cs", "namespace ModelContextProtocol.Server;\n\n/// Provides a thread-safe collection of instances, indexed by their URI templates.\npublic sealed class McpServerResourceCollection()\n : McpServerPrimitiveCollection(UriTemplate.UriTemplateComparer.Instance);"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/EmptyResult.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Represents an empty result object for operations that need to indicate successful completion \n/// but don't need to return any specific data.\n/// \npublic sealed class EmptyResult : Result\n{\n [JsonIgnore]\n internal static EmptyResult Instance { get; } = new();\n}"], ["/csharp-sdk/samples/EverythingServer/Tools/AddTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class AddTool\n{\n [McpServerTool(Name = \"add\"), Description(\"Adds two numbers.\")]\n public static string Add(int a, int b) => $\"The sum of {a} and {b} is {a + b}\";\n}\n"], ["/csharp-sdk/samples/EverythingServer/Tools/EchoTool.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Tools;\n\n[McpServerToolType]\npublic class EchoTool\n{\n [McpServerTool(Name = \"echo\"), Description(\"Echoes the message back to the client.\")]\n public static string Echo(string message) => $\"Echo: {message}\";\n}\n"], ["/csharp-sdk/samples/EverythingServer/Prompts/SimplePromptType.cs", "using ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace EverythingServer.Prompts;\n\n[McpServerPromptType]\npublic class SimplePromptType\n{\n [McpServerPrompt(Name = \"simple_prompt\"), Description(\"A prompt without arguments\")]\n public static string SimplePrompt() => \"This is a simple prompt without arguments\";\n}\n"], ["/csharp-sdk/src/Common/Polyfills/System/Diagnostics/CodeAnalysis/SetsRequiredMembersAttribute.cs", "#if !NET\nnamespace System.Diagnostics.CodeAnalysis\n{\n [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]\n internal sealed class SetsRequiredMembersAttribute : Attribute;\n}\n#endif"], ["/csharp-sdk/samples/AspNetCoreSseServer/Resources/SimpleResourceType.cs", "using ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.ComponentModel;\n\nnamespace TestServerWithHosting.Resources;\n\n[McpServerResourceType]\npublic class SimpleResourceType\n{\n [McpServerResource, Description(\"A direct text resource\")]\n public static string DirectTextResource() => \"This is a direct resource\";\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/UserIdClaim.cs", "namespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed record UserIdClaim(string Type, string Value, string Issuer);\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionId.cs", "using ModelContextProtocol.Protocol;\nusing System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\ninternal sealed class StatelessSessionId\n{\n [JsonPropertyName(\"clientInfo\")]\n public Implementation? ClientInfo { get; init; }\n\n [JsonPropertyName(\"userIdClaim\")]\n public UserIdClaim? UserIdClaim { get; init; }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/Stateless/StatelessSessionIdJsonContext.cs", "using System.Text.Json.Serialization;\n\nnamespace ModelContextProtocol.AspNetCore.Stateless;\n\n[JsonSerializable(typeof(StatelessSessionId))]\ninternal sealed partial class StatelessSessionIdJsonContext : JsonSerializerContext;\n"]], "task_instance_info": {"created_time": "2025-08-20 18:38:49", "created_task_model": "DeepSeek-R1", "class_skeleton": "private\nsealed\nclass\nRegistration\n(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable)\n: IAsyncDisposable\n{\nprivate static readonly AsyncLocal s_invokingAncestor = new();\nprivate readonly NotificationHandlers _handlers = handlers;\nprivate readonly string _method = method;\nprivate readonly Func _handler = handler;\nprivate readonly bool _temporary = unregisterable;\nprivate TaskCompletionSource? _disposeTcs;\nprivate int _refCount = 1;\nprivate bool _disposedCalled = false;\npublic Registration? Next;\npublic Registration? Prev;\npublic async ValueTask DisposeAsync () {}\npublic ValueTask InvokeAsync (JsonRpcNotification notification, CancellationToken cancellationToken) {}\nprivate async ValueTask InvokeTemporaryAsync (JsonRpcNotification notification, CancellationToken cancellationToken) {}\n}", "code_description": "This code segment functions to: Manage dynamic registration lifecycle for temporary event handlers by tracking active invocations and coordinating safe removal through reference counting and synchronization mechanisms to prevent premature disposal during concurrent operations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```c_sharp\n[TASK_BEGIN]\nprivate sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable)\n : IAsyncDisposable\n{\n private static readonly AsyncLocal s_invokingAncestor = new();\n private readonly NotificationHandlers _handlers = handlers;\n private readonly string _method = method;\n private readonly Func _handler = handler;\n private readonly bool _temporary = unregisterable;\n private TaskCompletionSource? _disposeTcs;\n private int _refCount = 1;\n private bool _disposedCalled = false;\n public Registration? Next;\n public Registration? Prev;\n\n public async ValueTask DisposeAsync()\n {\n TaskCompletionSource? tcs = null;\n lock (_handlers.SyncObj)\n {\n if (_disposedCalled) return;\n _disposedCalled = true;\n\n if (!_temporary) return;\n\n // Remove from linked list if we're the current head\n if (_handlers._handlers.TryGetValue(_method, out var currentHead) && currentHead == this)\n {\n if (Next != null)\n {\n _handlers._handlers[_method] = Next;\n Next.Prev = null;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n\n if (--_refCount == 0)\n {\n tcs = _disposeTcs;\n _disposeTcs = null;\n }\n else\n {\n _disposeTcs = new TaskCompletionSource();\n tcs = _disposeTcs;\n }\n }\n\n if (tcs != null)\n {\n await tcs.Task.ConfigureAwait(false);\n }\n }\n\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n if (s_invokingAncestor.Value != 0)\n {\n return _handler(notification, cancellationToken);\n }\n\n lock (_handlers.SyncObj)\n {\n if (_disposedCalled) return ValueTask.CompletedTask;\n _refCount++;\n }\n\n s_invokingAncestor.Value++;\n try\n {\n if (_temporary)\n {\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n return _handler(notification, cancellationToken);\n }\n finally\n {\n s_invokingAncestor.Value--;\n lock (_handlers.SyncObj)\n {\n if (--_refCount == 0 && _disposeTcs != null)\n {\n _disposeTcs.TrySetResult(true);\n }\n }\n }\n }\n\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n try\n {\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n await DisposeAsync().ConfigureAwait(false);\n }\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 18-40-30"}, "editdistance_info": {"edit_distance": 42.0712, "calculate_time": "2025-08-20 18:40:30", "true_code_clean": "private sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable) : IAsyncDisposable\n {\n private static readonly AsyncLocal s_invokingAncestor = new();\n private readonly NotificationHandlers _handlers = handlers;\n private readonly string _method = method;\n private readonly Func _handler = handler;\n private readonly bool _temporary = unregisterable;\n private TaskCompletionSource? _disposeTcs;\n private int _refCount = 1;\n private bool _disposedCalled = false;\n public Registration? Next;\n public Registration? Prev;\n public async ValueTask DisposeAsync()\n {\n if (!_temporary)\n {\n return;\n }\n lock (_handlers.SyncObj)\n {\n if (!_disposedCalled)\n {\n _disposedCalled = true;\n if (_handlers._handlers.TryGetValue(_method, out var handlers) && handlers == this)\n {\n if (Next is not null)\n {\n _handlers._handlers[_method] = Next;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n if (Prev is not null)\n {\n Prev.Next = Next;\n }\n if (Next is not null)\n {\n Next.Prev = Prev;\n }\n if (--_refCount != 0)\n {\n Debug.Assert(_disposeTcs is null);\n _disposeTcs = new(TaskCreationOptions.RunContinuationsAsynchronously);\n }\n }\n }\n if (_disposeTcs is not null && s_invokingAncestor.Value == 0)\n {\n await _disposeTcs.Task.ConfigureAwait(false);\n }\n }\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n if (!_temporary)\n {\n return _handler(notification, cancellationToken);\n }\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n lock (_handlers.SyncObj)\n {\n Debug.Assert(_refCount != 0 || _disposedCalled, $\"Expected {nameof(_disposedCalled)} == true when {nameof(_refCount)} == 0\");\n if (_disposedCalled)\n {\n return;\n }\n Debug.Assert(_refCount > 0);\n _refCount++;\n }\n s_invokingAncestor.Value++;\n try\n {\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n s_invokingAncestor.Value--;\n lock (_handlers.SyncObj)\n {\n _refCount--;\n if (_refCount == 0)\n {\n Debug.Assert(_disposedCalled);\n Debug.Assert(_disposeTcs is not null);\n bool completed = _disposeTcs!.TrySetResult(true);\n Debug.Assert(completed);\n }\n }\n }\n }\n }", "predict_code_clean": "private sealed class Registration(\n NotificationHandlers handlers, string method, Func handler, bool unregisterable)\n : IAsyncDisposable\n{\n private static readonly AsyncLocal s_invokingAncestor = new();\n private readonly NotificationHandlers _handlers = handlers;\n private readonly string _method = method;\n private readonly Func _handler = handler;\n private readonly bool _temporary = unregisterable;\n private TaskCompletionSource? _disposeTcs;\n private int _refCount = 1;\n private bool _disposedCalled = false;\n public Registration? Next;\n public Registration? Prev;\n public async ValueTask DisposeAsync()\n {\n TaskCompletionSource? tcs = null;\n lock (_handlers.SyncObj)\n {\n if (_disposedCalled) return;\n _disposedCalled = true;\n if (!_temporary) return;\n if (_handlers._handlers.TryGetValue(_method, out var currentHead) && currentHead == this)\n {\n if (Next != null)\n {\n _handlers._handlers[_method] = Next;\n Next.Prev = null;\n }\n else\n {\n _handlers._handlers.Remove(_method);\n }\n }\n if (--_refCount == 0)\n {\n tcs = _disposeTcs;\n _disposeTcs = null;\n }\n else\n {\n _disposeTcs = new TaskCompletionSource();\n tcs = _disposeTcs;\n }\n }\n if (tcs != null)\n {\n await tcs.Task.ConfigureAwait(false);\n }\n }\n public ValueTask InvokeAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n if (s_invokingAncestor.Value != 0)\n {\n return _handler(notification, cancellationToken);\n }\n lock (_handlers.SyncObj)\n {\n if (_disposedCalled) return ValueTask.CompletedTask;\n _refCount++;\n }\n s_invokingAncestor.Value++;\n try\n {\n if (_temporary)\n {\n return InvokeTemporaryAsync(notification, cancellationToken);\n }\n return _handler(notification, cancellationToken);\n }\n finally\n {\n s_invokingAncestor.Value--;\n lock (_handlers.SyncObj)\n {\n if (--_refCount == 0 && _disposeTcs != null)\n {\n _disposeTcs.TrySetResult(true);\n }\n }\n }\n }\n private async ValueTask InvokeTemporaryAsync(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n try\n {\n await _handler(notification, cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n await DisposeAsync().ConfigureAwait(false);\n }\n }\n}"}}