更新项目

main
bicijinlian 7 days ago
parent fd29fa92b3
commit b9c03a33af

@ -1,14 +1,33 @@
namespace McpStudy.McpClient;
using Azure.Core.Pipeline;
namespace McpStudy.McpClient;
internal class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("调用MCP服务示例");
await CallStdioAsync();
var HttpClient = new HttpClient(new SocketsHttpHandler
{
})
{
BaseAddress = new Uri("http://localhost:5000/"),
Timeout = TimeSpan.FromSeconds(10),
};
//await CallStdioAsync();
//请务必在调用前启动SseServer服务
await RequestSseServerAsync();
//await RequestSseServerAsync();
await RequestStreamableHttpServerAsync();
await Task.CompletedTask;
}
@ -105,4 +124,25 @@ internal class Program
Console.WriteLine("调用 Studio 类型的MCP服务结束");
}
static async Task RequestStreamableHttpServerAsync()
{
Console.WriteLine($"开始调用 StreamableHttp 类型的MCP服务......{System.Environment.NewLine}");
var clientTransport = new SseClientTransport(
new SseClientTransportOptions
{
Name = "StudyMCPServer",
Endpoint = new Uri("http://localhost:5000"),
TransportMode = HttpTransportMode.StreamableHttp,
//AdditionalHeaders = new Dictionary<string, string>() { { "text/event-stream", "Content-Type" } }
}
);
var mcpClient = await McpClientFactory.CreateAsync(clientTransport);
var clientTools = await mcpClient.ListToolsAsync();
//return clientTools.Select(_ => _.AsKernelFunction());
Console.WriteLine("调用 Studio 类型的MCP服务结束");
}
}

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>

@ -0,0 +1,30 @@
namespace McpStudy.McpServerSSE.Tools
{
[McpServerToolType]
public class StringTools
{
[McpServerTool,DisplayName("GetTextLength"), Description("获取文本的长度")]
public static int GetTextLength(string text)
{
if (text == null)
{
return 0;
}
return text.Length;
}
[McpServerTool, DisplayName("ReverseText"), Description("反转文本内容:把给定文本反序")]
public static string ReverseText(string text)
{
if (text == null)
{
return "";
}
else
{
return string.Join("", text.Reverse());
}
}
}
}

@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;
namespace McpStudy.McpServerStreamableHttp.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

@ -0,0 +1,20 @@
global using System.Linq;
global using System.ComponentModel;
global using System.Net.Http.Headers;
global using System.IO.Pipelines;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using ModelContextProtocol;
global using ModelContextProtocol.Protocol;
global using ModelContextProtocol.Client;
global using ModelContextProtocol.Server;
global using ModelContextProtocol.SemanticKernel;
global using ModelContextProtocol.AspNetCore;
global using ModelContextProtocolServer;
global using ModelContextProtocolServer.Sse;
global using ModelContextProtocolServer.Stdio;

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>McpStudy.McpServerSSE</title>
</head>
<body>
<div style="text-align:center">
<h2>McpStudy.McpServerSSE 启动成功!</h2>
<h3>WebAPI参阅<a id="GoSwagger" href="#">Swagger 文档</a></h3>
<h3>MCP服务测试<a id="GoMCP" href="#">MCP服务页</a></h3>
</div>
<script type="text/javascript">
//相对根路径
var baseUrl = document.baseURI;
baseUrl = baseUrl.replace(/\/$/, "");
//设置Swagger地址
var swaggerUrl = baseUrl + "/swagger/index.html";
//设置连接地址
document.getElementById("GoSwagger").setAttribute("href", swaggerUrl);
//设置MCP服务器地址
var mcpServerUrl = baseUrl + "/sse";
//设置连接地址
document.getElementById("GoMCP").setAttribute("href", mcpServerUrl);
</script>
</body>
</html>

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.6" />
<PackageReference Include="ModelContextProtocol.AspNetCore" Version="0.3.0-preview.1" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\McpStudy.Core\McpStudy.Core.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="Index.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

@ -0,0 +1,6 @@
@McpStudy.McpServerStreamableHttp_HostAddress = http://localhost:5190
GET {{McpStudy.McpServerStreamableHttp_HostAddress}}/weatherforecast/
Accept: application/json
###

@ -0,0 +1,68 @@
namespace McpStudy.McpServerStreamableHttp;
public class Program
{
private static Pipe _input = new Pipe();
private static Pipe _output = new Pipe();
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services
.AddMcpServer(options =>
{
options.ServerInfo = new Implementation
{
Name = "StudyMCPServer",
Version = "1.0.0"
};
})
.WithHttpTransport(options => options.Stateless = true)
.WithToolsFromAssembly(typeof(McpStudy.Core.TimeTools).Assembly)
.WithToolsFromAssembly(typeof(Program).Assembly);
var app = builder.Build();
// Configure the HTTP request pipeline.
app.MapOpenApi();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/openapi/v1.json", "v1");
});
app.UseAuthorization();
app.MapControllers();
//配置启动地址(支持子站点):自定义中间件+重定向
//只能用中间件,不能用路由(app.Map): / 和 "" 会优先被app.MapMcp处理
app.Use(async (context, next) =>
{
if (context.Request.Path == "/" || context.Request.Path == "")
{
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync(Path.Combine(app.Environment.ContentRootPath, "index.html"));
}
else
{
await next();
}
});
app.MapMcp();
app.Run();
}
}

@ -0,0 +1,14 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5190",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

@ -0,0 +1,13 @@
namespace McpStudy.McpServerStreamableHttp
{
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

@ -18,6 +18,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docs", "Docs", "{208BA388-4
Docs\项目说明.md = Docs\项目说明.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "McpStudy.McpServerStreamableHttp", "McpStudy.McpServerStreamableHttp\McpStudy.McpServerStreamableHttp.csproj", "{7891DD2F-E046-4509-9A10-E5CDD93B8B45}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -44,6 +46,10 @@ Global
{34A4291B-BA36-491B-914D-674CF3806314}.Debug|Any CPU.Build.0 = Debug|Any CPU
{34A4291B-BA36-491B-914D-674CF3806314}.Release|Any CPU.ActiveCfg = Release|Any CPU
{34A4291B-BA36-491B-914D-674CF3806314}.Release|Any CPU.Build.0 = Release|Any CPU
{7891DD2F-E046-4509-9A10-E5CDD93B8B45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7891DD2F-E046-4509-9A10-E5CDD93B8B45}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7891DD2F-E046-4509-9A10-E5CDD93B8B45}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7891DD2F-E046-4509-9A10-E5CDD93B8B45}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Loading…
Cancel
Save