-
Notifications
You must be signed in to change notification settings - Fork 4k
.Net: MCP prompt sample #11342
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 14 commits into
microsoft:main
from
SergeyMenshykh:sk-prompt-as-mcp-prompt
Apr 3, 2025
Merged
.Net: MCP prompt sample #11342
Changes from 9 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
660d422
add mcp prompt sample
SergeyMenshykh f86b6f4
add xml comment
SergeyMenshykh fc4c150
make GetCurrentWeatherForCityPrompt more generic
SergeyMenshykh f371ebd
simplify sample
SergeyMenshykh e136e5c
rename PromptResource
SergeyMenshykh c744983
Merge branch 'main' into sk-prompt-as-mcp-prompt
SergeyMenshykh c2df5bf
fix warnings
SergeyMenshykh 3299493
Merge branch 'sk-prompt-as-mcp-prompt' of https://github.com/SergeyMe…
SergeyMenshykh c5f76d9
Update dotnet/samples/Demos/ModelContextProtocolClientServer/MCPServe…
SergeyMenshykh 95bd10c
Address PR review comments
SergeyMenshykh ee9438b
Merge branch 'sk-prompt-as-mcp-prompt' of https://github.com/SergeyMe…
SergeyMenshykh 0c1e96a
Merge branch 'main' into sk-prompt-as-mcp-prompt
SergeyMenshykh 2db02f8
Merge branch 'main' into sk-prompt-as-mcp-prompt
SergeyMenshykh 4b46c01
Merge branch 'main' into sk-prompt-as-mcp-prompt
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
45 changes: 45 additions & 0 deletions
45
...les/Demos/ModelContextProtocolClientServer/MCPClient/Extensions/PromptResultExtensions.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,45 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using System; | ||
using Microsoft.SemanticKernel; | ||
using Microsoft.SemanticKernel.ChatCompletion; | ||
using ModelContextProtocol.Protocol.Types; | ||
|
||
namespace MCPClient; | ||
|
||
/// <summary> | ||
/// Extension methods for <see cref="GetPromptResult"/>. | ||
/// </summary> | ||
internal static class PromptResultExtensions | ||
{ | ||
/// <summary> | ||
/// Converts a <see cref="GetPromptResult"/> to a <see cref="ChatHistory"/>. | ||
/// </summary> | ||
/// <param name="result">The prompt result to convert.</param> | ||
/// <returns>The corresponding <see cref="ChatHistory"/>.</returns> | ||
public static ChatHistory ToChatHistory(this GetPromptResult result) | ||
{ | ||
ChatHistory chatHistory = []; | ||
|
||
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; | ||
default: | ||
throw new InvalidOperationException($"Unexpected message content type '{message.Content.Type}'"); | ||
} | ||
|
||
chatHistory.Add(new ChatMessageContent(message.Role.ToAuthorRole(), items)); | ||
} | ||
|
||
return chatHistory; | ||
} | ||
} |
28 changes: 28 additions & 0 deletions
28
dotnet/samples/Demos/ModelContextProtocolClientServer/MCPClient/Extensions/RoleExtensions.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,28 @@ | ||
// 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="Role"/> enum. | ||
/// </summary> | ||
internal static class RoleExtensions | ||
{ | ||
/// <summary> | ||
/// Converts a <see cref="Role"/> to a <see cref="AuthorRole"/>. | ||
/// </summary> | ||
/// <param name="role">The MCP role to convert.</param> | ||
/// <returns>The corresponding <see cref="AuthorRole"/>.</returns> | ||
public static AuthorRole ToAuthorRole(this Role role) | ||
{ | ||
return role switch | ||
{ | ||
Role.User => AuthorRole.User, | ||
Role.Assistant => AuthorRole.Assistant, | ||
_ => throw new InvalidOperationException($"Unexpected role '{role}'") | ||
}; | ||
} | ||
} |
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
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
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
32 changes: 32 additions & 0 deletions
32
dotnet/samples/Demos/ModelContextProtocolClientServer/MCPServer/Prompts/EmbeddedResource.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,32 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using System.Reflection; | ||
|
||
namespace MCPServer.Prompts; | ||
|
||
/// <summary> | ||
/// Reads embedded resources. | ||
/// </summary> | ||
public static class EmbeddedResource | ||
{ | ||
private static readonly string? s_namespace = typeof(EmbeddedResource).Namespace; | ||
|
||
internal static string ReadAsString(string fileName) | ||
{ | ||
// Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored. | ||
Assembly assembly = | ||
typeof(EmbeddedResource).GetTypeInfo().Assembly ?? | ||
throw new InvalidOperationException($"[{s_namespace}] {fileName} assembly not found"); | ||
|
||
// Resources are mapped like types, using the namespace and appending "." (dot) and the file name | ||
string resourceName = $"{s_namespace}.{fileName}"; | ||
|
||
Stream stream = | ||
assembly.GetManifestResourceStream(resourceName) ?? | ||
throw new InvalidOperationException($"{resourceName} resource not found"); | ||
|
||
// Return the resource content, in text format. | ||
using StreamReader reader = new(stream); | ||
return reader.ReadToEnd(); | ||
} | ||
} |
111 changes: 111 additions & 0 deletions
111
dotnet/samples/Demos/ModelContextProtocolClientServer/MCPServer/Prompts/PromptDefinition.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,111 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using Microsoft.SemanticKernel; | ||
using Microsoft.SemanticKernel.PromptTemplates.Handlebars; | ||
using ModelContextProtocol.Protocol.Types; | ||
using ModelContextProtocol.Server; | ||
|
||
namespace MCPServer.Prompts; | ||
|
||
/// <summary> | ||
/// Represents a prompt definition. | ||
/// </summary> | ||
internal sealed class PromptDefinition | ||
{ | ||
/// <summary> | ||
/// Gets or sets the prompt. | ||
/// </summary> | ||
public required Prompt Prompt { get; init; } | ||
|
||
/// <summary> | ||
/// Gets or sets the handler for the prompt. | ||
/// </summary> | ||
public required Func<RequestContext<GetPromptRequestParams>, CancellationToken, Task<GetPromptResult>> Handler { get; init; } | ||
|
||
/// <summary> | ||
/// Gets this prompt definition. | ||
/// </summary> | ||
/// <param name="jsonPrompt">The JSON prompt template.</param> | ||
/// <param name="kernel">An instance of the kernel to render the prompt.</param> | ||
/// <returns>The prompt definition.</returns> | ||
public static PromptDefinition Create(string jsonPrompt, Kernel kernel) | ||
{ | ||
PromptTemplateConfig promptTemplateConfig = PromptTemplateConfig.FromJson(jsonPrompt); | ||
|
||
return new PromptDefinition() | ||
{ | ||
Prompt = GetPrompt(promptTemplateConfig), | ||
Handler = (context, cancellationToken) => | ||
{ | ||
IPromptTemplate promptTemplate = new HandlebarsPromptTemplateFactory().Create(promptTemplateConfig); | ||
|
||
return GetPromptHandlerAsync(context, promptTemplateConfig, promptTemplate, kernel, cancellationToken); | ||
} | ||
}; | ||
} | ||
|
||
/// <summary> | ||
/// Creates an MCP prompt from SK prompt template. | ||
/// </summary> | ||
/// <param name="promptTemplateConfig">The prompt template configuration.</param> | ||
/// <returns>The MCP prompt.</returns> | ||
private static Prompt GetPrompt(PromptTemplateConfig promptTemplateConfig) | ||
{ | ||
// Create the MCP prompt arguments | ||
List<PromptArgument>? arguments = null; | ||
|
||
foreach (var inputVariable in promptTemplateConfig.InputVariables) | ||
{ | ||
(arguments ??= []).Add(new() | ||
{ | ||
Name = inputVariable.Name, | ||
Description = inputVariable.Description, | ||
Required = inputVariable.IsRequired | ||
}); | ||
} | ||
|
||
// Create the MCP prompt | ||
return new Prompt | ||
{ | ||
Name = promptTemplateConfig.Name!, | ||
Description = promptTemplateConfig.Description, | ||
Arguments = arguments | ||
}; | ||
} | ||
|
||
/// <summary> | ||
/// Handles the prompt request by rendering the prompt. | ||
/// </summary> | ||
/// <param name="context">The prompt request context.</param> | ||
/// <param name="promptTemplateConfig">The prompt template configuration.</param> | ||
/// <param name="promptTemplate">The prompt template.</param> | ||
/// <param name="kernel">The kernel to render the prompt.</param> | ||
/// <param name="cancellationToken">The cancellation token.</param> | ||
/// <returns>The prompt.</returns> | ||
private static async Task<GetPromptResult> GetPromptHandlerAsync(RequestContext<GetPromptRequestParams> context, PromptTemplateConfig promptTemplateConfig, IPromptTemplate promptTemplate, Kernel kernel, CancellationToken cancellationToken) | ||
{ | ||
// Render the prompt | ||
string renderedPrompt = await promptTemplate.RenderAsync( | ||
kernel: kernel, | ||
arguments: context.Params?.Arguments is { } args ? new KernelArguments(args!) : null, | ||
cancellationToken: cancellationToken); | ||
|
||
// Create prompt result | ||
return new GetPromptResult() | ||
{ | ||
Description = promptTemplateConfig.Description, | ||
Messages = | ||
[ | ||
new PromptMessage() | ||
{ | ||
Content = new Content() | ||
{ | ||
Type = "text", | ||
Text = renderedPrompt | ||
}, | ||
Role = Role.User | ||
} | ||
] | ||
}; | ||
} | ||
} |
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.