Skip to content

.Net: Mcp sampling sample #11533

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 8 commits into from
Apr 14, 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
2 changes: 1 addition & 1 deletion dotnet/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
<PackageVersion Include="Grpc.AspNetCore.Server.Reflection" Version="2.70.0" />
<PackageVersion Include="Grpc.AspNetCore.Web" Version="2.70.0" />
<PackageVersion Include="Grpc.Tools" Version="2.70.0" />
<PackageVersion Include="ModelContextProtocol" Version="0.1.0-preview.7" />
<PackageVersion Include="ModelContextProtocol" Version="0.1.0-preview.8" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.13" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="8.0.14" />
<PackageVersion Include="Microsoft.ML.Tokenizers.Data.Cl100kBase" Version="1.0.1" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using Microsoft.SemanticKernel.ChatCompletion;
using ModelContextProtocol.Protocol.Types;

namespace MCPClient;

/// <summary>
/// Extension methods for the <see cref="AuthorRole"/>.
/// </summary>
internal static class AuthorRoleExtensions
{
/// <summary>
/// Converts a <see cref="AuthorRole"/> to a <see cref="Role"/>.
/// </summary>
/// <param name="role">The author role to convert.</param>
/// <returns>The corresponding <see cref="Role"/>.</returns>
public static Role ToMCPRole(this AuthorRole role)
{
if (role == AuthorRole.User)
{
return Role.User;
}

if (role == AuthorRole.Assistant)
{
return Role.Assistant;
}

throw new InvalidOperationException($"Unexpected role '{role}'");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Linq;
using Microsoft.SemanticKernel;
using ModelContextProtocol.Protocol.Types;

namespace MCPClient;

/// <summary>
/// Extension methods for <see cref="ChatMessageContent"/>.
/// </summary>
public static class ChatMessageContentExtensions
{
/// <summary>
/// Converts a <see cref="ChatMessageContent"/> to a <see cref="CreateMessageResult"/>.
/// </summary>
/// <param name="chatMessageContent">The <see cref="ChatMessageContent"/> to convert.</param>
/// <returns>The corresponding <see cref="CreateMessageResult"/>.</returns>
public static CreateMessageResult ToCreateMessageResult(this ChatMessageContent chatMessageContent)
{
// Using the same heuristic as in the original MCP SDK code: McpClientExtensions.ToCreateMessageResult for consistency.
// ChatMessageContent can contain multiple items of different modalities, while the CreateMessageResult
// can only have a single content type: text, image, or audio. First, look for image or audio content,
// and if not found, fall back to the text content type by concatenating the text of all text contents.
Content? content = null;

foreach (KernelContent item in chatMessageContent.Items)
{
if (item is ImageContent image)
{
content = new Content
{
Type = "image",
Data = Convert.ToBase64String(image.Data!.Value.Span),
MimeType = image.MimeType
};
break;
}
else if (item is AudioContent audio)
{
content = new Content
{
Type = "audio",
Data = Convert.ToBase64String(audio.Data!.Value.Span),
MimeType = audio.MimeType
};
break;
}
}

content ??= new Content
{
Type = "text",
Text = string.Concat(chatMessageContent.Items.OfType<TextContent>()),
MimeType = "text/plain"
};

return new CreateMessageResult
{
Role = chatMessageContent.Role.ToMCPRole(),
Model = chatMessageContent.ModelId ?? "unknown",
Content = content
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using Microsoft.SemanticKernel;
using ModelContextProtocol.Protocol.Types;

namespace MCPClient;

/// <summary>
/// Extension methods for the <see cref="Content"/> class.
/// </summary>
public static class ContentExtensions
{
/// <summary>
/// Converts a <see cref="Content"/> object to a <see cref="KernelContent"/> object.
/// </summary>
/// <param name="content">The <see cref="Content"/> object to convert.</param>
/// <returns>The corresponding <see cref="KernelContent"/> object.</returns>
public static KernelContent ToKernelContent(this Content content)
{
return content.Type switch
{
"text" => new TextContent(content.Text),
"image" => new ImageContent(Convert.FromBase64String(content.Data!), content.MimeType),
"audio" => new AudioContent(Convert.FromBase64String(content.Data!), content.MimeType),
_ => throw new InvalidOperationException($"Unexpected message content type '{content.Type}'"),
};
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using ModelContextProtocol.Protocol.Types;
Expand All @@ -20,30 +20,16 @@ internal static class PromptResultExtensions
/// <returns>The corresponding <see cref="ChatHistory"/>.</returns>
public static IList<ChatMessageContent> ToChatMessageContents(this GetPromptResult result)
{
List<ChatMessageContent> contents = [];

foreach (PromptMessage message in result.Messages)
{
ChatMessageContentItemCollection items = [];

switch (message.Content.Type)
{
case "text":
items.Add(new TextContent(message.Content.Text));
break;
case "image":
items.Add(new ImageContent(Convert.FromBase64String(message.Content.Data!), message.Content.MimeType));
break;
case "audio":
items.Add(new AudioContent(Convert.FromBase64String(message.Content.Data!), message.Content.MimeType));
break;
default:
throw new InvalidOperationException($"Unexpected message content type '{message.Content.Type}'");
}

contents.Add(new ChatMessageContent(message.Role.ToAuthorRole(), items));
}
return [.. result.Messages.Select(ToChatMessageContent)];
}

return contents;
/// <summary>
/// Converts a <see cref="PromptMessage"/> to a <see cref="ChatMessageContent"/>.
/// </summary>
/// <param name="message">The <see cref="PromptMessage"/> to convert.</param>
/// <returns>The corresponding <see cref="ChatMessageContent"/>.</returns>
public static ChatMessageContent ToChatMessageContent(this PromptMessage message)
{
return new ChatMessageContent(role: message.Role.ToAuthorRole(), items: [message.Content.ToKernelContent()]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (c) Microsoft. All rights reserved.

using System.Collections.Generic;
using System.Linq;
using Microsoft.SemanticKernel;
using ModelContextProtocol.Protocol.Types;

namespace MCPClient;

/// <summary>
/// Extension methods for <see cref="SamplingMessage"/>.
/// </summary>
public static class SamplingMessageExtensions
{
/// <summary>
/// Converts a collection of <see cref="SamplingMessage"/> to a list of <see cref="ChatMessageContent"/>.
/// </summary>
/// <param name="samplingMessages">The collection of <see cref="SamplingMessage"/> to convert.</param>
/// <returns>The corresponding list of <see cref="ChatMessageContent"/>.</returns>
public static List<ChatMessageContent> ToChatMessageContents(this IEnumerable<SamplingMessage> samplingMessages)
{
return [.. samplingMessages.Select(ToChatMessageContent)];
}

/// <summary>
/// Converts a <see cref="SamplingMessage"/> to a <see cref="ChatMessageContent"/>.
/// </summary>
/// <param name="message">The <see cref="SamplingMessage"/> to convert.</param>
/// <returns>The corresponding <see cref="ChatMessageContent"/>.</returns>
public static ChatMessageContent ToChatMessageContent(this SamplingMessage message)
{
return new ChatMessageContent(role: message.Role.ToAuthorRole(), items: [message.Content.ToKernelContent()]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
using ModelContextProtocol.Protocol.Types;

namespace MCPClient;

/// <summary>
/// A filter that intercepts function invocations to allow for human-in-the-loop processing.
/// </summary>
public class HumanInTheLoopFilter : IFunctionInvocationFilter
{
/// <inheritdoc />
public Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func<FunctionInvocationContext, Task> next)
{
// Intercept the MCP sampling handler before invoking it
if (context.Function.Name == "MCPSamplingHandler")
{
CreateMessageRequestParams request = (CreateMessageRequestParams)context.Arguments["request"]!;

if (!GetUserApprovalForSamplingMessages(request))
{
context.Result = new FunctionResult(context.Result, "Operation was rejected due to PII.");
return Task.CompletedTask;
}
}

// Proceed with the handler invocation
return next.Invoke(context);
}

/// <summary>
/// Checks if the user approves the messages for further sampling request processing.
/// </summary>
/// <remarks>
/// This method serves as a placeholder for the actual implementation, which may involve user interaction through a user interface.
/// The user will be presented with a list of messages and given two options: to approve or reject the request.
/// </remarks>
/// <param name="request">The sampling request.</param>
/// <returns>Returns true if the user approves; otherwise, false.</returns>
private static bool GetUserApprovalForSamplingMessages(CreateMessageRequestParams request)
{
// Approve the request
return true;
}
}
Loading
Loading