Skip to content

Commit da86d52

Browse files
authored
Add an in-memory transport sample (#664)
* Add an in-memory transport sample * Rename sample
1 parent 650df63 commit da86d52

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

ModelContextProtocol.slnx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
<Project Path="samples/AspNetCoreSseServer/AspNetCoreSseServer.csproj" />
1313
<Project Path="samples/ChatWithTools/ChatWithTools.csproj" />
1414
<Project Path="samples/EverythingServer/EverythingServer.csproj" />
15+
<Project Path="samples/InMemoryTransport/InMemoryTransport.csproj" />
1516
<Project Path="samples/ProtectedMCPClient/ProtectedMCPClient.csproj" />
1617
<Project Path="samples/ProtectedMCPServer/ProtectedMCPServer.csproj" />
1718
<Project Path="samples/QuickstartClient/QuickstartClient.csproj" />
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
<PublishAot>true</PublishAot>
9+
</PropertyGroup>
10+
11+
<ItemGroup>
12+
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
13+
</ItemGroup>
14+
15+
</Project>

samples/InMemoryTransport/Program.cs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
using ModelContextProtocol.Client;
2+
using ModelContextProtocol.Protocol;
3+
using ModelContextProtocol.Server;
4+
using System.IO.Pipelines;
5+
6+
Pipe clientToServerPipe = new(), serverToClientPipe = new();
7+
8+
// Create a server using a stream-based transport over an in-memory pipe.
9+
await using IMcpServer server = McpServerFactory.Create(
10+
new StreamServerTransport(clientToServerPipe.Reader.AsStream(), serverToClientPipe.Writer.AsStream()),
11+
new McpServerOptions()
12+
{
13+
Capabilities = new()
14+
{
15+
Tools = new()
16+
{
17+
ToolCollection = [McpServerTool.Create((string arg) => $"Echo: {arg}", new() { Name = "Echo" })]
18+
}
19+
}
20+
});
21+
_ = server.RunAsync();
22+
23+
// Connect a client using a stream-based transport over the same in-memory pipe.
24+
await using IMcpClient client = await McpClientFactory.CreateAsync(
25+
new StreamClientTransport(clientToServerPipe.Writer.AsStream(), serverToClientPipe.Reader.AsStream()));
26+
27+
// List all tools.
28+
var tools = await client.ListToolsAsync();
29+
foreach (var tool in tools)
30+
{
31+
Console.WriteLine($"Tool Name: {tool.Name}");
32+
}
33+
Console.WriteLine();
34+
35+
// Invoke a tool.
36+
var echo = tools.First(t => t.Name == "Echo");
37+
Console.WriteLine(await echo.InvokeAsync(new()
38+
{
39+
["arg"] = "Hello World"
40+
}));

0 commit comments

Comments
 (0)