.net 网站开发权限设计品牌商标

张小明 2026/1/13 8:39:58
.net 网站开发权限设计,品牌商标,兰州做网站哪家好,关键词优化多少钱Model Context Protocol (MCP) 是一个标准化协议#xff0c;让 AI 客户端#xff08;如 Claude、ChatGPT 等#xff09;能够通过统一的接口调用你的 API。本文将详细介绍如何在 ASP.NET Core WebApi 项目中集成 MCP 支持#xff0c;实现 AI 与你的服务无缝对接。什么是 MCP…Model Context Protocol (MCP) 是一个标准化协议让 AI 客户端如 Claude、ChatGPT 等能够通过统一的接口调用你的 API。本文将详细介绍如何在 ASP.NET Core WebApi 项目中集成 MCP 支持实现 AI 与你的服务无缝对接。什么是 MCPMCPModel Context Protocol是一个开放协议旨在标准化 AI 应用与外部工具、数据源之间的通信方式。通过 MCP你的 API 可以被 AI 助手自动发现和调用提供标准化的工具描述和参数定义支持多种传输模式HTTP、Stdio实现安全的认证和授权核心特性本项目实现了以下功能✅ 使用官方 ModelContextProtocol.AspNetCore SDK✅ 通过 [McpServerTool] 特性快速定义工具✅ 自动参数绑定和 JSON Schema 生成✅ 支持 HTTP 和 Stdio 双传输模式✅ 基于 Token 的认证和授权✅ 与现有 WebApi 完美共存快速开始第一步安装 NuGet 包dotnet add package ModelContextProtocol.AspNetCore --version 0.4.0-preview.3第二步配置 MCP 服务在 Program.cs 中添加 MCP 配置using ModelContextProtocol.Server;var builder WebApplication.CreateBuilder(args);builder.Services.AddControllers();// 添加 MCP 服务器支持 HTTP 和 Stdio 双模式builder.Services.AddMcpServer(options {options.ServerInfo new ModelContextProtocol.Protocol.Implementation{Name Weather API,Version 1.0.0};}).WithHttpTransport() // HTTP 模式用于 Web 客户端.WithStdioServerTransport() // Stdio 模式用于 Kiro IDE 等本地工具.WithToolsFromAssembly();var app builder.Build();// 添加认证中间件可选app.UseMiddlewareMcpAuthenticationMiddleware();app.UseAuthorization();app.MapControllers();// 映射 MCP 端点app.MapMcp(/mcp);app.Run();第三步定义 MCP 工具创建 Tools/WeatherTools.csusing System.ComponentModel;using ModelContextProtocol.Server;[McpServerToolType]public static class WeatherTools{[McpServerTool][Description(Get weather forecast for the next 5 days)]public static IEnumerableWeatherForecast GetWeatherForecast(){var rng new Random();return Enumerable.Range(1, 5).Select(index new WeatherForecast{Date DateOnly.FromDateTime(DateTime.Now.AddDays(index)),TemperatureC rng.Next(-20, 55),Summary Summaries[rng.Next(Summaries.Length)]}).ToArray();}[McpServerTool][Description(Get current weather for a specific city)]public static WeatherForecast GetWeatherByCity([Description(The name of the city)] string city){var rng new Random();return new WeatherForecast{Date DateOnly.FromDateTime(DateTime.Now),TemperatureC rng.Next(-20, 55),Summary $Weather in {city}: {Summaries[rng.Next(Summaries.Length)]}};}private static readonly string[] Summaries new[]{Freezing, Bracing, Chilly, Cool, Mild,Warm, Balmy, Hot, Sweltering, Scorching};}第四步配置认证可选在 appsettings.json 中配置{McpAuth: {Enabled: true,ValidTokens: [your-secret-token-here]}}开发环境可以禁用认证appsettings.Development.json{McpAuth: {Enabled: false}}第五步运行和测试dotnet run应用启动后可以访问Swagger UI: http://localhost:5000/swaggerWebApi: http://localhost:5000/weatherforecastMCP 端点: http://localhost:5000/mcp传输模式详解HTTP 模式适用于 Web 应用、Claude Desktop、远程访问等场景。测试示例# 列出所有工具curl -X POST http://localhost:5000/mcp \-H Content-Type: application/json \-d {jsonrpc:2.0,id:1,method:tools/list}# 调用工具curl -X POST http://localhost:5000/mcp \-H Authorization: Bearer your-secret-token-here \-H Content-Type: application/json \-d {jsonrpc:2.0,id:2,method:tools/call,params:{name:GetWeatherForecast,arguments:{}}}Claude Desktop 配置编辑配置文件Windows: %APPDATA%\Claude\claude_desktop_config.json{mcpServers: {weather-api: {url: http://localhost:5000/mcp,headers: {Authorization: Bearer your-secret-token-here}}}}Stdio 模式适用于 Kiro IDE、本地命令行工具等场景无需网络端口。Kiro IDE 配置编辑 .kiro/settings/mcp.json{mcpServers: {weather-api: {command: dotnet,args: [run, --project, path/to/NetCoreApiMcpDemo.csproj],env: {ASPNETCORE_ENVIRONMENT: Development}}}}模式对比特性 HTTP 模式 Stdio 模式传输方式 HTTP POST 标准输入/输出适用场景 Web 应用、远程访问 本地工具、IDE 集成认证 HTTP Header 环境变量/配置网络 需要网络端口 无需网络性能 网络开销 进程间通信更快认证和授权实现认证中间件创建 Middleware/McpAuthenticationMiddleware.cspublic class McpAuthenticationMiddleware{private readonly RequestDelegate _next;private readonly IConfiguration _configuration;private readonly ILoggerMcpAuthenticationMiddleware _logger;public McpAuthenticationMiddleware(RequestDelegate next,IConfiguration configuration,ILoggerMcpAuthenticationMiddleware logger){_next next;_configuration configuration;_logger logger;}public async Task InvokeAsync(HttpContext context){// 只对 MCP 端点进行认证if (!context.Request.Path.StartsWithSegments(/mcp)){await _next(context);return;}// 检查是否启用认证var authEnabled _configuration.GetValuebool(McpAuth:Enabled);if (!authEnabled){await _next(context);return;}// 验证 Tokenvar authHeader context.Request.Headers[Authorization].FirstOrDefault();if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith(Bearer )){context.Response.StatusCode 401;await context.Response.WriteAsJsonAsync(new { error Unauthorized });return;}var token authHeader.Substring(Bearer .Length).Trim();var validTokens _configuration.GetSection(McpAuth:ValidTokens).Getstring[]();if (validTokens null || !validTokens.Contains(token)){context.Response.StatusCode 401;await context.Response.WriteAsJsonAsync(new { error Invalid token });return;}await _next(context);}}安全最佳实践使用强 Token至少 32 字符的随机字符串定期轮换定期更换 Token使用 HTTPS生产环境必须使用 HTTPS环境隔离开发和生产使用不同的 Token日志安全不要在日志中记录完整 Token客户端集成示例C# 客户端using ModelContextProtocol;using ModelContextProtocol.Client;var transport new HttpClientTransport(new HttpClientTransportOptions{BaseUrl new Uri(http://localhost:5000/mcp),Headers new Dictionarystring, string{[Authorization] Bearer your-secret-token-here}});var client await McpClient.CreateAsync(transport);await client.InitializeAsync(new InitializeParams{ProtocolVersion 2025-06-18,ClientInfo new Implementation{Name MyApp,Version 1.0.0}});// 列出工具var tools await client.ListToolsAsync();// 调用工具var result await client.CallToolAsync(GetWeatherForecast,new Dictionarystring, object?());JavaScript/Vue 客户端script setupimport { ref } from vue;const weather ref();const MCP_URL http://localhost:5000/mcp;const TOKEN your-secret-token-here;const callMcp async (method, params {}) {const response await fetch(MCP_URL, {method: POST,headers: {Content-Type: application/json,Authorization: Bearer ${TOKEN},},body: JSON.stringify({jsonrpc: 2.0,id: Date.now(),method,params,}),});return response.json();};const getWeather async () {const data await callMcp(tools/call, {name: GetWeatherForecast,arguments: {},});weather.value data.result.content[0].text;};/scriptMCP Tools 最佳实践让 AI 更准确地使用你的工具是成功的关键。以下是经过实践验证的最佳实践。核心原则AI 通过以下信息决定是否使用你的工具工具名称 - 清晰、描述性Description - 详细的功能说明参数描述 - 明确的参数用途使用场景 - 何时应该使用这个工具1. 使用清晰的命名// ❌ 不好 - 名称模糊[McpServerTool]public static string Get() { }// ✅ 好 - 动词开头描述清晰[McpServerTool]public static string GetWeatherForecast() { }// ✅ 更好 - 包含具体信息[McpServerTool]public static string GetWeatherForecastForNextDays() { }命名建议使用动词开头Get, Search, Calculate, Compare, Analyze包含操作对象Weather, Temperature, Forecast避免缩写和简称使用 PascalCase2. 编写详细的 Description最重要这是最关键的部分AI 主要通过 Description 判断是否使用工具。// ❌ 不好 - 太简短[Description(Get weather)]// ⚠️ 一般 - 有基本信息但不够[Description(Get weather forecast for the next 5 days)]// ✅ 好 - 包含详细信息和使用场景[Description(Get detailed weather forecast for the next several days including temperature, weather conditions, and trends.Use this tool when users ask about:- Future weather (tomorrow, next week, upcoming days)- Weather predictions or forecasts- Planning activities based on weather- Temperature trendsExamples of user queries:- Whats the weather forecast for the next 5 days?- Will it rain this week?- Whats the temperature trend?)]Description 应该包含功能说明 - 工具做什么使用场景 - 何时使用Use this tool when...示例查询 - 用户可能的提问方式支持的功能 - 特殊能力或限制3. 详细的参数描述
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

员工支付做网站的费用分录九度网站建设

语言障碍康复:失语症患者语音重建训练工具 在神经康复科的诊室里,一位中风后失语症患者正盯着平板屏幕上的文字,嘴唇微动却发不出完整音节。医生轻声鼓励:“试着跟读这句话。”——但回应他的,是一段由标准电子音合成的…

张小明 2026/1/12 20:53:28 网站建设

西安网站建设设计的好公司微信 host 微网站模版

Polars数据处理的5个核心技巧:让数据分析更高效简单 【免费下载链接】polars 由 Rust 编写的多线程、向量化查询引擎驱动的数据帧技术 项目地址: https://gitcode.com/GitHub_Trending/po/polars 在现代数据科学和工程中,高效的数据处理工具至关重…

张小明 2026/1/12 20:53:27 网站建设

云南哪里有给做网站的wordpress数据库容量

从零开始:J-Link驱动安装实战与Modbus通信调试全链路打通 你有没有遇到过这种情况?新买的J-Link仿真器插上电脑,设备管理器里却显示黄色感叹号;或者代码写好了,烧不进去、连不上芯片,反复重启、换线、重装系…

张小明 2026/1/12 20:53:25 网站建设

网站建设策划包括哪些内容wordpress站点统计

还在为海量文献管理头疼吗?zotero-style插件让你的Zotero瞬间升级为智能文献助手!无论你是科研新手还是资深学者,这篇指南都能帮你快速上手。 【免费下载链接】zotero-style zotero-style - 一个 Zotero 插件,提供了一系列功能来增…

张小明 2026/1/12 20:53:23 网站建设

网站全屏轮播怎么做深圳seo优化外包公司

第一章:Java抗量子加密性能优化概述随着量子计算技术的快速发展,传统公钥加密体系面临前所未有的安全威胁。抗量子加密(Post-Quantum Cryptography, PQC)算法作为应对未来量子攻击的核心技术,正逐步被引入主流开发平台…

张小明 2026/1/12 22:56:56 网站建设

群晖nas可以做网站吗新手学做网站书

Python PDF转Excel自动化处理终极指南 【免费下载链接】Python_pdf2Excel提取PDF内容写入Excel Python_pdf2Excel是一个高效的开源工具,专为自动化处理大量PDF文件并将其关键数据提取至Excel表格而设计。该项目通过Python脚本实现,能够快速准确地读取PDF…

张小明 2026/1/12 22:56:54 网站建设