Skip to content
19 changes: 19 additions & 0 deletions src/ModelContextProtocol.Core/Protocol/ElicitResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,22 @@ public sealed class ElicitResult : Result
[JsonPropertyName("content")]
public IDictionary<string, JsonElement>? Content { get; set; }
}

/// <summary>
/// Represents the client's response to an elicitation request, with typed content payload.
/// </summary>
/// <typeparam name="T">The type of the expected content payload.</typeparam>
public sealed class ElicitResult<T> : Result
{
/// <summary>
/// Gets or sets the user action in response to the elicitation.
/// </summary>
[JsonPropertyName("action")]
public string Action { get; set; } = "cancel";

/// <summary>
/// Gets or sets the submitted form data as a typed value.
/// </summary>
[JsonPropertyName("content")]
public T? Content { get; set; }
}
106 changes: 106 additions & 0 deletions src/ModelContextProtocol.Core/Server/McpServerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization.Metadata;

namespace ModelContextProtocol.Server;

Expand Down Expand Up @@ -234,6 +236,110 @@ public static ValueTask<ElicitResult> ElicitAsync(
cancellationToken: cancellationToken);
}

/// <summary>
/// Requests additional information from the user via the client, constructing a request schema from the
/// public serializable properties of <typeparamref name="T"/> and deserializing the response into <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type describing the expected input shape. Only primitive members are supported (string, number, boolean, enum).</typeparam>
/// <param name="server">The server initiating the request.</param>
/// <param name="message">The message to present to the user.</param>
/// <param name="serializerOptions">Serializer options that influence property naming and deserialization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
/// <returns>An <see cref="ElicitResult{T}"/> with the user's response, if accepted.</returns>
/// <remarks>
/// Elicitation uses a constrained subset of JSON Schema and only supports strings, numbers/integers, booleans and string enums.
/// Unsupported member types are ignored when constructing the schema.
/// </remarks>
public static async ValueTask<ElicitResult<T?>> ElicitAsync<T>(
this IMcpServer server,
string message,
JsonSerializerOptions? serializerOptions = null,
CancellationToken cancellationToken = default) where T : class
{
Throw.IfNull(server);
ThrowIfElicitationUnsupported(server);

serializerOptions ??= McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();

var schema = BuildRequestSchema<T>(serializerOptions);

var request = new ElicitRequestParams
{
Message = message,
RequestedSchema = schema,
};

var raw = await server.ElicitAsync(request, cancellationToken).ConfigureAwait(false);

if (!string.Equals(raw.Action, "accept", StringComparison.OrdinalIgnoreCase) || raw.Content is null)
{
return new ElicitResult<T?> { Action = raw.Action, Content = default };
}

var obj = new JsonObject();
foreach (var kvp in raw.Content)
{
obj[kvp.Key] = JsonNode.Parse(kvp.Value.GetRawText());
}

T? typed = JsonSerializer.Deserialize(obj, serializerOptions.GetTypeInfo<T>());
return new ElicitResult<T?> { Action = raw.Action, Content = typed };
}

private static ElicitRequestParams.RequestSchema BuildRequestSchema<T>(JsonSerializerOptions serializerOptions)
{
var schema = new ElicitRequestParams.RequestSchema();
var props = schema.Properties;

JsonTypeInfo<T> typeInfo = serializerOptions.GetTypeInfo<T>();

if (typeInfo.Kind != JsonTypeInfoKind.Object)
{
throw new McpException($"Type '{typeof(T).FullName}' is not supported for elicitation requests.");
}

foreach (JsonPropertyInfo pi in typeInfo.Properties)
{
var memberType = pi.PropertyType;
string name = pi.Name; // serialized name honoring naming policy/attributes
var def = CreatePrimitiveSchema(memberType, serializerOptions);
if (def is not null)
{
props[name] = def;
}
}

return schema;
}

private static ElicitRequestParams.PrimitiveSchemaDefinition? CreatePrimitiveSchema(Type type, JsonSerializerOptions serializerOptions)
{
Type underlyingType = Nullable.GetUnderlyingType(type) ?? type;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove this normalization step.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I remove this, nullable types such as bool? will result in a resolved schema represented as an array with "type": ["boolean", "null"] (instead of "type": "boolean"). This cannot be deserialized into a PrimitiveSchemaDefinition because the converter expects the types to be strings and does not support arrays:

public class Converter : JsonConverter<PrimitiveSchemaDefinition>
{
  public override PrimitiveSchemaDefinition? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  {
    // ...
    switch (propertyName)
    {
      case "type":
        type = reader.GetString(); // THROWS exception as it is an array for nullable types like bool?
        break;

To resolve this, I could modify the converter to accommodate nullable types in this way:

case "type":
    if (reader.TokenType == JsonTokenType.String)
    {
        type = reader.GetString();
    }
    else if (reader.TokenType == JsonTokenType.StartArray)
    {
        var types = JsonSerializer.Deserialize(ref reader, McpJsonUtilities.JsonContext.Default.StringArray);
        if (types is [var nullableType, "null"])
        {
            type = nullableType;
        }
    }
    break;

Does this make sense?


JsonTypeInfo typeInfo = serializerOptions.GetTypeInfo(underlyingType);

if (typeInfo.Kind != JsonTypeInfoKind.None)
{
throw new McpException($"Type '{type.FullName}' is not supported for elicitation requests.");
}

var jsonElement = AIJsonUtilities.CreateJsonSchema(underlyingType, serializerOptions: serializerOptions);

if (jsonElement.TryGetProperty("type", out var typeElement))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if the schema is just {} or true? What if the schema contains a supported type keyword but then also contains other unsupported keywords? Shouldn't we be validating those as well?

{
var typeValue = typeElement.GetString();
if (typeValue is "string" or "number" or "integer" or "boolean")
{
var primitiveSchemaDefinition =
jsonElement.Deserialize(McpJsonUtilities.JsonContext.Default.PrimitiveSchemaDefinition);
return primitiveSchemaDefinition;
}
}

return null;
}

private static void ThrowIfSamplingUnsupported(IMcpServer server)
{
if (server.ClientCapabilities?.Sampling is null)
Expand Down
Loading