Add an in-memory transport sample (#664)

* Add an in-memory transport sample

* Rename sample
This commit is contained in:
Stephen Toub 2025-07-31 21:37:49 -04:00 • committed by GitHub
commit da86d52241
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 56 additions and 0 deletions

View file

@ -12,6 +12,7 @@
<Project Path="samples/AspNetCoreSseServer/AspNetCoreSseServer.csproj" />
<Project Path="samples/ChatWithTools/ChatWithTools.csproj" />
<Project Path="samples/EverythingServer/EverythingServer.csproj" />
<Project Path="samples/InMemoryTransport/InMemoryTransport.csproj" />
<Project Path="samples/ProtectedMCPClient/ProtectedMCPClient.csproj" />
<Project Path="samples/ProtectedMCPServer/ProtectedMCPServer.csproj" />
<Project Path="samples/QuickstartClient/QuickstartClient.csproj" />

View file

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,40 @@
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.IO.Pipelines;
Pipe clientToServerPipe = new(), serverToClientPipe = new();
// Create a server using a stream-based transport over an in-memory pipe.
await using IMcpServer server = McpServerFactory.Create(
new StreamServerTransport(clientToServerPipe.Reader.AsStream(), serverToClientPipe.Writer.AsStream()),
new McpServerOptions()
{
Capabilities = new()
{
Tools = new()
{
ToolCollection = [McpServerTool.Create((string arg) => $"Echo: {arg}", new() { Name = "Echo" })]
}
}
});
_ = server.RunAsync();
// Connect a client using a stream-based transport over the same in-memory pipe.
await using IMcpClient client = await McpClientFactory.CreateAsync(
new StreamClientTransport(clientToServerPipe.Writer.AsStream(), serverToClientPipe.Reader.AsStream()));
// List all tools.
var tools = await client.ListToolsAsync();
foreach (var tool in tools)
{
Console.WriteLine($"Tool Name: {tool.Name}");
}
Console.WriteLine();
// Invoke a tool.
var echo = tools.First(t => t.Name == "Echo");
Console.WriteLine(await echo.InvokeAsync(new()
{
["arg"] = "Hello World"
}));