From 97acf0a123624c60f9fd90f41aa4a8ac757c22f6 Mon Sep 17 00:00:00 2001 From: Hadi Khazaee Asl Date: Thu, 5 Nov 2026 14:54:05 +0330 Subject: [PATCH] Add Support for Default Swagger Parameters Values in appSetting and Add Support for MCPServers Connecting and Handling Function Tooling ... --- Controllers/McpServerController.cs | 433 --------------------- Controllers/McpServersController.cs | 492 ++++++++++++++++++++++++ Controllers/XAiServiceControllerBase.cs | 16 +- Extensions/XProgramExtensions.cs | 13 + Interfaces/IXAiMcpServerProvider.cs | 33 +- Interfaces/IXAiServiceBase.cs | 4 + Providers/XAIServiceBase.cs | 156 +++++++- Providers/XAiMcpServerProvider.cs | 171 ++++++++ Providers/XAiService.cs | 2 + Providers/XDefaultThinkingAiService.cs | 2 + Startup.cs | 4 + appsettings.json | 4 + xAiApi.csproj | 1 - 13 files changed, 880 insertions(+), 451 deletions(-) delete mode 100644 Controllers/McpServerController.cs create mode 100644 Controllers/McpServersController.cs diff --git a/Controllers/McpServerController.cs b/Controllers/McpServerController.cs deleted file mode 100644 index aa2f6f6..0000000 --- a/Controllers/McpServerController.cs +++ /dev/null @@ -1,433 +0,0 @@ -using System; -using System.Linq; -using xModels.Dtos; -using xModels.Base; -using xIdentityHelper; -using System.Threading; -using xCommons.Providers; -using xAiModels.Models.Dtos; -using xAiModels.Controllers; -using System.Threading.Tasks; -using xCommons.Configurations; -using Microsoft.AspNetCore.Mvc; -using xAiModels.Interfaces.Dtos; -using xAiModels.Models.Entities; -using System.Collections.Generic; -using Microsoft.Extensions.Logging; -using Microsoft.AspNetCore.Authorization; -using Microsoft.EntityFrameworkCore.Query; - -namespace xAiApi.Controllers -{ - [Authorize] - public class McpServerController : XAiMcpServerControllerBase - { - public McpServerController( - ILogger logger, - XAppConfiguration appConfiguration, - XValidationProvider validationProvider, - IXAiMcpServerRepositoryService repositoryService, - Func, IOrderedQueryable> defaultOrderBuilder = null, - Func, IIncludableQueryable> defaultIncludeBuilder = null - ) : base( - logger, - appConfiguration, - validationProvider, - repositoryService, - defaultOrderBuilder, - defaultIncludeBuilder - ) - { } - - // - #region Actions ... - // - #region Add ... - /// - /// Add Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Add( - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Add( - item: item, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add or Update Specified Item ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddOrUpdate")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> AddOrUpdate( - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.AddOrUpdate( - item: item, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Add a Collection of Items ... - /// - /// - /// - /// - /// - /// - [HttpPost("AddMany")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task AddMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.AddMany( - request: request, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Retrieve ... - /// - /// Get Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Get( - [FromRoute] Guid id, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Get( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Get All Items ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task>> GetAll( - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.GetAll( - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Find Specified Item ... - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindOne/{query}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> FindOne( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.FindOne( - query: query, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Find Many Items ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("FindMany/{query}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task>> FindMany( - [FromRoute] string query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.FindMany( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - - /// - /// Retrieve Items Based on Query Mechanism ... - /// - /// - /// - /// - /// - /// - /// - /// - /// - [HttpGet("Query")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task>> Query( - [FromQuery] XQuery query, - [FromQuery] bool ignoreSoftDeleteds = true, - [FromQuery] bool useDefaultOrders = false, - [FromQuery] bool useDefaultIncludes = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Query( - query: query, - useDefaultOrders: useDefaultOrders, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds, - useDefaultIncludes: useDefaultIncludes - ); - - // - return result; - } - #endregion - - // - #region Update ... - /// - /// Update Item ... - /// - /// - /// - /// - /// - /// - /// - [HttpPut("{id}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Update( - [FromRoute] Guid id, - [FromBody] XAiMcpServerDto item, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Update( - id: id, - item: item, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Update a Collection of items ... - /// - /// - /// - /// - /// - /// - [HttpPost("UpdateMany")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> UpdateMany( - [FromBody] XBaseRangeRequest request, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.UpdateMany( - request: request, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - - // - #region Exists ... - /// - ///Check an Item Exists or not ... - /// - /// - /// - /// - /// - /// - /// - [HttpGet("{id}/IsExists")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> IsExists( - [FromRoute] Guid id, - [FromQuery] bool ignoreSoftDeleteds = true, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.IsExists( - id: id, - cancellationToken: cancellationToken, - ignoreSoftDeleteds: ignoreSoftDeleteds - ); - - // - return result; - } - #endregion - - // - #region Remove ... - /// - /// Remove an Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpDelete("{id}")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task> Remove( - [FromRoute] Guid id, - [FromQuery] bool softDelete = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.Remove( - id: id, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return result; - } - - /// - /// Remove Many Items ... - /// - /// - /// - /// - /// - /// - /// - [HttpPost("RemoveMany")] - [Authorize(Policy = XPolicies.EnabledAdmin)] - public override async Task RemoveMany( - [FromBody] XBaseRangeRequest request, - [FromQuery] bool softDelete = false, - CancellationToken cancellationToken = default - ) - { - // - var result = await base.RemoveMany( - request: request, - softDelete: softDelete, - cancellationToken: cancellationToken - ); - - // - return result; - } - #endregion - #endregion - } -} \ No newline at end of file diff --git a/Controllers/McpServersController.cs b/Controllers/McpServersController.cs new file mode 100644 index 0000000..dd53a9a --- /dev/null +++ b/Controllers/McpServersController.cs @@ -0,0 +1,492 @@ +using System; +using xModels.Dtos; +using xIdentityHelper; +using System.Threading; +using xAiApi.Interfaces; +using xCommons.Providers; +using xCommons.Extensions; +using xAiModels.Extensions; +using xAiModels.Models.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using xIdentityService.Controllers; +using Microsoft.AspNetCore.Authorization; + +namespace xAiApi.Controllers +{ + [Authorize] + public class McpServersController : XBaseIdentityApiV1Controller + { + private readonly IXAiMcpServerProvider mcpServerProvider; + + public McpServersController( + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + ILogger logger, + XValidationProvider validationProvider, + IXAiMcpServerProvider mcpServerProvider + ) : base( + logger, + appConfiguration, + identityProvider, + validationProvider + ) + { + this.mcpServerProvider = mcpServerProvider; + } + + // + #region Provider ... + /// + /// Retrieve Specified MCP Server ... + /// + /// + /// + /// + [HttpGet("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> GetMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.GetMcpServer( + id: id, + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Add MCP Server ... + /// + /// + /// + /// + [HttpPost] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> AddMcpServer( + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || item.IsNullOrDefault()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.AddMcpServer( + item: item, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Update Specified MCP Server ... + /// + /// + /// + /// + /// + [HttpPut("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> UpdateMcpServer( + [FromRoute] Guid id, + [FromBody] XAiMcpServerDto item, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (id.IsDefaultGuid() || + !ModelState.IsValid || + !item.IsValidForAddOrUpdate()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.UpdateMcpServer( + id: id, + item: item, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Remove Specified MCP Server ... + /// + /// + /// + /// + [HttpDelete("{id}")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> RemoveMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.RemoveMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Enable Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Enable")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> EnableMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.EnableMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Disable Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Disable")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> DisableMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.DisableMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Toggle Specified MCP Server ... + /// + /// + /// + /// + [HttpPost("{id}/Toggle")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task> ToggleMcpServer( + [FromRoute] Guid id, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid || id.IsDefaultGuid()) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.ToggleMcpServer( + id: id, + userInfo: userInfo, + connectionId: connectionId, + cancellationToken: cancellationToken + ); + + // + return Ok(result); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Get all Registered MCP Servers by handling Ownership ... + /// + /// + /// + [HttpGet] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task>> GetMcpServers( + [FromQuery] bool forceOwner = true, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid) + { + XException.InvalidArgs.Throw(); + } + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.GetAll( + userInfo: userInfo, + forceOwner: forceOwner, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Query Registered MCP Servers by handling Ownership ... + /// + /// + /// + /// + /// + [HttpGet("Query")] + [Authorize(Policy = XPolicies.EnabledUser)] + public virtual async Task>> QueryMcpServers( + [FromQuery] XQuery query, + [FromQuery] bool forceOwner = true, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Validate ... + if (!ModelState.IsValid) + { + XException.InvalidArgs.Throw(); + } + await ValidationProvider + .GroupValidationBuilder() + .AddNotNull(query) + .ValidateGroupAsync(); + + // + var userInfo = await GetUserInfo(); + var connectionId = GetConnectionId(); + + // + var result = await mcpServerProvider.Query( + query: query, + userInfo: userInfo, + forceOwner: forceOwner, + cancellationToken: cancellationToken + ); + + // + return Ok(result.ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + /// + /// Refresh MCP Servers ... + /// + /// + [HttpPost("Refresh")] + [Authorize(Policy = XPolicies.EnabledAdmin)] + public async Task RefreshMcpServers() + { + // + try + { + // + await mcpServerProvider.RefreshAsync(); + + // + return Ok(); + } catch(Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + } +} \ No newline at end of file diff --git a/Controllers/XAiServiceControllerBase.cs b/Controllers/XAiServiceControllerBase.cs index 32dd63f..3735719 100644 --- a/Controllers/XAiServiceControllerBase.cs +++ b/Controllers/XAiServiceControllerBase.cs @@ -67,9 +67,13 @@ namespace xAiApi.Controllers // Validate ... ValidationProvider.NotEmpty(question); + // + var userInfo = await GetUserInfo(); + // var result = await aiService.AskTextAsync( prompt: question, + userInfo: userInfo, cancellationToken: cancellationToken ); @@ -112,9 +116,13 @@ namespace xAiApi.Controllers // Configure SSE Response ... Response.PrepareSseResponse(); + // + var userInfo = await GetUserInfo(); + // var enumerable = aiService.AskTextAsEnumerable( prompt: question, + userInfo: userInfo, cancellationToken: cancellationToken ); @@ -324,7 +332,7 @@ namespace xAiApi.Controllers files: null, topK: request.TopK, userInfo: userInfo, - type: request.Type, + type: request.Type, prompt: request.Prompt, minScore: request.MinScore, connectionId: connectionId, @@ -381,7 +389,7 @@ namespace xAiApi.Controllers files: null, topK: request.TopK, userInfo: userInfo, - type: request.Type, + type: request.Type, prompt: request.Prompt, minScore: request.MinScore, connectionId: connectionId, @@ -466,7 +474,7 @@ namespace xAiApi.Controllers files: files, topK: request.TopK, userInfo: userInfo, - type: request.Type, + type: request.Type, prompt: request.Prompt, minScore: request.MinScore, connectionId: connectionId, @@ -524,7 +532,7 @@ namespace xAiApi.Controllers files: files, topK: request.TopK, userInfo: userInfo, - type: request.Type, + type: request.Type, prompt: request.Prompt, minScore: request.MinScore, connectionId: connectionId, diff --git a/Extensions/XProgramExtensions.cs b/Extensions/XProgramExtensions.cs index c99afba..bfaef84 100644 --- a/Extensions/XProgramExtensions.cs +++ b/Extensions/XProgramExtensions.cs @@ -1,4 +1,6 @@ using xIdentityHelper; +using xAiApi.Providers; +using xAiApi.Interfaces; using xCommons.Extensions; using xCommons.Authorization; using System.Collections.Generic; @@ -11,6 +13,17 @@ namespace xAiApi.Extensions { public static class XProgramExtensions { + /// + /// Register MCP Server Provider ... + /// + /// + public static void AddXAiMcpServerProvider( + this IServiceCollection source + ) + { + source.AddScoped(); + } + /// /// Register Authorization Policies /// diff --git a/Interfaces/IXAiMcpServerProvider.cs b/Interfaces/IXAiMcpServerProvider.cs index 251263e..fb25baa 100644 --- a/Interfaces/IXAiMcpServerProvider.cs +++ b/Interfaces/IXAiMcpServerProvider.cs @@ -1,17 +1,19 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; -using System.Threading.Tasks; -using ModelContextProtocol.Client; -using xAiModels.Models.Dtos; -using xAiModels.Models.Entities; -using xIdentityModels.Models; using xModels.Dtos; +using System.Threading; +using xAiModels.Models.Dtos; +using xIdentityModels.Models; +using System.Threading.Tasks; +using System.Linq.Expressions; +using xAiModels.Models.Entities; +using System.Collections.Generic; +using ModelContextProtocol.Client; namespace xAiApi.Interfaces { + /// + /// MCP Manager / Provider ... + /// public interface IXAiMcpServerProvider { // @@ -64,6 +66,19 @@ namespace xAiApi.Interfaces CancellationToken cancellationToken = default ); + /// + /// Get an Mcp Server ... + /// + /// + /// + /// + /// + Task GetMcpServer( + Guid id, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ); + /// /// Update Specified Mcp Server ... /// diff --git a/Interfaces/IXAiServiceBase.cs b/Interfaces/IXAiServiceBase.cs index 843291a..358208d 100644 --- a/Interfaces/IXAiServiceBase.cs +++ b/Interfaces/IXAiServiceBase.cs @@ -32,10 +32,12 @@ namespace xAiApi.Interfaces /// Base Method for Communicate with LLM ... /// /// + /// /// /// Task AskTextAsync( string prompt, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); @@ -43,10 +45,12 @@ namespace xAiApi.Interfaces /// Base Method for Communicate with LLM ... /// /// + /// /// /// IAsyncEnumerable AskTextAsEnumerable( string prompt, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ); diff --git a/Providers/XAIServiceBase.cs b/Providers/XAIServiceBase.cs index 3efe183..c3958d2 100644 --- a/Providers/XAIServiceBase.cs +++ b/Providers/XAIServiceBase.cs @@ -47,16 +47,22 @@ namespace xAiApi.Providers private readonly ILogger logger; private readonly XAiApiConfiguration configuration; private readonly XValidationProvider validationProvider; + private readonly IXAiMcpServerProvider mcpServerProvider; private readonly IXFileContentExtractor fileContentExtractor; + // + private readonly bool useProvidedMcpServers; + protected XAIServiceBase( IXAiRAGService ragProvider, IXAiDataProvider dataProvider, ILogger logger, XAiApiConfiguration configuration, XValidationProvider validationProvider, + IXAiMcpServerProvider mcpServerProvider, IXFileContentExtractor fileContentExtractor, - string model = null + string model = null, + bool useProvidedMcpServers = true ) { // @@ -64,8 +70,10 @@ namespace xAiApi.Providers this.ragProvider = ragProvider; this.dataProvider = dataProvider; this.configuration = configuration; + this.mcpServerProvider = mcpServerProvider; this.validationProvider = validationProvider; this.fileContentExtractor = fileContentExtractor; + this.useProvidedMcpServers = useProvidedMcpServers; // // Prepare Embedding Model Descriptor ... @@ -86,10 +94,12 @@ namespace xAiApi.Providers /// Base Method for Communicate with LLM ... /// /// + /// /// /// public virtual async Task AskTextAsync( string prompt, + XUserClaimsInfoDto userInfo = null, CancellationToken cancellationToken = default ) { @@ -103,6 +113,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); var history = GetHistory(prompt); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools .Cast()]; + } + + // var response = await client.GetResponseAsync( options: Options, messages: history, @@ -131,10 +158,12 @@ namespace xAiApi.Providers /// Base Method for Communicate with LLM ... /// /// + /// /// /// public virtual async IAsyncEnumerable AskTextAsEnumerable( string prompt, + XUserClaimsInfoDto userInfo = null, [EnumeratorCancellation] CancellationToken cancellationToken = default ) @@ -149,6 +178,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); var history = GetHistory(prompt); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools .Cast()]; + } + + // var enumerable = client.GetStreamingResponseAsync( options: Options, messages: history @@ -196,6 +242,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); var history = GetHistory(prompt, context); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // var response = await client.GetResponseAsync( options: Options, messages: history, @@ -245,6 +308,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); var history = GetHistory(prompt, context); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // var enumerable = client.GetStreamingResponseAsync( options: Options, messages: history, @@ -312,6 +392,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // var response = await client .GetResponseAsync( options: Options, @@ -376,6 +473,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // var stream = client .GetStreamingResponseAsync( options: Options, @@ -449,6 +563,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // var response = await client.GetResponseAsync( options: Options, messages: prep.History, @@ -536,6 +667,23 @@ namespace xAiApi.Providers // using var client = Descriptor.GetClient(); + + // + // Handle Provided MCP Servers ... + if (useProvidedMcpServers) + { + // + var availableTools = await mcpServerProvider + .GetAvailableToolsAsync( + userInfo: userInfo, + cancellationToken: cancellationToken + ); + + // + Options.Tools = [.. availableTools.Cast()]; + } + + // var stream = client .GetStreamingResponseAsync( options: Options, @@ -992,9 +1140,6 @@ namespace xAiApi.Providers { continue; } - - // - // TODO: Implement File Save ... } // @@ -1133,6 +1278,9 @@ namespace xAiApi.Providers // var result = new List(); + // + await Task.FromResult(true); + // // Retrieve Introduction Prompt ... var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName); diff --git a/Providers/XAiMcpServerProvider.cs b/Providers/XAiMcpServerProvider.cs index 6b527ae..14f51ad 100644 --- a/Providers/XAiMcpServerProvider.cs +++ b/Providers/XAiMcpServerProvider.cs @@ -13,6 +13,7 @@ using xAiModels.Models.Dtos; using xIdentityModels.Models; using System.Threading.Tasks; using System.Linq.Expressions; +using xAiModels.Providers.Hubs; using xAiModels.Models.Entities; using xAiModels.Interfaces.Dtos; using xIdentityHelper.Extensions; @@ -20,6 +21,7 @@ using System.Collections.Generic; using xIdentityService.Interfaces; using ModelContextProtocol.Client; using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.SignalR; using xAiModels.Interfaces.Entities; using xAiModels.Interfaces.Enrichers; @@ -30,6 +32,7 @@ namespace xAiApi.Providers /// public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable { + private readonly IHubContext hub; private readonly IXIdentityProvider identityProvider; private readonly ILogger logger; private readonly XValidationProvider validationProvider; @@ -44,6 +47,7 @@ namespace xAiApi.Providers private bool isInitialized = false; public XAiMcpServerProvider( + IHubContext hub, IXIdentityProvider identityProvider, ILogger logger, XValidationProvider validationProvider, @@ -53,6 +57,7 @@ namespace xAiApi.Providers ) { // + this.hub = hub; this.logger = logger; this.identityProvider = identityProvider; this.mcpServerEnricher = mcpServerEnricher; @@ -299,6 +304,15 @@ namespace xAiApi.Providers cancellationToken: cancellationToken ); + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: result.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerCreated.GetStringValue() + ); + // await initLock.WaitAsync(cancellationToken); try @@ -315,6 +329,59 @@ namespace xAiApi.Providers return result; } + /// + /// Get an Mcp Server ... + /// + /// + /// + /// + /// + public async Task GetMcpServer( + Guid id, + XUserClaimsInfoDto userInfo = null, + CancellationToken cancellationToken = default + ) + { + // + // Validation ... + validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(userInfo) + .AddNotEmpty(userInfo.UserId) + .ValidateGroup(); + + // + var result = await mcpServerServiceProvider + .GetAsync( + id: id, + includeBuilder: null, + ignoreSoftDeleteds: true, + cancellationToken: cancellationToken + ); + + // + // Validate Ownership ... + if (!userInfo.IsAdmin() && result.OwnerId != userInfo.UserId) + { + XException.NotAllowed.Throw(); + } + + // + if (!result.IsNullOrDefault()) + { + // + // Handle Enrichment ... + result = await mcpServerEnricher.Enrich( + source: result, + cancellationToken: cancellationToken + ); + } + + // + return result; + } + /// /// Update Specified Mcp Server ... /// @@ -396,6 +463,15 @@ namespace xAiApi.Providers cancellationToken: cancellationToken ); + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: result.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + // await initLock.WaitAsync(cancellationToken); try @@ -484,6 +560,15 @@ namespace xAiApi.Providers cancellationToken: cancellationToken ); + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: result.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerRemoved.GetStringValue() + ); + // await initLock.WaitAsync(cancellationToken); try @@ -569,6 +654,15 @@ namespace xAiApi.Providers // if (result) { + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: exists.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + // await initLock.WaitAsync(cancellationToken); try @@ -654,6 +748,15 @@ namespace xAiApi.Providers // if (result) { + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: exists.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + // await initLock.WaitAsync(cancellationToken); try @@ -731,6 +834,15 @@ namespace xAiApi.Providers // if (result) { + // + // Sending Push ... + await SendPush( + connectionId: connectionId, + cancellationToken: cancellationToken, + payLoad: exists.ToJSON(camelCase: true), + action: XAiDataProviderHubActions.McpServerUpdated.GetStringValue() + ); + // await initLock.WaitAsync(cancellationToken); try @@ -1114,5 +1226,64 @@ namespace xAiApi.Providers } } #endregion + + // + #region Hub Actions ... + /// + /// Send Custom Push Message ... + /// + /// + /// + /// + /// + /// + public async Task SendPush( + string action, + string payLoad, + string connectionId = null, + CancellationToken cancellationToken = default + ) + { + // + try + { + // + // Collect Allowed Actions ... + var actions = new List + { + XAiDataProviderHubActions.McpServerCreated.GetStringValue(), + XAiDataProviderHubActions.McpServerUpdated.GetStringValue(), + XAiDataProviderHubActions.McpServerRemoved.GetStringValue(), + }; + + // + // Validate Args ... + var isValid = + !action.IsNullOrEmpty() && + actions.Contains(action); + if (!isValid) + { + return; + } + + // + // Retrieve Connection Id ... + var clients = hub.Clients.All; + if (!connectionId.IsNullOrEmpty()) + { + clients = hub.Clients.AllExcept(connectionId); + } + + // + await clients.SendAsync( + action, + payLoad, + connectionId, + cancellationToken + ); + } + catch { } + } + #endregion } } \ No newline at end of file diff --git a/Providers/XAiService.cs b/Providers/XAiService.cs index 2fc8ea7..0e41651 100644 --- a/Providers/XAiService.cs +++ b/Providers/XAiService.cs @@ -16,6 +16,7 @@ namespace xAiApi.Providers ILogger logger, XAiApiConfiguration configuration, XValidationProvider validationProvider, + IXAiMcpServerProvider mcpServerProvider, IXFileContentExtractor fileContentExtractor ) : base( ragProvider, @@ -23,6 +24,7 @@ namespace xAiApi.Providers logger, configuration, validationProvider, + mcpServerProvider, fileContentExtractor, XAiApiConstants.XAiDefaultModelName ) diff --git a/Providers/XDefaultThinkingAiService.cs b/Providers/XDefaultThinkingAiService.cs index 1f430ed..bde80b7 100644 --- a/Providers/XDefaultThinkingAiService.cs +++ b/Providers/XDefaultThinkingAiService.cs @@ -17,6 +17,7 @@ namespace xAiApi.Providers ILogger logger, XAiApiConfiguration configuration, XValidationProvider validationProvider, + IXAiMcpServerProvider mcpServerProvider, IXFileContentExtractor fileContentExtractor, ReasoningEffort effort = ReasoningEffort.Medium, ReasoningOutput output = ReasoningOutput.Full @@ -26,6 +27,7 @@ namespace xAiApi.Providers logger, configuration, validationProvider, + mcpServerProvider, fileContentExtractor, XAiApiConstants.XAiDefaultThinkingModelName ) diff --git a/Startup.cs b/Startup.cs index c094aaf..54f2312 100644 --- a/Startup.cs +++ b/Startup.cs @@ -184,6 +184,10 @@ namespace xAiApi // Register XAiApi Configuration ... services.AddXAiApiConfiguration(Configuration); + // + // Register MCP Server Provider ... + services.AddXAiMcpServerProvider(); + // // Register File Content Extractor Services ... services.AddXAiFileContentExtractors(); diff --git a/appsettings.json b/appsettings.json index 4709a07..800aad6 100644 --- a/appsettings.json +++ b/appsettings.json @@ -18,7 +18,11 @@ "Name": "Hadi Khazaee Asl", "Email": "hadi_khazaee_asl@yahoo.com", "Url": "https://www.saherelm.ir" + }, + "DefaultValues": { + "version": "1.0" } + }, "HttpServiceConfiguration": { "DisableSSLCheck": true, diff --git a/xAiApi.csproj b/xAiApi.csproj index d016453..abc9e33 100644 --- a/xAiApi.csproj +++ b/xAiApi.csproj @@ -7,7 +7,6 @@ Hadi Khazaee Asl SaherElm IT Center xSaherElm.xAiApi - netcoreapp3.1