Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/ModelContextProtocol/Server/AIFunctionMcpServerTool.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ModelContextProtocol.Protocol;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
Expand All @@ -9,8 +11,10 @@
namespace ModelContextProtocol.Server;

/// <summary>Provides an <see cref="McpServerTool"/> that's implemented via an <see cref="AIFunction"/>.</summary>
internal sealed class AIFunctionMcpServerTool : McpServerTool
internal sealed partial class AIFunctionMcpServerTool : McpServerTool
{
private readonly ILogger _logger;

/// <summary>
/// Creates an <see cref="McpServerTool"/> instance for a method, specified via a <see cref="Delegate"/> instance.
/// </summary>
Expand Down Expand Up @@ -194,7 +198,7 @@ options.OpenWorld is not null ||
}
}

return new AIFunctionMcpServerTool(function, tool);
return new AIFunctionMcpServerTool(function, tool, options?.Services);
}

private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpServerToolCreateOptions? options)
Expand Down Expand Up @@ -239,10 +243,11 @@ private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpSe
internal AIFunction AIFunction { get; }

/// <summary>Initializes a new instance of the <see cref="McpServerTool"/> class.</summary>
private AIFunctionMcpServerTool(AIFunction function, Tool tool)
private AIFunctionMcpServerTool(AIFunction function, Tool tool, IServiceProvider? serviceProvider)
{
AIFunction = function;
ProtocolTool = tool;
_logger = serviceProvider?.GetService<ILoggerFactory>()?.CreateLogger<AIFunctionMcpServerTool>() ?? (ILogger)NullLogger.Instance;
}

/// <inheritdoc />
Expand Down Expand Up @@ -277,6 +282,8 @@ public override async ValueTask<CallToolResponse> InvokeAsync(
}
catch (Exception e) when (e is not OperationCanceledException)
{
ToolCallError(request.Params?.Name ?? string.Empty, e);

string errorMessage = e is McpException ?
$"An error occurred invoking '{request.Params?.Name}': {e.Message}" :
$"An error occurred invoking '{request.Params?.Name}'.";
Expand Down Expand Up @@ -359,4 +366,7 @@ private static CallToolResponse ConvertAIContentEnumerableToCallToolResponse(IEn
IsError = allErrorContent && hasAny
};
}

[LoggerMessage(Level = LogLevel.Error, Message = "\"{ToolName}\" threw an unhandled exception.")]
private partial void ToolCallError(string toolName, Exception exception);
}
41 changes: 41 additions & 0 deletions tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using Moq;
using System.Reflection;
using System.Text.Json;
Expand Down Expand Up @@ -381,6 +383,45 @@ public async Task SupportsSchemaCreateOptions()
);
}

[Fact]
public async Task ToolCallError_LogsErrorMessage()
{
// Arrange
var mockLoggerProvider = new MockLoggerProvider();
var loggerFactory = new LoggerFactory(new[] { mockLoggerProvider });
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(loggerFactory);
var serviceProvider = services.BuildServiceProvider();

var toolName = "tool-that-throws";
var exceptionMessage = "Test exception message";

McpServerTool tool = McpServerTool.Create(() =>
{
throw new InvalidOperationException(exceptionMessage);
}, new() { Name = toolName, Services = serviceProvider });

var mockServer = new Mock<IMcpServer>();
var request = new RequestContext<CallToolRequestParams>(mockServer.Object)
{
Params = new CallToolRequestParams() { Name = toolName },
Services = serviceProvider
};

// Act
var result = await tool.InvokeAsync(request, TestContext.Current.CancellationToken);

// Assert
Assert.True(result.IsError);
Assert.Single(result.Content);
Assert.Equal($"An error occurred invoking '{toolName}'.", result.Content[0].Text);

var errorLog = Assert.Single(mockLoggerProvider.LogMessages, m => m.LogLevel == LogLevel.Error);
Assert.Equal($"\"{toolName}\" threw an unhandled exception.", errorLog.Message);
Assert.IsType<InvalidOperationException>(errorLog.Exception);
Assert.Equal(exceptionMessage, errorLog.Exception.Message);
}

private sealed class MyService;

private class DisposableToolType : IDisposable
Expand Down
Loading