Skip to content

Commit 9f0eb04

Browse files
committed
refactor(demo): update calculator demo to use functional tool
1 parent 798d5d0 commit 9f0eb04

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/ModelContextProtocol.NET.Demo.Calculator/ModelContextProtocol.NET.Demo.Calculator.csproj

+3
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
<PackageReference Include="Serilog" />
1313
<PackageReference Include="Serilog.Extensions.Logging" />
1414
<PackageReference Include="Serilog.Sinks.File" />
15+
<ProjectReference
16+
Include="..\ModelContextProtocol.NET.Core\ModelContextProtocol.NET.Core.csproj"
17+
/>
1518
<ProjectReference
1619
Include="..\ModelContextProtocol.NET.Server\ModelContextProtocol.NET.Server.csproj"
1720
/>

src/ModelContextProtocol.NET.Demo.Calculator/Program.cs

+41-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
1-
using System.Threading.Tasks;
1+
using System;
2+
using System.Threading;
3+
using System.Threading.Tasks;
24
using Microsoft.Extensions.DependencyInjection;
35
using Microsoft.Extensions.Logging;
6+
using ModelContextProtocol.NET.Core.Models.Protocol.Client.Responses;
47
using ModelContextProtocol.NET.Core.Models.Protocol.Common;
8+
using ModelContextProtocol.NET.Core.Models.Protocol.Shared.Content;
59
using ModelContextProtocol.NET.Demo.Calculator.Handlers;
610
using ModelContextProtocol.NET.Server.Builder;
711
using Serilog;
@@ -25,7 +29,42 @@
2529
builder.SetMinimumLevel(LogLevel.Trace);
2630
})
2731
)
28-
.ConfigureTools(tools => tools.AddHandler<CalculatorToolHandler>())
32+
.ConfigureTools(tools =>
33+
tools
34+
//.AddHandler<CalculatorToolHandler>()
35+
.AddFunction(
36+
name: "Calculator_function_flavor",
37+
description: "Still performs basic arithmetic operations, but implemented in functional style",
38+
parameterTypeInfo: CalculatorParametersJsonContext.Default.CalculatorParameters,
39+
handler: (CalculatorParameters parameters, CancellationToken ct) =>
40+
Task.FromResult(
41+
new CallToolResult
42+
{
43+
Content = (TextContent)
44+
(
45+
(double)(
46+
parameters.Operation switch
47+
{
48+
CalculatorOperation.Add => parameters.A + parameters.B,
49+
CalculatorOperation.Subtract => parameters.A - parameters.B,
50+
CalculatorOperation.Multiply => parameters.A * parameters.B,
51+
CalculatorOperation.Divide when parameters.B != 0
52+
=> parameters.A / parameters.B,
53+
CalculatorOperation.Divide
54+
=> throw new DivideByZeroException(
55+
"Cannot divide by zero"
56+
),
57+
_
58+
=> throw new ArgumentException(
59+
$"Unknown operation: {parameters.Operation}"
60+
),
61+
}
62+
)
63+
).ToString()
64+
}
65+
)
66+
)
67+
)
2968
.Build();
3069

3170
try

0 commit comments

Comments
 (0)