Skip to content

Validate and filter inputSchema for McpServerTool so it is spec compliant #343

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
41 changes: 40 additions & 1 deletion src/ModelContextProtocol/Server/AIFunctionMcpServerTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(
{
Name = options?.Name ?? function.Name,
Description = options?.Description ?? function.Description,
InputSchema = function.JsonSchema,
InputSchema = FilterJsonSchema(function.JsonSchema),
};

if (options is not null)
Expand Down Expand Up @@ -220,6 +220,45 @@ options.OpenWorld is not null ||
return newOptions;
}

/// <summary>
/// Filters a JsonElement containing a schema to only include allowed properties: "type", "properties", and "required".
/// </summary>
private static JsonElement FilterJsonSchema(JsonElement schema)
{
using var memoryStream = new MemoryStream();
using var writer = new Utf8JsonWriter(memoryStream);
Copy link
Contributor

@halter73 halter73 Apr 22, 2025

Choose a reason for hiding this comment

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

I think it would probably be better to use JsonObject to build up the JSON DOM and then convert that to a JsonElement using jsonNode.Deserialize<JsonElement>(typeInfo).

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/use-dom#create-a-jsonnode-dom-with-object-initializers-and-make-changes

@eiriktsarpalis is probably the best person to ask about the right approach here though.

Edit: Could we also use AIFunctionFactoryOptions.JsonSchemaCreateOptions.TransformSchemaNode for the AIFunctions we create ourselves from Delegates and the like and avoid generating the intermediate schema in that case?

Copy link
Contributor

Choose a reason for hiding this comment

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

Edit: Could we also use AIFunctionFactoryOptions.JsonSchemaCreateOptions.TransformSchemaNode for the AIFunctions we create ourselves from Delegates and the like and avoid generating the intermediate schema in that case?

Yep, that's the best way to achieve that. Although per my remarks in #343 (comment) this should most likely be left to individual implementers as I think the metaschema is not meant to be interpreted literally.


writer.WriteStartObject();

// Include "type" property if it exists
if (schema.TryGetProperty("type", out var typeElement))
{
writer.WritePropertyName("type");
typeElement.WriteTo(writer);
}

// Include "properties" property if it exists
if (schema.TryGetProperty("properties", out var propertiesElement))
{
writer.WritePropertyName("properties");
propertiesElement.WriteTo(writer);
}

// Include "required" property if it exists
if (schema.TryGetProperty("required", out var requiredElement))
{
writer.WritePropertyName("required");
requiredElement.WriteTo(writer);
}

writer.WriteEndObject();
writer.Flush();

memoryStream.Position = 0;
using var document = JsonDocument.Parse(memoryStream.ToArray());
return document.RootElement.Clone();
}

/// <summary>Gets the <see cref="AIFunction"/> wrapped by this tool.</summary>
internal AIFunction AIFunction { get; }

Expand Down
8 changes: 6 additions & 2 deletions src/ModelContextProtocol/Utils/Json/McpJsonUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,12 @@ internal static bool IsValidMcpToolSchema(JsonElement element)
{
return false;
}

return true; // No need to check other properties
Copy link
Contributor

Choose a reason for hiding this comment

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

Now we need to update the return false; at the end of the loop to return true if the "type" property was found and know unknown properties were found.

}
else if (!(property.NameEquals("properties") ||
property.NameEquals("required")))
{
// Only "type", "properties", and "required" are allowed.
return false;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static void ToolInputSchema_HasValidDefaultSchema()
[InlineData("""{"type":"number"}""")]
[InlineData("""{"type":"array"}""")]
[InlineData("""{"type":["object"]}""")]
[InlineData("""{"type":"object", "title": "MyAwesomeTool", "description": "It's awesome!", "properties": {}, "required" : ["NotAParam"] }""")]
public static void ToolInputSchema_RejectsInvalidSchemaDocuments(string invalidSchema)
{
using var document = JsonDocument.Parse(invalidSchema);
Expand All @@ -41,7 +42,7 @@ public static void ToolInputSchema_RejectsInvalidSchemaDocuments(string invalidS
[Theory]
[InlineData("""{"type":"object"}""")]
[InlineData("""{"type":"object", "properties": {}, "required" : [] }""")]
[InlineData("""{"type":"object", "title": "MyAwesomeTool", "description": "It's awesome!", "properties": {}, "required" : ["NotAParam"] }""")]
[InlineData("""{"type":"object", "properties": {}, "required" : ["NotAParam"] }""")]
public static void ToolInputSchema_AcceptsValidSchemaDocuments(string validSchema)
{
using var document = JsonDocument.Parse(validSchema);
Expand Down
Loading