Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
6c04345
Add ElicitAsync<T> (#630)
mehrandvd Aug 18, 2025
839e5f9
Merge branch 'main' into add-elicitasync
mehrandvd Aug 21, 2025
9f1100b
Fix the enum issue. for ElicitAsync<T>.
mehrandvd Aug 22, 2025
0259465
Use AIJsonUtilities.CreateJsonSchema to create PrimitiveSchemaDefinit…
mehrandvd Aug 23, 2025
309b2da
Merge latest main.
mehrandvd Aug 26, 2025
e520a33
Simplify ElicitAsync for schema validation. #630
mehrandvd Aug 27, 2025
86ecb95
Merge branch 'modelcontextprotocol:main' into add-elicitasync
mehrandvd Aug 27, 2025
3d5a1d6
Add error handling for unsupported elicitation types #630
mehrandvd Aug 27, 2025
ade05e6
Validate generic types in BuildRequestSchema #630
mehrandvd Aug 28, 2025
a2fdf0a
Move nullable types handling logic to ElicitationRequestParams.Covert…
mehrandvd Sep 2, 2025
ec19bd5
Add schema validation for elicitation requests
mehrandvd Sep 2, 2025
85e8e26
Merge branch 'modelcontextprotocol:main' into add-elicitasync
mehrandvd Sep 3, 2025
49c3fa9
Refactor nullable type pattern matching. #630
mehrandvd Sep 3, 2025
f31815e
Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs
mehrandvd Sep 4, 2025
1abcfde
Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs
mehrandvd Sep 4, 2025
400b14d
Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs
mehrandvd Sep 4, 2025
0ac795b
Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs
mehrandvd Sep 4, 2025
c78da12
Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs
mehrandvd Sep 4, 2025
6457cbd
Add ElicitResultSchemaCache. #630
mehrandvd Sep 5, 2025
dfaedf3
Prepopulate elicit schema validation logic. #630
mehrandvd Sep 5, 2025
18eae33
Merge branch 'modelcontextprotocol:main' into add-elicitasync
mehrandvd Sep 5, 2025
c8e9bc8
Use Nullable.GetUnderlyingType to handle nullable types on elicitatio…
mehrandvd Sep 5, 2025
7f554ed
Rename static field.
mehrandvd Sep 5, 2025
c8b3a08
Fix static field renamings. #630
mehrandvd Sep 5, 2025
a227475
Make BuildRequestSchema non-generic. #630
mehrandvd Sep 5, 2025
d141073
Avoid closure allocation for serializerOptions on netcore #630
mehrandvd Sep 6, 2025
2f1dcf0
Merge branch 'modelcontextprotocol:main' into add-elicitasync
mehrandvd Sep 8, 2025
c5419c6
Refactor ElicitRequestParams and McpServerExtensions. #630
mehrandvd Sep 8, 2025
1a32217
Remove reduntant checks. #630
mehrandvd Sep 8, 2025
4f20c12
Add IsAccepted property and update ElicitAsync return type
mehrandvd Sep 8, 2025
9419e11
Rename to s_elicitAllowedProperties
mehrandvd Sep 8, 2025
4775040
Fix renaming s_elicitAllowedProperties. #630
mehrandvd Sep 9, 2025
a3b6c11
Remove unnecessary json attributes. #630
mehrandvd Sep 9, 2025
c5a22f6
Improve xml comment
mehrandvd Sep 10, 2025
444dea7
Remove extra IsAccepted property. #630
mehrandvd Sep 11, 2025
1d6c5c7
Use IsAccepted for checks.
mehrandvd Sep 12, 2025
54e0f12
Add IsAccepted to non-generic ElicitResult.
mehrandvd Sep 12, 2025
ccb48e9
Merge branch 'modelcontextprotocol:main' into add-elicitasync
mehrandvd Sep 15, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/ModelContextProtocol.Core/Protocol/ElicitRequestParams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,19 @@ public class Converter : JsonConverter<PrimitiveSchemaDefinition>
switch (propertyName)
{
case "type":
type = reader.GetString();
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;

case "title":
Expand Down
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; }
}
197 changes: 197 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,201 @@ 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)
{
JsonTypeInfo typeInfo = serializerOptions.GetTypeInfo(type);

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

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

if (!TryValidateElicitationPrimitiveSchema(type, jsonElement, out var error))
{
throw new McpException(error);
}

var primitiveSchemaDefinition =
jsonElement.Deserialize(McpJsonUtilities.JsonContext.Default.PrimitiveSchemaDefinition);
return primitiveSchemaDefinition;
}

/// <summary>
/// Validate the produced schema strictly to the subset we support. We only accept an object schema
/// with a supported primitive type keyword and no additional unsupported keywords.Reject things like
/// {}, 'true', or schemas that include unrelated keywords(e.g.items, properties, patternProperties, etc.).
/// </summary>
/// <param name="type">The type of the schema being validated.</param>
/// <param name="schema">The schema to validate.</param>
/// <param name="error">The error message, if validation fails.</param>
/// <returns></returns>
private static bool TryValidateElicitationPrimitiveSchema(Type type, JsonElement schema, out string error)
{
if (schema.ValueKind is not JsonValueKind.Object)
{
error = $"Schema generated for type '{type.FullName}' is invalid: expected a JSON object.";
return false;
}

if (!schema.TryGetProperty("type", out JsonElement typeProperty)
|| !(typeProperty.ValueKind is JsonValueKind.String or JsonValueKind.Array))
{
error = $"Schema generated for type '{type.FullName}' is invalid: missing or non-string 'type' property.";
return false;
}

string? typeKeyword = null;
if (typeProperty.ValueKind == JsonValueKind.Array) // bool? will parse as ["boolean", "null"]
{
var types = JsonSerializer.Deserialize(typeProperty.GetRawText(), McpJsonUtilities.JsonContext.Default.StringArray);
if (types is [var nullableType, "null"])
{
typeKeyword = nullableType;
}
else
{
error = $"Schema generated for type '{type.FullName}' is invalid: unsupported 'type' array.";
return false;
}
}
else
{
typeKeyword = typeProperty.GetString();
}

if (string.IsNullOrEmpty(typeKeyword))
{
error = $"Schema generated for type '{type.FullName}' is invalid: empty 'type' value.";
return false;
}

// Accept number or integer as the numeric primitive (both map to NumberSchema)
bool isString = typeKeyword == "string";
bool isBoolean = typeKeyword == "boolean";
bool isNumber = typeKeyword == "number" || typeKeyword == "integer";
if (!isString && !isBoolean && !isNumber)
{
error = $"Schema generated for type '{type.FullName}' is invalid: unsupported primitive type '{typeKeyword}'.";
return false;
}

// Allowed property names per primitive schema we support.
HashSet<string> allowed = new(StringComparer.Ordinal)
{
"type",
"title",
"description"
};
if (isString)
{
allowed.Add("minLength");
allowed.Add("maxLength");
allowed.Add("format");
allowed.Add("enum"); // for string enums
allowed.Add("enumNames"); // for string enums
}
else if (isNumber)
{
allowed.Add("minimum");
allowed.Add("maximum");
}
else if (isBoolean)
{
allowed.Add("default");
}

foreach (JsonProperty prop in schema.EnumerateObject())
{
if (!allowed.Contains(prop.Name))
{
error = $"The property '{type.FullName}.{prop.Name}' is not supported for elicitation.";
return false;
}
}

error = string.Empty;
return true;
}

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