- 
                Notifications
    You must be signed in to change notification settings 
- Fork 555
Overhaul tool handling #89
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
      
      
            stephentoub
  merged 5 commits into
  modelcontextprotocol:main
from
stephentoub:overhaultools
  
      
      
   
  Mar 25, 2025 
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      
    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
    
  
  
    
              
  
    
      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
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -1,51 +1,36 @@ | ||
| using ModelContextProtocol.Protocol.Types; | ||
| using Microsoft.Extensions.AI; | ||
| using ModelContextProtocol.Server; | ||
| using System.ComponentModel; | ||
|  | ||
| namespace TestServerWithHosting.Tools; | ||
|  | ||
| /// <summary> | ||
| /// This tool uses depenency injection and async method | ||
| /// This tool uses dependency injection and async method | ||
| /// </summary> | ||
| [McpToolType] | ||
| public class SampleLlmTool | ||
| [McpServerToolType] | ||
| public static class SampleLlmTool | ||
| { | ||
| private readonly IMcpServer _server; | ||
|  | ||
| public SampleLlmTool(IMcpServer server) | ||
| { | ||
| _server = server ?? throw new ArgumentNullException(nameof(server)); | ||
| } | ||
|  | ||
| [McpTool("sampleLLM"), Description("Samples from an LLM using MCP's sampling feature")] | ||
| public async Task<string> SampleLLM( | ||
| [McpServerTool("sampleLLM"), Description("Samples from an LLM using MCP's sampling feature")] | ||
| public static async Task<string> SampleLLM( | ||
| IMcpServer thisServer, | ||
| [Description("The prompt to send to the LLM")] string prompt, | ||
| [Description("Maximum number of tokens to generate")] int maxTokens, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, "sampleLLM", maxTokens); | ||
| var sampleResult = await _server.RequestSamplingAsync(samplingParams, cancellationToken); | ||
| ChatMessage[] messages = | ||
| [ | ||
| new(ChatRole.System, "You are a helpful test server."), | ||
| new(ChatRole.User, prompt), | ||
| ]; | ||
|  | ||
| return $"LLM sampling result: {sampleResult.Content.Text}"; | ||
| } | ||
|  | ||
| private static CreateMessageRequestParams CreateRequestSamplingParams(string context, string uri, int maxTokens = 100) | ||
| { | ||
| return new CreateMessageRequestParams() | ||
| ChatOptions options = new() | ||
| { | ||
| Messages = [new SamplingMessage() | ||
| { | ||
| Role = Role.User, | ||
| Content = new Content() | ||
| { | ||
| Type = "text", | ||
| Text = $"Resource {uri} context: {context}" | ||
| } | ||
| }], | ||
| SystemPrompt = "You are a helpful test server.", | ||
| MaxTokens = maxTokens, | ||
| MaxOutputTokens = maxTokens, | ||
| Temperature = 0.7f, | ||
| IncludeContext = ContextInclusion.ThisServer | ||
| }; | ||
|  | ||
| var samplingResponse = await thisServer.AsSamplingChatClient().GetResponseAsync(messages, options, cancellationToken); | ||
|  | ||
| return $"LLM sampling result: {samplingResponse}"; | ||
| } | ||
| } | 
  
    
      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
    
  
  
    
              
  
    
      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
    
  
  
    
              
  
    
      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,104 @@ | ||
| using Microsoft.Extensions.AI; | ||
| using ModelContextProtocol.Protocol.Types; | ||
| using ModelContextProtocol.Utils; | ||
| using System.Runtime.InteropServices; | ||
|  | ||
| namespace ModelContextProtocol; | ||
|  | ||
| /// <summary>Provides helpers for conversions related to <see cref="AIContent"/>.</summary> | ||
| public static class AIContentExtensions | ||
| { | ||
| /// <summary>Creates a <see cref="ChatMessage"/> from a <see cref="PromptMessage"/>.</summary> | ||
| /// <param name="promptMessage">The message to convert.</param> | ||
| /// <returns>The created <see cref="ChatMessage"/>.</returns> | ||
| public static ChatMessage ToChatMessage(this PromptMessage promptMessage) | ||
| { | ||
| Throw.IfNull(promptMessage); | ||
|  | ||
| return new() | ||
| { | ||
| RawRepresentation = promptMessage, | ||
| Role = promptMessage.Role == Role.User ? ChatRole.User : ChatRole.Assistant, | ||
| Contents = [ToAIContent(promptMessage.Content)] | ||
| }; | ||
| } | ||
|  | ||
| /// <summary>Creates a new <see cref="AIContent"/> from the content of a <see cref="Content"/>.</summary> | ||
| /// <param name="content">The <see cref="Content"/> to convert.</param> | ||
| /// <returns>The created <see cref="AIContent"/>.</returns> | ||
| public static AIContent ToAIContent(this Content content) | ||
| { | ||
| Throw.IfNull(content); | ||
|  | ||
| AIContent ac; | ||
| if (content is { Type: "image", MimeType: not null, Data: not null }) | ||
| { | ||
| ac = new DataContent(Convert.FromBase64String(content.Data), content.MimeType); | ||
| } | ||
| else if (content is { Type: "resource" } && content.Resource is { } resourceContents) | ||
| { | ||
| ac = resourceContents.Blob is not null && resourceContents.MimeType is not null ? | ||
| new DataContent(Convert.FromBase64String(resourceContents.Blob), resourceContents.MimeType) : | ||
| new TextContent(resourceContents.Text); | ||
|  | ||
| (ac.AdditionalProperties ??= [])["uri"] = resourceContents.Uri; | ||
|         
                  stephentoub marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| } | ||
| else | ||
| { | ||
| ac = new TextContent(content.Text); | ||
| } | ||
|  | ||
| ac.RawRepresentation = content; | ||
|  | ||
| return ac; | ||
| } | ||
|  | ||
| /// <summary>Creates a new <see cref="AIContent"/> from the content of a <see cref="ResourceContents"/>.</summary> | ||
| /// <param name="content">The <see cref="ResourceContents"/> to convert.</param> | ||
| /// <returns>The created <see cref="AIContent"/>.</returns> | ||
| public static AIContent ToAIContent(this ResourceContents content) | ||
| { | ||
| Throw.IfNull(content); | ||
|  | ||
| AIContent ac = content.Blob is not null && content.MimeType is not null ? | ||
| new DataContent(Convert.FromBase64String(content.Blob), content.MimeType) : | ||
| new TextContent(content.Text); | ||
|  | ||
| (ac.AdditionalProperties ??= [])["uri"] = content.Uri; | ||
| ac.RawRepresentation = content; | ||
|  | ||
| return ac; | ||
| } | ||
|  | ||
| /// <summary>Creates a list of <see cref="AIContent"/> from a sequence of <see cref="Content"/>.</summary> | ||
| /// <param name="contents">The <see cref="Content"/> instances to convert.</param> | ||
| /// <returns>The created <see cref="AIContent"/> instances.</returns> | ||
| public static IList<AIContent> ToAIContents(this IEnumerable<Content> contents) | ||
| { | ||
| Throw.IfNull(contents); | ||
|  | ||
| return contents.Select(ToAIContent).ToList(); | ||
| } | ||
|  | ||
| /// <summary>Creates a list of <see cref="AIContent"/> from a sequence of <see cref="ResourceContents"/>.</summary> | ||
| /// <param name="contents">The <see cref="ResourceContents"/> instances to convert.</param> | ||
| /// <returns>The created <see cref="AIContent"/> instances.</returns> | ||
| public static IList<AIContent> ToAIContents(this IEnumerable<ResourceContents> contents) | ||
| { | ||
| Throw.IfNull(contents); | ||
|  | ||
| return contents.Select(ToAIContent).ToList(); | ||
| } | ||
|  | ||
| /// <summary>Extracts the data from a <see cref="DataContent"/> as a Base64 string.</summary> | ||
| internal static string GetBase64Data(this DataContent dataContent) | ||
| { | ||
| #if NET | ||
| return Convert.ToBase64String(dataContent.Data.Span); | ||
| #else | ||
| return MemoryMarshal.TryGetArray(dataContent.Data, out ArraySegment<byte> segment) ? | ||
| Convert.ToBase64String(segment.Array!, segment.Offset, segment.Count) : | ||
| Convert.ToBase64String(dataContent.Data.ToArray()); | ||
| #endif | ||
| } | ||
| } | ||
      
      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.