-
Notifications
You must be signed in to change notification settings - Fork 4k
.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
SergeyMenshykh
merged 8 commits into
microsoft:main
from
SergeyMenshykh:mcp-sampling-sample
Apr 14, 2025
Merged
.Net: Mcp sampling sample #11533
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
46fcf11
1. add mcp sampling sample
SergeyMenshykh b6e0e9b
fix xml comment
SergeyMenshykh d4b794c
improve xml comments
SergeyMenshykh 22fcb53
Merge branch 'main' into mcp-sampling-sample
SergeyMenshykh 2c2b7d9
update to the latest mcp neget package
SergeyMenshykh b736482
Merge branch 'mcp-sampling-sample' of https://github.com/SergeyMenshy…
SergeyMenshykh fb6dfa2
address pr review comments
SergeyMenshykh b929d8b
fix warning
SergeyMenshykh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
33 changes: 33 additions & 0 deletions
33
...mples/Demos/ModelContextProtocolClientServer/MCPClient/Extensions/AuthorRoleExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}'"); | ||
} | ||
} |
66 changes: 66 additions & 0 deletions
66
...mos/ModelContextProtocolClientServer/MCPClient/Extensions/ChatMessageContentExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}; | ||
} | ||
} |
29 changes: 29 additions & 0 deletions
29
.../samples/Demos/ModelContextProtocolClientServer/MCPClient/Extensions/ContentExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}'"), | ||
}; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
34 changes: 34 additions & 0 deletions
34
.../Demos/ModelContextProtocolClientServer/MCPClient/Extensions/SamplingMessageExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()]); | ||
} | ||
} |
48 changes: 48 additions & 0 deletions
48
dotnet/samples/Demos/ModelContextProtocolClientServer/MCPClient/HumanInTheLoopFilter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.