{"repo_name": "csharp-sdk", "file_name": "/csharp-sdk/src/ModelContextProtocol.Core/Protocol/ToolAnnotations.cs", "inference_info": {"prefix_code": "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", "suffix_code": "", "middle_code": "{\n [JsonPropertyName(\"title\")]\n public string? Title { get; set; }\n [JsonPropertyName(\"destructiveHint\")]\n public bool? DestructiveHint { get; set; }\n [JsonPropertyName(\"idempotentHint\")]\n public bool? IdempotentHint { get; set; }\n [JsonPropertyName(\"openWorldHint\")]\n public bool? OpenWorldHint { get; set; }\n [JsonPropertyName(\"readOnlyHint\")]\n public bool? ReadOnlyHint { get; set; }\n}", "code_description": null, "fill_type": "BLOCK_TYPE", "language_type": "c_sharp", "sub_task_type": "while_statement"}, "context_code": [["/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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 /// endTurn The model naturally completed its response. \n /// maxTokens The response was truncated due to reaching token limits. \n /// stopSequence A 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/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/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/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/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/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/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/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/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/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/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/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/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.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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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.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/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/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/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/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/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/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/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 ///