Add Support for Default Swagger Parameters Values in appSetting and Add Support for MCPServers Connecting and Handling Function Tooling ...

This commit is contained in:
2026-11-05 14:54:05 +03:30
parent c7efdd5525
commit 97acf0a123
13 changed files with 880 additions and 451 deletions
-433
View File
@@ -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<McpServerController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider,
IXAiMcpServerRepositoryService repositoryService,
Func<IQueryable<XAiMcpServer>, IOrderedQueryable<XAiMcpServer>> defaultOrderBuilder = null,
Func<IQueryable<XAiMcpServer>, IIncludableQueryable<XAiMcpServer, object>> defaultIncludeBuilder = null
) : base(
logger,
appConfiguration,
validationProvider,
repositoryService,
defaultOrderBuilder,
defaultIncludeBuilder
)
{ }
//
#region Actions ...
//
#region Add ...
/// <summary>
/// Add Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> Add(
[FromBody] XAiMcpServerDto item,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Add(
item: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Add or Update Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AddOrUpdate")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> AddOrUpdate(
[FromBody] XAiMcpServerDto item,
CancellationToken cancellationToken = default
)
{
//
var result = await base.AddOrUpdate(
item: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Add a Collection of Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("AddMany")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult> AddMany(
[FromBody] XBaseRangeRequest<XAiMcpServerDto> request,
CancellationToken cancellationToken = default
)
{
//
var result = await base.AddMany(
request: request,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
//
#region Retrieve ...
/// <summary>
/// Get Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("{id}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> 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;
}
/// <summary>
/// Get All Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultOrders"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> 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;
}
/// <summary>
/// Find Specified Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("FindOne/{query}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> 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;
}
/// <summary>
/// Find Many Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultOrders"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("FindMany/{query}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> 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;
}
/// <summary>
/// Retrieve Items Based on Query Mechanism ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="useDefaultOrders"></param>
/// <param name="useDefaultIncludes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Query")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XQueryResult<XAiMcpServerDto>>> 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 ...
/// <summary>
/// Update Item ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPut("{id}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> Update(
[FromRoute] Guid id,
[FromBody] XAiMcpServerDto item,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Update(
id: id,
item: item,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Update a Collection of items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("UpdateMany")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<bool>> UpdateMany(
[FromBody] XBaseRangeRequest<XAiMcpServerDto> request,
CancellationToken cancellationToken = default
)
{
//
var result = await base.UpdateMany(
request: request,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
//
#region Exists ...
/// <summary>
///Check an Item Exists or not ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("{id}/IsExists")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<bool>> 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 ...
/// <summary>
/// Remove an Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpDelete("{id}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult<XAiMcpServerDto>> Remove(
[FromRoute] Guid id,
[FromQuery] bool softDelete = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.Remove(
id: id,
softDelete: softDelete,
cancellationToken: cancellationToken
);
//
return result;
}
/// <summary>
/// Remove Many Items ...
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="request"></param>
/// <param name="softDelete"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("RemoveMany")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public override async Task<ActionResult> RemoveMany(
[FromBody] XBaseRangeRequest<XAiMcpServerDto> request,
[FromQuery] bool softDelete = false,
CancellationToken cancellationToken = default
)
{
//
var result = await base.RemoveMany(
request: request,
softDelete: softDelete,
cancellationToken: cancellationToken
);
//
return result;
}
#endregion
#endregion
}
}
+492
View File
@@ -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<McpServersController> logger,
XValidationProvider validationProvider,
IXAiMcpServerProvider mcpServerProvider
) : base(
logger,
appConfiguration,
identityProvider,
validationProvider
)
{
this.mcpServerProvider = mcpServerProvider;
}
//
#region Provider ...
/// <summary>
/// Retrieve Specified MCP Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("{id}")]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<XAiMcpServerDto>> 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;
}
}
/// <summary>
/// Add MCP Server ...
/// </summary>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<XAiMcpServerDto>> 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;
}
}
/// <summary>
/// Update Specified MCP Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPut("{id}")]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<XAiMcpServerDto>> 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;
}
}
/// <summary>
/// Remove Specified MCP Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpDelete("{id}")]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<XAiMcpServerDto>> 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;
}
}
/// <summary>
/// Enable Specified MCP Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("{id}/Enable")]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<bool>> 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;
}
}
/// <summary>
/// Disable Specified MCP Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("{id}/Disable")]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<bool>> 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;
}
}
/// <summary>
/// Toggle Specified MCP Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpPost("{id}/Toggle")]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<bool>> 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;
}
}
/// <summary>
/// Get all Registered MCP Servers by handling Ownership ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<IEnumerable<XAiMcpServerDto>>> 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;
}
}
/// <summary>
/// Query Registered MCP Servers by handling Ownership ...
/// </summary>
/// <param name="query"></param>
/// <param name="forceOwner"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
[HttpGet("Query")]
[Authorize(Policy = XPolicies.EnabledUser)]
public virtual async Task<ActionResult<XQueryResult<XAiMcpServerDto>>> 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
/// <summary>
/// Refresh MCP Servers ...
/// </summary>
/// <returns></returns>
[HttpPost("Refresh")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public async Task<ActionResult> RefreshMcpServers()
{
//
try
{
//
await mcpServerProvider.RefreshAsync();
//
return Ok();
} catch(Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
}
}
+12 -4
View File
@@ -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,
+13
View File
@@ -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
{
/// <summary>
/// Register MCP Server Provider ...
/// </summary>
/// <param name="source"></param>
public static void AddXAiMcpServerProvider(
this IServiceCollection source
)
{
source.AddScoped<IXAiMcpServerProvider, XAiMcpServerProvider>();
}
/// <summary>
/// Register Authorization Policies
/// </summary>
+24 -9
View File
@@ -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
{
/// <summary>
/// MCP Manager / Provider ...
/// </summary>
public interface IXAiMcpServerProvider
{
//
@@ -64,6 +66,19 @@ namespace xAiApi.Interfaces
CancellationToken cancellationToken = default
);
/// <summary>
/// Get an Mcp Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XAiMcpServerDto> GetMcpServer(
Guid id,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Update Specified Mcp Server ...
/// </summary>
+4
View File
@@ -32,10 +32,12 @@ namespace xAiApi.Interfaces
/// Base Method for Communicate with LLM ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> AskTextAsync(
string prompt,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
@@ -43,10 +45,12 @@ namespace xAiApi.Interfaces
/// Base Method for Communicate with LLM ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
IAsyncEnumerable<string> AskTextAsEnumerable(
string prompt,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
+152 -4
View File
@@ -47,16 +47,22 @@ namespace xAiApi.Providers
private readonly ILogger<XAIServiceBase> 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<XAIServiceBase> 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 ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task<string> 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<AITool>()];
}
//
var response = await client.GetResponseAsync(
options: Options,
messages: history,
@@ -131,10 +158,12 @@ namespace xAiApi.Providers
/// Base Method for Communicate with LLM ...
/// </summary>
/// <param name="prompt"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async IAsyncEnumerable<string> 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<AITool>()];
}
//
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<AITool>()];
}
//
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<AITool>()];
}
//
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<AITool>()];
}
//
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<AITool>()];
}
//
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<AITool>()];
}
//
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<AITool>()];
}
//
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<ChatMessage>();
//
await Task.FromResult(true);
//
// Retrieve Introduction Prompt ...
var ragPrompt = configuration.GetPrompt(XAiApiConstants.XAiApiRagPromptName);
+171
View File
@@ -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
/// </summary>
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
{
private readonly IHubContext<XAiDataProviderHub> hub;
private readonly IXIdentityProvider identityProvider;
private readonly ILogger<XAiMcpServerProvider> logger;
private readonly XValidationProvider validationProvider;
@@ -44,6 +47,7 @@ namespace xAiApi.Providers
private bool isInitialized = false;
public XAiMcpServerProvider(
IHubContext<XAiDataProviderHub> hub,
IXIdentityProvider identityProvider,
ILogger<XAiMcpServerProvider> 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;
}
/// <summary>
/// Get an Mcp Server ...
/// </summary>
/// <param name="id"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XAiMcpServerDto> 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;
}
/// <summary>
/// Update Specified Mcp Server ...
/// </summary>
@@ -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 ...
/// <summary>
/// Send Custom Push Message ...
/// </summary>
/// <param name="action"></param>
/// <param name="payLoad"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task SendPush(
string action,
string payLoad,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
try
{
//
// Collect Allowed Actions ...
var actions = new List<string>
{
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
}
}
+2
View File
@@ -16,6 +16,7 @@ namespace xAiApi.Providers
ILogger<XAiService> 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
)
+2
View File
@@ -17,6 +17,7 @@ namespace xAiApi.Providers
ILogger<XAIServiceBase> 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
)
+4
View File
@@ -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();
+4
View File
@@ -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,
-1
View File
@@ -7,7 +7,6 @@
<Authors>Hadi Khazaee Asl</Authors>
<Company>SaherElm IT Center</Company>
<PackageId>xSaherElm.xAiApi</PackageId>
<!-- <TargetFramework>net8.0</TargetFramework> -->
<TargetFramework>netcoreapp3.1</TargetFramework>
<Description>