Skip to content

Change type of Tool.InputSchema to be JsonElement #4

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

Merged
merged 4 commits into from
Mar 20, 2025
Merged
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
4 changes: 1 addition & 3 deletions samples/anthropic/tools/ToolsConsole/McpToolExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ public static class McpToolExtensions
List<Anthropic.SDK.Common.Tool> result = [];
foreach (var tool in tools)
{
var function = tool.InputSchema == null
? new Function(tool.Name, tool.Description)
: new Function(tool.Name, tool.Description, JsonSerializer.Serialize(tool.InputSchema));
var function = new Function(tool.Name, tool.Description, JsonSerializer.SerializeToNode(tool.InputSchema));
result.Add(function);
}
return result;
Expand Down
12 changes: 1 addition & 11 deletions src/ModelContextProtocol/Client/McpClientExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -466,24 +466,14 @@ private static JsonRpcRequest CreateRequest(string method, Dictionary<string, ob
/// <summary>Provides an AI function that calls a tool through <see cref="IMcpClient"/>.</summary>
private sealed class McpAIFunction(IMcpClient client, Tool tool) : AIFunction
{
private JsonElement? _jsonSchema;

/// <inheritdoc/>
public override string Name => tool.Name;

/// <inheritdoc/>
public override string Description => tool.Description ?? string.Empty;

/// <inheritdoc/>
public override JsonElement JsonSchema => _jsonSchema ??=
JsonSerializer.SerializeToElement(new Dictionary<string, object>
{
["type"] = "object",
["title"] = tool.Name,
["description"] = tool.Description ?? string.Empty,
["properties"] = tool.InputSchema?.Properties ?? [],
["required"] = tool.InputSchema?.Required ?? []
}, McpJsonUtilities.JsonContext.Default.DictionaryStringObject);
public override JsonElement JsonSchema => tool.InputSchema;

/// <inheritdoc/>
protected async override Task<object?> InvokeCoreAsync(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ public static IMcpServerBuilder WithTools(this IMcpServerBuilder builder, params
{
Name = function.Name,
Description = function.Description,
InputSchema = JsonSerializer.Deserialize(function.JsonSchema, McpJsonUtilities.JsonContext.Default.JsonSchema),
InputSchema = function.JsonSchema,
});

callbacks.Add(function.Name, async (request, cancellationToken) =>
Expand Down
26 changes: 0 additions & 26 deletions src/ModelContextProtocol/Protocol/Types/JsonSchema.cs

This file was deleted.

20 changes: 0 additions & 20 deletions src/ModelContextProtocol/Protocol/Types/JsonSchemaProperty.cs

This file was deleted.

23 changes: 21 additions & 2 deletions src/ModelContextProtocol/Protocol/Types/Tool.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Text.Json.Serialization;
using ModelContextProtocol.Utils.Json;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ModelContextProtocol.Protocol.Types;

Expand All @@ -23,6 +25,23 @@ public class Tool
/// <summary>
/// A JSON Schema object defining the expected parameters for the tool.
/// </summary>
/// <remarks>
/// Needs to a valid JSON schema object that additionally is of type object.
/// </remarks>
[JsonPropertyName("inputSchema")]
public JsonSchema? InputSchema { get; set; }
public JsonElement InputSchema
{
get => _inputSchema;
set
{
if (!McpJsonUtilities.IsValidMcpToolSchema(value))
{
throw new ArgumentException("The specified document is not a valid MPC tool JSON schema.", nameof(InputSchema));
}

_inputSchema = value;
}
}

private JsonElement _inputSchema = McpJsonUtilities.DefaultMcpToolSchema;
}
33 changes: 32 additions & 1 deletion src/ModelContextProtocol/Utils/Json/McpJsonUtilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,31 @@ private static JsonSerializerOptions CreateDefaultOptions()
internal static JsonTypeInfo<T> GetTypeInfo<T>(this JsonSerializerOptions options) =>
(JsonTypeInfo<T>)options.GetTypeInfo(typeof(T));

internal static JsonElement DefaultMcpToolSchema = ParseJsonElement("{\"type\":\"object\"}"u8);
internal static bool IsValidMcpToolSchema(JsonElement element)
{
if (element.ValueKind is not JsonValueKind.Object)
{
return false;
}

foreach (JsonProperty property in element.EnumerateObject())
{
if (property.NameEquals("type"))
{
if (property.Value.ValueKind is not JsonValueKind.String ||
!property.Value.ValueEquals("object"))
{
return false;
}

return true; // No need to check other properties
}
}

return false; // No type keyword found.
}

// Keep in sync with CreateDefaultOptions above.
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web,
UseStringEnumConverter = true,
Expand All @@ -96,7 +121,13 @@ internal static JsonTypeInfo<T> GetTypeInfo<T>(this JsonSerializerOptions option
[JsonSerializable(typeof(CreateMessageResult))]
[JsonSerializable(typeof(ListRootsResult))]
[JsonSerializable(typeof(InitializeResult))]
[JsonSerializable(typeof(JsonSchema))]
[JsonSerializable(typeof(CallToolResponse))]
internal sealed partial class JsonContext : JsonSerializerContext;

private static JsonElement ParseJsonElement(ReadOnlySpan<byte> utf8Json)
{
Utf8JsonReader reader = new(utf8Json);
return JsonElement.ParseValue(ref reader);
}

}
42 changes: 27 additions & 15 deletions tests/ModelContextProtocol.TestServer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System.Text;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Protocol.Messages;
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Text;
using System.Text.Json;

namespace ModelContextProtocol.TestServer;

Expand Down Expand Up @@ -91,28 +92,39 @@ private static ToolsCapability ConfigureTools()
{
Name = "echo",
Description = "Echoes the input back to the client.",
InputSchema = new JsonSchema()
{
Type = "object",
Properties = new Dictionary<string, JsonSchemaProperty>()
InputSchema = JsonSerializer.Deserialize<JsonElement>("""
{
["message"] = new JsonSchemaProperty() { Type = "string", Description = "The input to echo back." }
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The input to echo back."
}
},
"required": ["message"]
}
},
"""),
},
new Tool()
{
Name = "sampleLLM",
Description = "Samples from an LLM using MCP's sampling feature.",
InputSchema = new JsonSchema()
{
Type = "object",
Properties = new Dictionary<string, JsonSchemaProperty>()
InputSchema = JsonSerializer.Deserialize<JsonElement>("""
{
["prompt"] = new JsonSchemaProperty() { Type = "string", Description = "The prompt to send to the LLM" },
["maxTokens"] = new JsonSchemaProperty() { Type = "number", Description = "Maximum number of tokens to generate" }
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "The prompt to send to the LLM"
},
"maxTokens": {
"type": "number",
"description": "Maximum number of tokens to generate"
}
},
"required": ["prompt", "maxTokens"]
}
},
"""),
}
]
});
Expand Down
38 changes: 25 additions & 13 deletions tests/ModelContextProtocol.TestSseServer/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.Extensions.Logging;
using Serilog;
using System.Text;
using System.Text.Json;

internal class Program
{
Expand Down Expand Up @@ -121,28 +122,39 @@ static CreateMessageRequestParams CreateRequestSamplingParams(string context, st
{
Name = "echo",
Description = "Echoes the input back to the client.",
InputSchema = new JsonSchema()
{
Type = "object",
Properties = new Dictionary<string, JsonSchemaProperty>()
InputSchema = JsonSerializer.Deserialize<JsonElement>("""
{
["message"] = new JsonSchemaProperty() { Type = "string", Description = "The input to echo back." }
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The input to echo back."
}
},
"required": ["message"]
}
},
"""),
},
new Tool()
{
Name = "sampleLLM",
Description = "Samples from an LLM using MCP's sampling feature.",
InputSchema = new JsonSchema()
{
Type = "object",
Properties = new Dictionary<string, JsonSchemaProperty>()
InputSchema = JsonSerializer.Deserialize<JsonElement>("""
{
["prompt"] = new JsonSchemaProperty() { Type = "string", Description = "The prompt to send to the LLM" },
["maxTokens"] = new JsonSchemaProperty() { Type = "number", Description = "Maximum number of tokens to generate" }
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "The prompt to send to the LLM"
},
"maxTokens": {
"type": "number",
"description": "Maximum number of tokens to generate"
}
},
"required": ["prompt", "maxTokens"]
}
},
"""),
}
]
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,10 @@ public async Task Can_List_Registered_Tool()
var tool = result.Tools[0];
Assert.Equal("Echo", tool.Name);
Assert.Equal("Echoes the input back to the client.", tool.Description);
Assert.NotNull(tool.InputSchema);
Assert.Equal("object", tool.InputSchema.Type);
Assert.NotNull(tool.InputSchema.Properties);
Assert.NotEmpty(tool.InputSchema.Properties);
Assert.Contains("message", tool.InputSchema.Properties);
Assert.Equal("string", tool.InputSchema.Properties["message"].Type);
Assert.Equal("the echoes message", tool.InputSchema.Properties["message"].Description);
Assert.NotNull(tool.InputSchema.Required);
Assert.NotEmpty(tool.InputSchema.Required);
Assert.Contains("message", tool.InputSchema.Required);
Assert.Equal("object", tool.InputSchema.GetProperty("type").GetString());
Assert.Equal(JsonValueKind.Object, tool.InputSchema.GetProperty("properties").GetProperty("message").ValueKind);
Assert.Equal("the echoes message", tool.InputSchema.GetProperty("properties").GetProperty("message").GetProperty("description").GetString());
Assert.Equal(1, tool.InputSchema.GetProperty("required").GetArrayLength());

tool = result.Tools[1];
Assert.Equal("double_echo", tool.Name);
Expand Down Expand Up @@ -288,31 +282,15 @@ public async Task Recognizes_Parameter_Types()
var tool = result.Tools.First(t => t.Name == "TestTool");
Assert.Equal("TestTool", tool.Name);
Assert.Empty(tool.Description!);
Assert.NotNull(tool.InputSchema);
Assert.Equal("object", tool.InputSchema.Type);
Assert.NotNull(tool.InputSchema.Properties);
Assert.NotEmpty(tool.InputSchema.Properties);

Assert.Contains("number", tool.InputSchema.Properties);
Assert.Equal("integer", tool.InputSchema.Properties["number"].Type);

Assert.Contains("otherNumber", tool.InputSchema.Properties);
Assert.Equal("number", tool.InputSchema.Properties["otherNumber"].Type);

Assert.Contains("someCheck", tool.InputSchema.Properties);
Assert.Equal("boolean", tool.InputSchema.Properties["someCheck"].Type);

Assert.Contains("someDate", tool.InputSchema.Properties);
Assert.Equal("string", tool.InputSchema.Properties["someDate"].Type);

Assert.Contains("someOtherDate", tool.InputSchema.Properties);
Assert.Equal("string", tool.InputSchema.Properties["someOtherDate"].Type);

Assert.Contains("data", tool.InputSchema.Properties);
Assert.Equal("array", tool.InputSchema.Properties["data"].Type);

Assert.Contains("complexObject", tool.InputSchema.Properties);
Assert.Equal("object", tool.InputSchema.Properties["complexObject"].Type);
Assert.Equal("object", tool.InputSchema.GetProperty("type").GetString());

Assert.Contains("integer", tool.InputSchema.GetProperty("properties").GetProperty("number").GetProperty("type").GetString());
Assert.Contains("number", tool.InputSchema.GetProperty("properties").GetProperty("otherNumber").GetProperty("type").GetString());
Assert.Contains("boolean", tool.InputSchema.GetProperty("properties").GetProperty("someCheck").GetProperty("type").GetString());
Assert.Contains("string", tool.InputSchema.GetProperty("properties").GetProperty("someDate").GetProperty("type").GetString());
Assert.Contains("string", tool.InputSchema.GetProperty("properties").GetProperty("someOtherDate").GetProperty("type").GetString());
Assert.Contains("array", tool.InputSchema.GetProperty("properties").GetProperty("data").GetProperty("type").GetString());
Assert.Contains("object", tool.InputSchema.GetProperty("properties").GetProperty("complexObject").GetProperty("type").GetString());
}

[McpToolType]
Expand Down
Loading
Loading