找回密码
 立即注册
首页 业界区 业界 最新DeepSeek-V3驱动的MCP与SemanticKernel实战教程 - ...

最新DeepSeek-V3驱动的MCP与SemanticKernel实战教程 - 打造智能应用的终极指南

镝赋洧 2025-6-2 22:46:13
简单介绍

在进入教程之前我们可以先对MCP进行一个大概的了解,MCP是什么?为什么要用MCP?MCP和Function Calling有什么区别?
MCP是什么?

Model Context Protocol (MCP) 是一个开放协议,它使 LLM 应用与外部数据源和工具之间的无缝集成成为可能。无论你是构建 AI 驱动的 IDE、改善 chat 交互,还是构建自定义的 AI 工作流,MCP 提供了一种标准化的方式,将 LLM 与它们所需的上下文连接起来。
1.png


  • MCP Hosts: 想要通过MCP访问数据的程序,如Claude Desktop、ide或AI工具
  • MCP Clients: 与服务器保持1:1连接的协议客户端
  • MCP Servers: 轻量级程序,每个程序都通过标准化的模型上下文协议公开特定的功能
  • Local Data Sources: MCP服务器可以安全访问的计算机文件、数据库和服务
  • Remote Services: MCP服务器可以连接的internet上可用的外部系统(例如通过api)
为什么要用MCP?


  • 扩展LLM的能力:让模型能够访问最新数据、专有信息和本地资源
  • 数据私密性和安全性:数据可以保留在本地或受控环境中,减少敏感信息共享的风险
  • 工具集成:使LLM能够调用和控制外部工具,扩展其功能范围
  • 减少幻觉:通过提供准确的上下文信息,降低模型生成虚假内容的可能性
  • 标准化:为开发者提供一致的接口,简化集成过程
  • 可扩展性:支持从简单用例到复杂企业级应用的多种场景
  • 跨语言的能力:通过标准的MCP协议我们可以使用不同语言提供的MCPServer的能力
MCP和Function Calling有什么区别?

我听过最多人问的就是MCP和Function Calling有什么区别?
特性MCPFunction Calling基础关系基于Function Calling构建并扩展作为MCP的基础技术设计范围更广泛的协议,处理上下文获取和工具使用主要聚焦于调用特定函数架构客户端-服务器架构,支持分布式系统通常是API参数的直接定义和调用数据处理可以处理大型数据集和复杂上下文主要处理结构化的函数参数和返回值上下文管理专门设计用于管理和提供上下文上下文管理不是核心功能标准化程度开放协议,旨在跨不同系统和模型标准化实现方式因平台而异,标准化程度较低应用场景适用于需要复杂上下文和工具集成的场景适用于调用预定义函数执行特定任务简而言之,MCP(Model Context Protocol)是在Function Calling基础上发展而来的更全面的协议,它不仅保留了Function Calling的核心功能,还扩展了上下文获取和管理能力,为LLM提供更丰富、更标准化的环境交互能力。
开始MCPClient基础教程

前提条件,您需要先将上一个教程的MCPServer跑起来一会才能进行当前步骤,因为MCPClient是需要MCPServer提供Tools,下面我默认您已经运行了MCPServer,
然后可以访问 https://account.coreshub.cn/signup?invite=ZmpMQlZxYVU= 获取免费的DeepSeek-V3模型和白嫖GPU服务器,通过上面连接注册以后访问
https://console.coreshub.cn/xb3/maas/global-keys/ 地址获取到APIKey
然后记住我们的APIKey,开始下面的旅途

  • 创建属于您的MCPClient程序
创建一个McpClient的控制台项目
2.png

给项目添加依赖包
  1.     <ItemGroup>
  2.         <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.3" />
  3.         <PackageReference Include="Microsoft.SemanticKernel" Version="1.44.0" />
  4.         <PackageReference Include="ModelContextProtocol" Version="0.1.0-preview.4" />
  5.     </ItemGroup>
复制代码
下面的教程我们将使用Microsoft.SemanticKernel开发,然后依赖ModelContextProtocol官方的包,然后我们需要用到Microsoft.Extensions.Hosting
开始我们的代码开发

  • 扩展SemanticKernel的MCPClient
由于SemnaticKernel默认是不能直接使用MCP的功能,那么我们需要先对它进行扩展
创建几个基础类
JsonSchema.cs
  1. /// <summary>
  2. /// Represents a JSON schema for a tool's input arguments.
  3. /// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/2024-11-05/schema.json">See the schema for details</see>
  4. /// </summary>
  5. internal class JsonSchema
  6. {
  7.     /// <summary>
  8.     /// The type of the schema, should be "object".
  9.     /// </summary>
  10.     [JsonPropertyName("type")]
  11.     public string Type { get; set; } = "object";
  12.     /// <summary>
  13.     /// Map of property names to property definitions.
  14.     /// </summary>
  15.     [JsonPropertyName("properties")]
  16.     public Dictionary<string, JsonSchemaProperty>? Properties { get; set; }
  17.     /// <summary>
  18.     /// List of required property names.
  19.     /// </summary>
  20.     [JsonPropertyName("required")]
  21.     public List<string>? Required { get; set; }
  22. }
  23. JsonSchemaProperty.cs
  24. /// <summary>
  25. /// Represents a property in a JSON schema.
  26. /// <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/2024-11-05/schema.json">See the schema for details</see>
  27. /// </summary>
  28. internal class JsonSchemaProperty
  29. {
  30.     /// <summary>
  31.     /// The type of the property. Should be a JSON Schema type and is required.
  32.     /// </summary>
  33.     [JsonPropertyName("type")]
  34.     public string Type { get; set; } = string.Empty;
  35.     /// <summary>
  36.     /// A human-readable description of the property.
  37.     /// </summary>
  38.     [JsonPropertyName("description")]
  39.     public string? Description { get; set; } = string.Empty;
  40. }
复制代码
接下来创建MCP的扩展类,用于将MCPFunction进行转换成SemanticKernel Function
ModelContextProtocolExtensions.cs
  1. /// <summary>
  2. /// Extension methods for ModelContextProtocol
  3. /// </summary>
  4. internal static class ModelContextProtocolExtensions
  5. {
  6.     /// <summary>
  7.     /// Map the tools exposed on this <see cref="IMcpClient"/> to a collection of <see cref="KernelFunction"/> instances for use with the Semantic Kernel.
  8.     /// <param name="mcpClient">The <see cref="IMcpClient"/>.</param>
  9.     /// <param name="cancellationToken">The optional <see cref="CancellationToken"/>.</param>
  10.     /// </summary>
  11.     internal static async Task<IReadOnlyList<KernelFunction>> MapToFunctionsAsync(this IMcpClient mcpClient, CancellationToken cancellationToken = default)
  12.     {
  13.         var functions = new List<KernelFunction>();
  14.         foreach (var tool in await mcpClient.ListToolsAsync(cancellationToken).ConfigureAwait(false))
  15.         {
  16.             functions.Add(tool.ToKernelFunction(mcpClient, cancellationToken));
  17.         }
  18.         return functions;
  19.     }
  20.     private static KernelFunction ToKernelFunction(this McpClientTool tool, IMcpClient mcpClient, CancellationToken cancellationToken)
  21.     {
  22.         async Task<string> InvokeToolAsync(Kernel kernel, KernelFunction function, KernelArguments arguments, CancellationToken ct)
  23.         {
  24.             try
  25.             {
  26.                 // Convert arguments to dictionary format expected by ModelContextProtocol
  27.                 Dictionary<string, object?> mcpArguments = [];
  28.                 foreach (var arg in arguments)
  29.                 {
  30.                     if (arg.Value is not null)
  31.                     {
  32.                         mcpArguments[arg.Key] = function.ToArgumentValue(arg.Key, arg.Value);
  33.                     }
  34.                 }
  35.                 // Call the tool through ModelContextProtocol
  36.                 var result = await mcpClient.CallToolAsync(
  37.                     tool.Name,
  38.                     mcpArguments.AsReadOnly(),
  39.                     cancellationToken: ct
  40.                 ).ConfigureAwait(false);
  41.                 // Extract the text content from the result
  42.                 return string.Join("\n", result.Content
  43.                     .Where(c => c.Type == "text")
  44.                     .Select(c => c.Text));
  45.             }
  46.             catch (Exception ex)
  47.             {
  48.                 await Console.Error.WriteLineAsync($"Error invoking tool '{tool.Name}': {ex.Message}");
  49.                 // Rethrowing to allow the kernel to handle the exception
  50.                 throw;
  51.             }
  52.         }
  53.         return KernelFunctionFactory.CreateFromMethod(
  54.             method: InvokeToolAsync,
  55.             functionName: tool.Name,
  56.             description: tool.Description,
  57.             parameters: tool.ToParameters(),
  58.             returnParameter: ToReturnParameter()
  59.         );
  60.     }
  61.     private static object ToArgumentValue(this KernelFunction function, string name, object value)
  62.     {
  63.         var parameterType = function.Metadata.Parameters.FirstOrDefault(p => p.Name == name)?.ParameterType;
  64.         if (parameterType == null)
  65.         {
  66.             return value;
  67.         }
  68.         if (Nullable.GetUnderlyingType(parameterType) == typeof(int))
  69.         {
  70.             return Convert.ToInt32(value);
  71.         }
  72.         if (Nullable.GetUnderlyingType(parameterType) == typeof(double))
  73.         {
  74.             return Convert.ToDouble(value);
  75.         }
  76.         if (Nullable.GetUnderlyingType(parameterType) == typeof(bool))
  77.         {
  78.             return Convert.ToBoolean(value);
  79.         }
  80.         if (parameterType == typeof(List<string>))
  81.         {
  82.             return (value as IEnumerable<object>)?.ToList() ?? value;
  83.         }
  84.         if (parameterType == typeof(Dictionary<string, object>))
  85.         {
  86.             return (value as Dictionary<string, object>)?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value) ?? value;
  87.         }
  88.         return value;
  89.     }
  90.     private static List<KernelParameterMetadata>? ToParameters(this McpClientTool tool)
  91.     {
  92.         var inputSchema = JsonSerializer.Deserialize<JsonSchema>(tool.JsonSchema.GetRawText());
  93.         var properties = inputSchema?.Properties;
  94.         if (properties == null)
  95.         {
  96.             return null;
  97.         }
  98.         HashSet<string> requiredProperties = [.. inputSchema!.Required ?? []];
  99.         return properties.Select(kvp =>
  100.             new KernelParameterMetadata(kvp.Key)
  101.             {
  102.                 Description = kvp.Value.Description,
  103.                 ParameterType = ConvertParameterDataType(kvp.Value, requiredProperties.Contains(kvp.Key)),
  104.                 IsRequired = requiredProperties.Contains(kvp.Key)
  105.             }).ToList();
  106.     }
  107.     private static KernelReturnParameterMetadata ToReturnParameter()
  108.     {
  109.         return new KernelReturnParameterMetadata
  110.         {
  111.             ParameterType = typeof(string),
  112.         };
  113.     }
  114.     private static Type ConvertParameterDataType(JsonSchemaProperty property, bool required)
  115.     {
  116.         var type = property.Type switch
  117.         {
  118.             "string" => typeof(string),
  119.             "integer" => typeof(int),
  120.             "number" => typeof(double),
  121.             "boolean" => typeof(bool),
  122.             "array" => typeof(List<string>),
  123.             "object" => typeof(Dictionary<string, object>),
  124.             _ => typeof(object)
  125.         };
  126.         return !required && type.IsValueType ? typeof(Nullable<>).MakeGenericType(type) : type;
  127.     }
  128. }
复制代码
然后创建SemanticKernel的扩展,对SKFunction进行扩展
KernelExtensions.cs
  1. /// <summary>
  2. /// Extension methods for KernelPlugin
  3. /// </summary>
  4. public static class KernelExtensions
  5. {
  6.     private static readonly ConcurrentDictionary<string, IKernelBuilderPlugins> SseMap = new();
  7.     /// <summary>
  8.     /// Creates a Model Content Protocol plugin from an SSE server that contains the specified MCP functions and adds it into the plugin collection.
  9.     /// </summary>
  10.     /// <param name="endpoint"></param>
  11.     /// <param name="serverName"></param>
  12.     /// <param name="cancellationToken">The optional <see cref="CancellationToken"/>.</param>
  13.     /// <param name="plugins"></param>
  14.     /// <returns>A <see cref="KernelPlugin"/> containing the functions.</returns>
  15.     public static async Task<IKernelBuilderPlugins> AddMcpFunctionsFromSseServerAsync(this IKernelBuilderPlugins plugins,
  16.         string endpoint, string serverName, CancellationToken cancellationToken = default)
  17.     {
  18.         var key = ToSafePluginName(serverName);
  19.         if (SseMap.TryGetValue(key, out var sseKernelPlugin))
  20.         {
  21.             return sseKernelPlugin;
  22.         }
  23.         var mcpClient = await GetClientAsync(serverName, endpoint, null, null, cancellationToken).ConfigureAwait(false);
  24.         var functions = await mcpClient.MapToFunctionsAsync(cancellationToken: cancellationToken).ConfigureAwait(false);
  25.         cancellationToken.Register(() => mcpClient.DisposeAsync().ConfigureAwait(false).GetAwaiter().GetResult());
  26.         sseKernelPlugin = plugins.AddFromFunctions(key, functions);
  27.         return SseMap[key] = sseKernelPlugin;
  28.     }
  29.     private static async Task<IMcpClient> GetClientAsync(string serverName, string? endpoint,
  30.         Dictionary<string, string>? transportOptions, ILoggerFactory? loggerFactory,
  31.         CancellationToken cancellationToken)
  32.     {
  33.         var transportType = !string.IsNullOrEmpty(endpoint) ? TransportTypes.Sse : TransportTypes.StdIo;
  34.         McpClientOptions options = new()
  35.         {
  36.             ClientInfo = new()
  37.             {
  38.                 Name = $"{serverName} {transportType}Client",
  39.                 Version = "1.0.0"
  40.             }
  41.         };
  42.         var config = new McpServerConfig
  43.         {
  44.             Id = serverName.ToLowerInvariant(),
  45.             Name = serverName,
  46.             Location = endpoint,
  47.             TransportType = transportType,
  48.             TransportOptions = transportOptions
  49.         };
  50.         return await McpClientFactory.CreateAsync(config, options,
  51.             loggerFactory: loggerFactory ?? NullLoggerFactory.Instance, cancellationToken: cancellationToken);
  52.     }
  53.     // A plugin name can contain only ASCII letters, digits, and underscores.
  54.     private static string ToSafePluginName(string serverName)
  55.     {
  56.         return Regex.Replace(serverName, @"[^\w]", "_");
  57.     }
  58. }
复制代码

  • 实现连接MCPServer的Tools
现在我们就可以实现核心的代码了,打开我们的Program.cs
  1. using McpClient;
  2. using Microsoft.SemanticKernel;
  3. using Microsoft.SemanticKernel.ChatCompletion;
  4. using Microsoft.SemanticKernel.Connectors.OpenAI;
  5. using ChatMessageContent = Microsoft.SemanticKernel.ChatMessageContent;
  6. #pragma warning disable SKEXP0010
  7. var builder = Host.CreateEmptyApplicationBuilder(settings: null);
  8. builder.Configuration
  9.     .AddEnvironmentVariables()
  10.     .AddUserSecrets<Program>();
  11. var kernelBuilder = builder.Services.AddKernel()
  12.     .AddOpenAIChatCompletion("DeepSeek-V3", new Uri("https://openapi.coreshub.cn/v1"), "您使用的https://openapi.coreshub.cn/v1平台的APIKey");
  13. await kernelBuilder.Plugins.AddMcpFunctionsFromSseServerAsync("http://您的MCPServerip:端口/sse", "token");
  14. Console.ForegroundColor = ConsoleColor.Green;
  15. Console.WriteLine("MCP Client Started!");
  16. Console.ResetColor();
  17. var app = builder.Build();
  18. var kernel = app.Services.GetService<Kernel>();
  19. var chatCompletion = app.Services.GetService<IChatCompletionService>();
  20. PromptForInput();
  21. while (Console.ReadLine() is string query && !"exit".Equals(query, StringComparison.OrdinalIgnoreCase))
  22. {
  23.     if (string.IsNullOrWhiteSpace(query))
  24.     {
  25.         PromptForInput();
  26.         continue;
  27.     }
  28.     var history = new ChatHistory
  29.     {
  30.         new ChatMessageContent(AuthorRole.System, "下面如果需要计算俩个数的和,请使用我提供的工具。"),
  31.         new ChatMessageContent(AuthorRole.User, query)
  32.     };
  33.     await foreach (var message in chatCompletion?.GetStreamingChatMessageContentsAsync(history,
  34.                        new OpenAIPromptExecutionSettings()
  35.                        {
  36.                            ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions,
  37.                        }, kernel))
  38.     {
  39.         Console.Write(message.Content);
  40.     }
  41.     Console.WriteLine();
  42.     PromptForInput();
  43. }
  44. static void PromptForInput()
  45. {
  46.     Console.WriteLine("Enter a command (or 'exit' to quit):");
  47.     Console.ForegroundColor = ConsoleColor.Cyan;
  48.     Console.Write("> ");
  49.     Console.ResetColor();
  50. }
复制代码
然后开始启动我们的MCPClient,在此之前需要先修改代码中的参数改成自己的,然后先启动MCPServer以后,在启动我们的MCPClient
执行以后提问1+1=?然后会得到一下的结果
3.png

在执行之前我们可以先在MCPServer中的算法函数Debug,这样就可以清晰的看到进入的流程了
4.png

通过上面的案例,恭喜您您已经熟练的掌握了MCPServer+MCPClient+SemanticKernel的入门级教程

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册