Skip to content

Use tools from an MCP Server #61

@eduhza

Description

@eduhza

I'm trying to use Google_GenerativeAI.Microsoft to use an IChatClient with Gemini configured but i'm having issues with the tools.

My tools are defined in my MCP Server using ModelContextProtocol

[McpServerToolType]
public class FuncionarioTools(ILogger<FuncionarioTools> logger)
{
    [McpServerTool, Description("Adiciona um novo funcionário")]
    public async Task<string> AdicionarFuncionario([Description("Dados do funcionário a ser adicionado")] FuncionarioDto adicionarFuncionarioDto)
    {
        logger.LogInformation("Adicionando funcionário: {Nome}", adicionarFuncionarioDto.Nome);
        // do stuffs...
    }
}

But when I send the tools to GetResponseAsync I get errors for all DateOnly properties and parameters that has DataAnnotations such as [EmailAdress]:

GenerativeAI.Exceptions.ApiException
HResult=0x80131500
Message=INVALID_ARGUMENT (Code: 400): * GenerateContentRequest.tools[0].function_declarations[1].parameters.properties[dataReferencia].format: only 'enum' and 'date-time' are supported for STRING type

  • GenerateContentRequest.tools[0].function_declarations[3].parameters.properties[adicionarExtraAssinaturaDto].properties[cobrarApartirDe].format: only 'enum' and 'date-time' are supported for STRING type
  • GenerateContentRequest.tools[0].function_declarations[84].parameters.properties[adicionarFuncionarioDto].properties[emailPessoal].format: only 'enum' and 'date-time' are supported for STRING type
    ....
    Source=GenerativeAI
    StackTrace:
    at GenerativeAI.Core.ApiBase.d__13.MoveNext()
    at GenerativeAI.Core.ApiBase.d__12`2.MoveNext()
    at GenerativeAI.BaseModel.d__2.MoveNext()
    at GenerativeAI.GenerativeModel.d__36.MoveNext()
    at GenerativeAI.Microsoft.GenerativeAIChatClient.d__10.MoveNext()
    at Compartilhado.Aplicacao.Servicos.Compartilhado.AgenteIA.AgenteIAServico.d__4.MoveNext()

Is there a fix to this or another proper way to achieve the communication with gemini correctly exposing my MCP Tools?
Here is my code:

public sealed class AgenteIAServico(
    IChatClient chatClient,
    IClienteMcpServidor mcpClient,
    ILogger<AgenteIAServico> logger
) : IAgenteIAServico
{
    public async Task<RespostaPromptDto> ProcessarPromptAsync(string prompt, List<AIContent> historico)
    {
        try
        {
            await mcpClient.IniciarServidorMcp();
            prompt = "Buscar enderecos com id = 1";
            logger.LogInformation("Processando prompt: {Mensagem}", prompt);

            var mcpTools = await mcpClient.ListarToolsAsync();

            var chatHistory = new List<Microsoft.Extensions.AI.ChatMessage>
            {
                new(ChatRole.User, prompt)
            };

            var chatResponse = await chatClient.GetResponseAsync(chatHistory, new ChatOptions
            {
                Tools = [.. mcpTools]
            });
            return new RespostaPromptDto
            {
                Mensagem = chatResponse.Text,
                HistoricoConversa = [],
                Sucesso = true
            };
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Erro ao processar prompt");
            return new RespostaPromptDto
            {
                Mensagem = "Erro interno do servidor",
                HistoricoConversa = historico,
                Sucesso = false,
                ErroMensagem = ex.Message
            };
        }
}

Dependency injection:

        var geminiApiKey = configuration["GEMINI_API_KEY"];
        if (!string.IsNullOrWhiteSpace(geminiApiKey))
        {
            services.AddScoped<IChatClient>(provider => new GenerativeAIChatClient(geminiApiKey));
        }
        services.AddSingleton<IClienteMcpServidor, ClienteMcpServidor>();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions