Add ElicitAsync<T> (#630) (#715)

* Add ElicitAsync<T> (#630)

- Refactored `ElicitResult` to a generic class `ElicitResult<T>` for typed content.
- Added `ElicitAsync<T>` method in `McpServerExtensions.cs` to request user input and construct schemas based on type `T`.
- Implemented schema building logic to handle primitive types and enums, ignoring unsupported types.
- Introduced `ElicitationTypedTests.cs` for testing the new elicitation functionality with typed forms.
- Verified naming policies in tests to ensure correct serialization casing.
- Defined `SampleForm` and `CamelForm` classes for expected input shapes, including unsupported properties for schema testing.
- Created JSON serialization contexts for both forms using source generation for improved performance.

* Fix the enum issue. for ElicitAsync<T>.

* Use AIJsonUtilities.CreateJsonSchema to create PrimitiveSchemaDefinition. #630

Renamed `BuildRequestSchemaFor<T>` to `BuildRequestSchema<T>`.
Updated the implementation to use `CreatePrimitiveSchema` and
enhanced type checks for supported primitives with
`AIJsonUtilities.CreateJsonSchema`. Streamlined handling of
unsupported types by consolidating return statements.

* Simplify ElicitAsync for schema validation. #630

Simplified the `ElicitAsync` method in `McpServerExtensions.cs` by removing unnecessary JSON object construction and directly deserializing `raw.Content`. Updated `CreatePrimitiveSchema` to use `JsonTypeInfo` for type checking and adjusted return logic for unsupported types.

In `ElicitationTypedTests.cs`, modified the `Can_Elicit_Typed_Information` test to account for the new `Created` property in `SampleForm`, increasing the expected property count from 5 to 6. Added assertions for the type and format of the `Created` property and included its deserialization in the test setup.

* Add error handling for unsupported elicitation types #630

Introduce exception handling in `McpServerExtensions.cs` for unsupported types. Add a test case in `ElicitationTypedTests.cs` to verify exception throwing for unsupported types. Define a new `UnsupportedForm` class with nested properties and include JSON serialization attributes for proper handling.

* Validate generic types in BuildRequestSchema #630

Introduce validation to ensure only object types are supported for elicitation requests in the `BuildRequestSchema` method. An exception is thrown for non-object types. Update the test suite with a new test case to verify this behavior, ensuring that an exception is raised when eliciting a non-object generic type (e.g., string) and that the elicitation handler is not invoked in this scenario.

* Move nullable types handling logic to ElicitationRequestParams.Coverter. #630

* Add schema validation for elicitation requests

Introduce `TryValidateElicitationPrimitiveSchema` method to validate JSON schemas for elicitation requests. This method checks for object type, verifies the "type" property, and ensures compliance with allowed properties based on primitive types (string, boolean, number). Integrate this validation in the `BuildRequestSchema` method to ensure generated schemas are valid before further processing.

* Refactor nullable type pattern matching. #630

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Add ElicitResultSchemaCache. #630

* Prepopulate elicit schema validation logic. #630

- Introduced `LazyElicitAllowedProperties` to cache allowed property names for primitive types, replacing hardcoded logic.
- Streamlined `TryValidateElicitationPrimitiveSchema` method by consolidating type checks using pattern matching.
- Removed manual addition of allowed properties and now retrieve them directly from the new dictionary.
- Updated handling of "integer" type to be treated as "number" for consistency.

* Use Nullable.GetUnderlyingType to handle nullable types on elicitation. #630

- Update `ElicitRequestParams.cs` to throw a `JsonException` for non-string "type" properties, simplifying error handling.
- Modify `CreatePrimitiveSchema` in `McpServerExtensions.cs` to better handle nullable types and improve error messages.
- Revise `TryValidateElicitationPrimitiveSchema` to accept schema as the first parameter, enhancing clarity in error reporting.
- Simplify validation logic for the "type" keyword by directly retrieving string values, ensuring unsupported "type" arrays are flagged as errors.

* Rename static field.

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Fix static field renamings. #630

* Make BuildRequestSchema non-generic. #630

* Avoid closure allocation for serializerOptions on netcore  #630

Updated the `GetOrAdd` method to use a generic type parameter for .NET, allowing for better handling of `JsonSerializerOptions`. Retained the original implementation for other frameworks to ensure compatibility.

* Refactor ElicitRequestParams and McpServerExtensions. #630

- Simplified "type" property handling in Converter.
- Changed s_lazyElicitAllowedProperties to nullable type.
- Updated ElicitAsync to use static lambda for clarity.
- Refactored CreatePrimitiveSchema to handle nullable types.
- Initialized allowed properties in TryValidateElicitationPrimitiveSchema.
- Updated ElicitationTypedTests for naming conventions and added tests for nullable properties.
- Enforced required properties in SampleForm and introduced NullablePropertyForm.
- Added JSON source generation context for NullablePropertyForm.

* Remove reduntant checks. #630

Refactor JSON schema type handling and add integer support

This commit simplifies the validation logic for the `type` property in the JSON schema by removing unnecessary conditional checks. It directly retrieves the string value from `typeProperty` and assigns it to `typeKeyword`. Additionally, it enhances the `s_lazyElicitAllowedProperties` dictionary to include support for the `integer` type, allowing it to be recognized as a valid type with its corresponding allowed properties.

* Add IsAccepted property and update ElicitAsync return type

- Introduced `IsAccepted` property in `ElicitResult` and `ElicitResult<T>` to indicate if the action was accepted.
- Changed `ElicitAsync<T>` to return `ValueTask<ElicitResult<T>>` instead of `ValueTask<ElicitResult<T?>>`, ensuring non-nullable results.
- Updated return statements in `ElicitAsync<T>` to reflect the new return type, treating `Content` as non-nullable.

* Rename to s_elicitAllowedProperties

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Fix renaming s_elicitAllowedProperties. #630

* Remove unnecessary json attributes. #630

* Improve xml comment

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Remove extra IsAccepted property. #630

* Use IsAccepted for checks.

Co-authored-by: Stephen Toub <stoub@microsoft.com>

* Add IsAccepted to non-generic ElicitResult.

---------

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
This commit is contained in:
Mehran Davoudi 2025-09-15 18:50:50 +04:00 • committed by GitHub
commit 15d1271212
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 608 additions and 0 deletions

View file

@ -33,6 +33,15 @@ public sealed class ElicitResult : Result
[JsonPropertyName("action")]
public string Action { get; set; } = "cancel";
/// <summary>
/// Convenience indicator for whether the elicitation was accepted by the user.
/// </summary>
/// <remarks>
/// Indicates that the elicitation request completed successfully and value of <see cref="Content"/> has been populated with a value.
/// </remarks>
[JsonIgnore]
public bool IsAccepted => string.Equals(Action, "accept", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets the submitted form data.
/// </summary>
@ -48,3 +57,28 @@ 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>
public string Action { get; set; } = "cancel";
/// <summary>
/// Convenience indicator for whether the elicitation was accepted by the user.
/// </summary>
/// <remarks>
/// Indicates that the elicitation request completed successfully and value of <see cref="Content"/> has been populated with a value.
/// </remarks>
public bool IsAccepted => string.Equals(Action, "accept", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Gets or sets the submitted form data as a typed value.
/// </summary>
public T? Content { get; set; }
}

View file

@ -1,9 +1,13 @@
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Protocol;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
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;
@ -12,6 +16,13 @@ namespace ModelContextProtocol.Server;
/// </summary>
public static class McpServerExtensions
{
/// <summary>
/// Caches request schemas for elicitation requests based on the type and serializer options.
/// </summary>
private static readonly ConditionalWeakTable<JsonSerializerOptions, ConcurrentDictionary<Type, ElicitRequestParams.RequestSchema>> s_elicitResultSchemaCache = new();
private static Dictionary<string, HashSet<string>>? s_elicitAllowedProperties = null;
/// <summary>
/// Requests to sample an LLM via the client using the specified request parameters.
/// </summary>
@ -234,6 +245,190 @@ public static class McpServerExtensions
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)
{
Throw.IfNull(server);
ThrowIfElicitationUnsupported(server);
serializerOptions ??= McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
var dict = s_elicitResultSchemaCache.GetValue(serializerOptions, _ => new());
#if NET
var schema = dict.GetOrAdd(typeof(T), static (t, s) => BuildRequestSchema(t, s), serializerOptions);
#else
var schema = dict.GetOrAdd(typeof(T), type => BuildRequestSchema(type, serializerOptions));
#endif
var request = new ElicitRequestParams
{
Message = message,
RequestedSchema = schema,
};
var raw = await server.ElicitAsync(request, cancellationToken).ConfigureAwait(false);
if (!raw.IsAccepted || 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 };
}
/// <summary>
/// Builds a request schema for elicitation based on the public serializable properties of <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the schema being built.</param>
/// <param name="serializerOptions">The serializer options to use.</param>
/// <returns>The built request schema.</returns>
/// <exception cref="McpException"></exception>
private static ElicitRequestParams.RequestSchema BuildRequestSchema(Type type, JsonSerializerOptions serializerOptions)
{
var schema = new ElicitRequestParams.RequestSchema();
var props = schema.Properties;
JsonTypeInfo typeInfo = serializerOptions.GetTypeInfo(type);
if (typeInfo.Kind != JsonTypeInfoKind.Object)
{
throw new McpException($"Type '{type.FullName}' is not supported for elicitation requests.");
}
foreach (JsonPropertyInfo pi in typeInfo.Properties)
{
var def = CreatePrimitiveSchema(pi.PropertyType, serializerOptions);
props[pi.Name] = def;
}
return schema;
}
/// <summary>
/// Creates a primitive schema definition for the specified type, if supported.
/// </summary>
/// <param name="type">The type to create the schema for.</param>
/// <param name="serializerOptions">The serializer options to use.</param>
/// <returns>The created primitive schema definition.</returns>
/// <exception cref="McpException">Thrown when the type is not supported.</exception>
private static ElicitRequestParams.PrimitiveSchemaDefinition CreatePrimitiveSchema(Type type, JsonSerializerOptions serializerOptions)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
throw new McpException($"Type '{type.FullName}' is not a supported property type for elicitation requests. Nullable types are not supported.");
}
var typeInfo = serializerOptions.GetTypeInfo(type);
if (typeInfo.Kind != JsonTypeInfoKind.None)
{
throw new McpException($"Type '{type.FullName}' is not a supported property type for elicitation requests.");
}
var jsonElement = AIJsonUtilities.CreateJsonSchema(type, serializerOptions: serializerOptions);
if (!TryValidateElicitationPrimitiveSchema(jsonElement, type, out var error))
{
throw new McpException(error);
}
var primitiveSchemaDefinition =
jsonElement.Deserialize(McpJsonUtilities.JsonContext.Default.PrimitiveSchemaDefinition);
if (primitiveSchemaDefinition is null)
throw new McpException($"Type '{type.FullName}' is not a supported property type for elicitation requests.");
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="schema">The schema to validate.</param>
/// <param name="type">The type of the schema being validated, just for reporting errors.</param>
/// <param name="error">The error message, if validation fails.</param>
/// <returns></returns>
private static bool TryValidateElicitationPrimitiveSchema(JsonElement schema, Type type,
[NotNullWhen(false)] out string? error)
{
if (schema.ValueKind is not JsonValueKind.Object)
{
error = $"Schema generated for type '{type.FullName}' is invalid: expected an object schema.";
return false;
}
if (!schema.TryGetProperty("type", out JsonElement typeProperty)
|| typeProperty.ValueKind is not JsonValueKind.String)
{
error = $"Schema generated for type '{type.FullName}' is invalid: missing or invalid 'type' keyword.";
return false;
}
var typeKeyword = typeProperty.GetString();
if (string.IsNullOrEmpty(typeKeyword))
{
error = $"Schema generated for type '{type.FullName}' is invalid: empty 'type' value.";
return false;
}
if (typeKeyword is not ("string" or "number" or "integer" or "boolean"))
{
error = $"Schema generated for type '{type.FullName}' is invalid: unsupported primitive type '{typeKeyword}'.";
return false;
}
s_elicitAllowedProperties ??= new()
{
["string"] = ["type", "title", "description", "minLength", "maxLength", "format", "enum", "enumNames"],
["number"] = ["type", "title", "description", "minimum", "maximum"],
["integer"] = ["type", "title", "description", "minimum", "maximum"],
["boolean"] = ["type", "title", "description", "default"]
};
var allowed = s_elicitAllowedProperties[typeKeyword];
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)

View file

@ -0,0 +1,379 @@
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ModelContextProtocol.Tests.Configuration;
public partial class ElicitationTypedTests : ClientServerTestBase
{
public ElicitationTypedTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
mcpServerBuilder.WithCallToolHandler(async (request, cancellationToken) =>
{
Assert.NotNull(request.Params);
if (request.Params!.Name == "TestElicitationTyped")
{
var result = await request.Server.ElicitAsync<SampleForm>(
message: "Please provide more information.",
serializerOptions: ElicitationTypedDefaultJsonContext.Default.Options,
cancellationToken: CancellationToken.None);
Assert.Equal("accept", result.Action);
Assert.NotNull(result.Content);
Assert.Equal("Alice", result.Content!.Name);
Assert.Equal(30, result.Content!.Age);
Assert.True(result.Content!.Active);
Assert.Equal(SampleRole.Admin, result.Content!.Role);
Assert.Equal(99.5, result.Content!.Score);
}
else if (request.Params!.Name == "TestElicitationCamelForm")
{
var result = await request.Server.ElicitAsync<CamelForm>(
message: "Please provide more information.",
serializerOptions: ElicitationTypedCamelJsonContext.Default.Options,
cancellationToken: CancellationToken.None);
Assert.Equal("accept", result.Action);
Assert.NotNull(result.Content);
Assert.Equal("Bob", result.Content!.FirstName);
Assert.Equal(90210, result.Content!.ZipCode);
Assert.False(result.Content!.IsAdmin);
}
else if (request.Params!.Name == "TestElicitationNullablePropertyForm")
{
var result = await request.Server.ElicitAsync<NullablePropertyForm>(
message: "Please provide more information.",
serializerOptions: ElicitationNullablePropertyJsonContext.Default.Options,
cancellationToken: CancellationToken.None);
// Should be unreachable
return new CallToolResult
{
Content = [new TextContentBlock { Text = "unexpected" }],
};
}
else if (request.Params!.Name == "TestElicitationUnsupportedType")
{
await request.Server.ElicitAsync<UnsupportedForm>(
message: "Please provide more information.",
serializerOptions: ElicitationUnsupportedJsonContext.Default.Options,
cancellationToken: CancellationToken.None);
// Should be unreachable
return new CallToolResult
{
Content = [new TextContentBlock { Text = "unexpected" }],
};
}
else if (request.Params!.Name == "TestElicitationNonObjectGenericType")
{
// This should throw because T is not an object type with properties (string primitive)
await request.Server.ElicitAsync<string>(
message: "Any message",
serializerOptions: McpJsonUtilities.DefaultOptions,
cancellationToken: CancellationToken.None);
return new CallToolResult
{
Content = [new TextContentBlock { Text = "unexpected" }],
};
}
else
{
Assert.Fail($"Unexpected tool name: {request.Params!.Name}");
}
return new CallToolResult
{
Content = [new TextContentBlock { Text = "success" }],
};
});
}
[Fact]
public async Task Can_Elicit_Typed_Information()
{
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new()
{
Elicitation = new()
{
ElicitationHandler = async (request, cancellationToken) =>
{
Assert.NotNull(request);
Assert.Equal("Please provide more information.", request.Message);
Assert.Equal(6, request.RequestedSchema.Properties.Count);
foreach (var entry in request.RequestedSchema.Properties)
{
var key = entry.Key;
var value = entry.Value;
switch (key)
{
case nameof(SampleForm.Name):
var stringSchema = Assert.IsType<ElicitRequestParams.StringSchema>(value);
Assert.Equal("string", stringSchema.Type);
break;
case nameof(SampleForm.Age):
var intSchema = Assert.IsType<ElicitRequestParams.NumberSchema>(value);
Assert.Equal("integer", intSchema.Type);
break;
case nameof(SampleForm.Active):
var boolSchema = Assert.IsType<ElicitRequestParams.BooleanSchema>(value);
Assert.Equal("boolean", boolSchema.Type);
break;
case nameof(SampleForm.Role):
var enumSchema = Assert.IsType<ElicitRequestParams.EnumSchema>(value);
Assert.Equal("string", enumSchema.Type);
Assert.Equal([nameof(SampleRole.User), nameof(SampleRole.Admin)], enumSchema.Enum);
break;
case nameof(SampleForm.Score):
var numSchema = Assert.IsType<ElicitRequestParams.NumberSchema>(value);
Assert.Equal("number", numSchema.Type);
break;
case nameof(SampleForm.Created):
var dateTimeSchema = Assert.IsType<ElicitRequestParams.StringSchema>(value);
Assert.Equal("string", dateTimeSchema.Type);
Assert.Equal("date-time", dateTimeSchema.Format);
break;
default:
Assert.Fail($"Unexpected property in schema: {key}");
break;
}
}
return new ElicitResult
{
Action = "accept",
Content = new Dictionary<string, JsonElement>
{
[nameof(SampleForm.Name)] = (JsonElement)JsonSerializer.Deserialize("""
"Alice"
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
[nameof(SampleForm.Age)] = (JsonElement)JsonSerializer.Deserialize("""
30
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
[nameof(SampleForm.Active)] = (JsonElement)JsonSerializer.Deserialize("""
true
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
[nameof(SampleForm.Role)] = (JsonElement)JsonSerializer.Deserialize("""
"Admin"
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
[nameof(SampleForm.Score)] = (JsonElement)JsonSerializer.Deserialize("""
99.5
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
[nameof(SampleForm.Created)] = (JsonElement)JsonSerializer.Deserialize("""
"2023-08-27T03:05:00"
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
},
};
},
},
},
});
var result = await client.CallToolAsync("TestElicitationTyped", cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal("success", (result.Content[0] as TextContentBlock)?.Text);
}
[Fact]
public async Task Elicit_Typed_Respects_NamingPolicy()
{
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new()
{
Elicitation = new()
{
ElicitationHandler = async (request, cancellationToken) =>
{
Assert.NotNull(request);
Assert.Equal("Please provide more information.", request.Message);
// Expect camelCase names based on serializer options
Assert.Contains("firstName", request.RequestedSchema.Properties.Keys);
Assert.Contains("zipCode", request.RequestedSchema.Properties.Keys);
Assert.Contains("isAdmin", request.RequestedSchema.Properties.Keys);
return new ElicitResult
{
Action = "accept",
Content = new Dictionary<string, JsonElement>
{
["firstName"] = (JsonElement)JsonSerializer.Deserialize("""
"Bob"
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
["zipCode"] = (JsonElement)JsonSerializer.Deserialize("""
90210
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
["isAdmin"] = (JsonElement)JsonSerializer.Deserialize("""
false
""", McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonElement)))!,
},
};
},
},
},
});
var result = await client.CallToolAsync("TestElicitationCamelForm", cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal("success", (result.Content[0] as TextContentBlock)?.Text);
}
[Fact]
public async Task Elicit_Typed_With_Unsupported_Property_Type_Throws()
{
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new()
{
Elicitation = new()
{
// Handler should never be invoked because the exception occurs before the request is sent.
ElicitationHandler = async (req, ct) =>
{
Assert.Fail("Elicitation handler should not be called for unsupported schema test.");
return new ElicitResult { Action = "cancel" };
},
},
},
});
var ex = await Assert.ThrowsAsync<McpException>(async() =>
await client.CallToolAsync("TestElicitationUnsupportedType", cancellationToken: TestContext.Current.CancellationToken));
Assert.Contains(typeof(UnsupportedForm.Nested).FullName!, ex.Message);
}
[Fact]
public async Task Elicit_Typed_With_Nullable_Property_Type_Throws()
{
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new()
{
Elicitation = new()
{
// Handler should never be invoked because the exception occurs before the request is sent.
ElicitationHandler = async (req, ct) =>
{
Assert.Fail("Elicitation handler should not be called for unsupported schema test.");
return new ElicitResult { Action = "cancel" };
},
},
},
});
var ex = await Assert.ThrowsAsync<McpException>(async () =>
await client.CallToolAsync("TestElicitationNullablePropertyForm", cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public async Task Elicit_Typed_With_NonObject_Generic_Type_Throws()
{
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
{
Capabilities = new()
{
Elicitation = new()
{
// Should not be invoked
ElicitationHandler = async (req, ct) =>
{
Assert.Fail("Elicitation handler should not be called for non-object generic type test.");
return new ElicitResult { Action = "cancel" };
},
},
},
});
var ex = await Assert.ThrowsAsync<McpException>(async () =>
await client.CallToolAsync("TestElicitationNonObjectGenericType", cancellationToken: TestContext.Current.CancellationToken));
Assert.Contains(typeof(string).FullName!, ex.Message);
}
[JsonConverter(typeof(CustomizableJsonStringEnumConverter<SampleRole>))]
public enum SampleRole
{
User,
Admin,
}
public sealed class SampleForm
{
public required string Name { get; set; }
public int Age { get; set; }
public bool Active { get; set; }
public SampleRole Role { get; set; }
public double Score { get; set; }
public DateTime Created { get; set; }
}
public sealed class CamelForm
{
public required string FirstName { get; set; }
public int ZipCode { get; set; }
public bool IsAdmin { get; set; }
}
public sealed class NullablePropertyForm
{
public string? FirstName { get; set; }
public int ZipCode { get; set; }
public bool IsAdmin { get; set; }
}
[JsonSerializable(typeof(SampleForm))]
[JsonSerializable(typeof(SampleRole))]
[JsonSerializable(typeof(JsonElement))]
internal partial class ElicitationTypedDefaultJsonContext : JsonSerializerContext;
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(CamelForm))]
[JsonSerializable(typeof(JsonElement))]
internal partial class ElicitationTypedCamelJsonContext : JsonSerializerContext;
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(NullablePropertyForm))]
[JsonSerializable(typeof(JsonElement))]
internal partial class ElicitationNullablePropertyJsonContext : JsonSerializerContext;
public sealed class UnsupportedForm
{
public string? Name { get; set; }
public Nested? NestedProperty { get; set; } // Triggers unsupported (complex object)
public sealed class Nested
{
public string? Value { get; set; }
}
}
[JsonSerializable(typeof(UnsupportedForm))]
[JsonSerializable(typeof(UnsupportedForm.Nested))]
[JsonSerializable(typeof(JsonElement))]
internal partial class ElicitationUnsupportedJsonContext : JsonSerializerContext;
}