Compare commits

...
11 Commits
Author SHA1 Message Date
saherelm c05a389a44 last ... 2026-11-11 12:31:38 +03:30
saherelm 185aaae19a apply fix on Create Conversation Validations ... 2026-11-11 11:56:33 +03:30
saherelm 4fe5d57d37 fix Create Conversation to Handle Default Project Id ... 2026-11-11 11:43:10 +03:30
saherelm 27b9f51dc9 apply fix on owner id validation ... 2026-11-11 10:31:47 +03:30
saherelm 08fd26ffac last ... 2026-11-10 17:30:10 +03:30
saherelm 476ace743d last ... 2026-11-08 18:06:27 +03:30
saherelm c53553e1cf add all requirements for implementing XAiMcpClient ... 2026-11-06 19:09:07 +03:30
saherelm 33dda6bee7 Handle Authentication and Authorization in xAiMcpServer ... 2026-11-05 20:08:43 +03:30
saherelm 7ba0916461 adding datetime zone library ... 2026-11-05 18:12:50 +03:30
saherelm 2d44ec8744 Adding Requirements for AiMcpServer Definition and Usage ... 2026-11-05 14:51:59 +03:30
saherelm 25534f0273 Add MCP Server Domain and Persistence Contracts
- افزودن XAiMcpServer و XAiMcpServerDto.
- افزودن قراردادها و providerهای repository، in-memory/EF/Mongo، key generator،
  seeder، enricher و service provider.
- افزودن Entity Framework configuration، mapper و GraphQL type/query/schema.
- افزودن XAiMcpServerUsageScope و XAiMcpToolDescriptor.
2026-11-04 17:50:51 +03:30
18 changed files with 609 additions and 68 deletions
+40
View File
@@ -0,0 +1,40 @@
using System;
namespace xAiModels.Attributes
{
/// <summary>
/// Decorate and Describe Specified MCP Tool to LLM ...
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class XAiMcpToolAttribute : Attribute
{
/// <summary>
/// Tools Unique Name (Default: Method Name) ...
/// </summary>
/// <value></value>
public string Name { get; }
/// <summary>
/// Tools Description for LLM ...
/// </summary>
/// <value></value>
public string Description { get; set; }
/// <summary>
/// Specify it's Required to Authenticated or not ...
/// </summary>
/// <value></value>
public bool RequiresAuthentication { get; set; } = false;
/// <summary>
/// Authorization and Policiy ...
/// </summary>
/// <value></value>
public string RequiredPolicy { get; set; } = string.Empty;
public XAiMcpToolAttribute(string name = null)
{
Name = name;
}
}
}
+34
View File
@@ -0,0 +1,34 @@
using System;
namespace xAiModels.Attributes
{
/// <summary>
/// Describe Specific Tools Parameter Metadata ...
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public sealed class XAiMcpToolParamAttribute : Attribute
{
/// <summary>
/// Parameter Name in JSON (Default Parameter Name) ...
/// </summary>
/// <value></value>
public string Name { get; }
/// <summary>
/// Describe Parameter to LLM ...
/// </summary>
/// <value></value>
public string Description { get; set; }
/// <summary>
/// Specified this Parameter is Required or not (Default is true) ...
/// </summary>
/// <value></value>
public bool Required { get; set; } = true;
public XAiMcpToolParamAttribute(string name = null)
{
Name = name;
}
}
}
+10
View File
@@ -0,0 +1,10 @@
using System;
namespace xAiModels.Attributes
{
/// <summary>
/// Decorate Tools Classes ...
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class XAiMcpToolTypeAttribute : Attribute { }
}
+23
View File
@@ -0,0 +1,23 @@
namespace xAiModels.Constants
{
public struct XAiMcpConstants
{
//
public const string XAiMcpProtocol = "2024-11-05";
public const string XAiMcpClientName = "XAiMcpClient";
public const string XAiMcpSessionIdentifier = "Mcp-Session-Id";
public const string XAiMcpProtocolIdentifier = "MCP-Protocol-Version";
//
public const string TextKey = "text";
public const string ContentKey = "content";
public const string ServerInfoNameKey = "name";
public const string ServerInfoKey = "serverInfo";
public const string ServerInfoVersionKey = "version";
public const string ProtocolVersionKey = "protocolVersion";
//
public const string serverInfoNameValue = "xAiApi";
public const string serverInfoVersionValue = "";
}
}
+16
View File
@@ -0,0 +1,16 @@
using xExceptions.Attributes;
namespace xAiModels.Constants
{
public enum XAiMcpMethods
{
[StringValue("initialize")]
Initialize,
[StringValue("tools/list")]
ToolsList,
[StringValue("tools/call")]
ToolsCall,
}
}
-33
View File
@@ -1,33 +0,0 @@
using System;
using System.Linq;
using xCommons.Providers;
using xAiModels.Models.Dtos;
using xDataService.Interfaces;
using xCommons.Configurations;
using xDataService.Controllers;
using xAiModels.Models.Entities;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore.Query;
namespace xAiModels.Controllers
{
public abstract class XAiMcpServerControllerBase : XBaseServiceController<XAiMcpServer, XAiMcpServerDto, Guid>
{
protected XAiMcpServerControllerBase(
ILogger<XAiMcpServerControllerBase> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider,
IXBaseRepositoryService<XAiMcpServer, XAiMcpServerDto, Guid> repositoryService,
Func<IQueryable<XAiMcpServer>, IOrderedQueryable<XAiMcpServer>> defaultOrderBuilder = null,
Func<IQueryable<XAiMcpServer>, IIncludableQueryable<XAiMcpServer, object>> defaultIncludeBuilder = null
) : base(
logger,
appConfiguration,
validationProvider,
repositoryService,
defaultOrderBuilder,
defaultIncludeBuilder
)
{ }
}
}
+2 -1
View File
@@ -17,7 +17,8 @@ namespace xAiModels.Extensions
source is not null &&
!source.IsNullOrDefault() &&
!string.IsNullOrWhiteSpace(source.Text) &&
source.FinishReason == ChatFinishReason.Stop;
(source.FinishReason == ChatFinishReason.Stop ||
source.FinishReason == ChatFinishReason.ToolCalls);
//
return result;
+34 -10
View File
@@ -29,8 +29,7 @@ namespace xAiModels.Extensions
//
var result =
!source.IsNullOrDefault() &&
!source.OwnerId.IsNullOrEmpty() &&
!source.Prompt.IsNullOrEmpty();
!source.OwnerId.IsNullOrEmpty();
//
return result;
@@ -40,8 +39,7 @@ namespace xAiModels.Extensions
//
var result =
!source.IsNullOrDefault() &&
!source.OwnerId.IsNullOrEmpty() &&
!source.Prompt.IsNullOrEmpty();
!source.OwnerId.IsNullOrEmpty();
//
return result;
@@ -57,9 +55,7 @@ namespace xAiModels.Extensions
//
var result =
!source.IsNullOrDefault() &&
!source.OwnerId.IsNullOrEmpty() &&
!source.ProjectId.IsNull() &&
!source.ProjectId.IsDefaultGuid();
!source.OwnerId.IsNullOrEmpty();
//
return result;
@@ -69,9 +65,7 @@ namespace xAiModels.Extensions
//
var result =
!source.IsNullOrDefault() &&
!source.OwnerId.IsNullOrEmpty() &&
!source.ProjectId.IsNull() &&
!source.ProjectId.IsDefaultGuid();
!source.OwnerId.IsNullOrEmpty();
//
return result;
@@ -524,5 +518,35 @@ namespace xAiModels.Extensions
value: $"{XAuthorization.TokenIdentifier} {apiKey}"
);
}
/// <summary>
/// Converts To AITools ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static IList<AITool> ToAITools(
this IList<XAiMcpToolDefinition> source
)
{
//
var result = new List<AITool>();
//
foreach (var tool in source)
{
//
var declaration = AIFunctionFactory.CreateDeclaration(
name: tool.Name,
jsonSchema: tool.InputSchema,
description: tool.Description
);
//
result.Add(declaration);
}
//
return result;
}
}
}
+74
View File
@@ -0,0 +1,74 @@
using xCommons.Constants;
using xCommons.Extensions;
using xAiModels.Constants;
using xIdentityModels.Models;
using xCommons.Configurations;
using System.Collections.Generic;
using xIdentityService.Constants;
namespace xAiModels.Helpers
{
/// <summary>
/// a Helper Class for Prepare Headers of MCP Client ...
/// </summary>
public static class XAiMcpHeaderBuilder
{
/// <summary>
/// Build Headers for MCP Client Connection ...
/// </summary>
/// <param name="appConfiguration"></param>
/// <param name="sessionId"></param>
/// <param name="connectionId"></param>
/// <param name="userInfo"></param>
/// <param name="protocolVersion"></param>
/// <returns></returns>
public static Dictionary<string, string> Build(
XAppConfiguration appConfiguration,
string sessionId = null,
string connectionId = null,
XUserClaimsInfoDto userInfo = null,
string protocolVersion = XAiMcpConstants.XAiMcpProtocol
)
{
//
var headers = new Dictionary<string, string>
{
//
["Accept"] = "application/json, text/event-stream",
["Content-Type"] = "application/json",
[XAiMcpConstants.XAiMcpProtocolIdentifier] = protocolVersion,
[XAuthorization.XPoweredBy] = appConfiguration.XPoweredValue ?? "xAiApi"
};
//
// Adding Authorization Headers ...
if (!userInfo.IsNullOrDefault() && !userInfo.AccessToken.IsNullOrEmpty())
{
//
headers[XAuthorization.Header] = $"{XAuthorization.TokenIdentifier} {userInfo.AccessToken}";
headers[XAuthorization.ExpiresAt] = userInfo.ExpiresAt.ToString();
//
if (!userInfo.RefreshToken.IsNullOrEmpty())
{
headers[XAuthorization.RefreshToken] = userInfo.RefreshToken;
}
}
//
// شناسه اتصال (برای Push Notification ها)
if (!connectionId.IsNullOrEmpty()) {
headers[XHeader.ConnectionId.GetStringValue()] = connectionId;
}
//
// Session Id ...
if (!sessionId.IsNullOrEmpty()) {
headers[XAiMcpConstants.XAiMcpSessionIdentifier] = sessionId;
}
//
return headers;
}
}
}
+86
View File
@@ -0,0 +1,86 @@
using System;
using System.IO;
using System.Text;
using System.Threading;
using xCommons.Extensions;
using xHttpService.Constants;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace xAiModels.Helpers
{
public static class XAiMcpSseReader
{
/// <summary>
/// Read an SSE Event ...
/// </summary>
/// <param name="stream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async IAsyncEnumerable<string> ReadAsync(
Stream stream,
[EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
using var reader = new StreamReader(stream, Encoding.UTF8);
var dataBuffer = new StringBuilder();
while (!reader.EndOfStream)
{
//
var line = await reader.ReadLineAsync();
if (line is null)
{
break;
}
//
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
//
// Empty Line equals End of an Event ...
if (line.IsNullOrEmpty())
{
//
if (dataBuffer.Length > 0)
{
//
yield return dataBuffer.ToString();
dataBuffer.Clear();
}
//
continue;
}
//
if (line.StartsWith(XSSEConstants.DataIdentifier, StringComparison.OrdinalIgnoreCase))
{
//
var data = line
.Substring(XSSEConstants.DataIdentifier.Length)
.TrimStart();
//
if (dataBuffer.Length > 0)
{
dataBuffer.Append('\n');
}
//
dataBuffer.Append(data);
}
}
//
if (dataBuffer.Length > 0)
{
yield return dataBuffer.ToString();
}
}
}
}
+9 -3
View File
@@ -66,12 +66,14 @@ namespace xAiModels.Interfaces
/// Load List of Conversations for Specified Project ...
/// </summary>
/// <param name="projectId"></param>
/// <param name="ownerId"></param>
/// <param name="fillMessages"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XAiConversationDto>> LoadConversations(
Guid projectId,
Guid? projectId,
string ownerId = null,
bool fillMessages = false,
string connectionId = null,
CancellationToken cancellationToken = default
@@ -81,10 +83,14 @@ namespace xAiModels.Interfaces
/// Load Messages of Specified Conversation ...
/// </summary>
/// <param name="conversationId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XAiMessageDto>> LoadMessages(
Guid conversationId,
Guid? conversationId,
string ownerId = null,
string connectionId = null,
CancellationToken cancellationToken = default
);
#endregion
@@ -231,7 +237,7 @@ namespace xAiModels.Interfaces
/// <returns></returns>
Task<XAiConversationDto> CreateConversation(
string ownerId,
Guid projectId,
Guid? projectId,
XAiConversationDto item = null,
string connectionId = null,
CancellationToken cancellationToken = default
+17
View File
@@ -0,0 +1,17 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpJsonRpcError
{
[JsonPropertyName("code")]
public int Code { get; set; }
[JsonPropertyName("message")]
public string Message { get; set; }
[JsonPropertyName("data")]
public JsonElement? Data { get; set; }
}
}
+21
View File
@@ -0,0 +1,21 @@
using System;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpJsonRpcRequest
{
[JsonPropertyName("jsonrpc")]
public string JsonRpc { get; set; } = "2.0";
[JsonPropertyName("id")]
public string Id { get; set; } = Guid.NewGuid().ToString("N");
[JsonPropertyName("method")]
public string Method { get; set; }
[JsonPropertyName("params")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public object Params { get; set; }
}
}
+25
View File
@@ -0,0 +1,25 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpJsonRpcResponse
{
[JsonPropertyName("jsonrpc")]
public string JsonRpc { get; set; }
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("result")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public JsonElement? Result { get; set; }
[JsonPropertyName("error")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public XAiMcpJsonRpcError Error { get; set; }
[JsonIgnore]
public bool IsSuccess => Error is null;
}
}
+17
View File
@@ -0,0 +1,17 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace xAiModels.Models
{
public class XAiMcpToolDefinition
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
[JsonPropertyName("inputSchema")]
public JsonElement InputSchema { get; set; }
}
}
+17
View File
@@ -0,0 +1,17 @@
using System;
using System.Threading;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace xAiModels.Models
{
public class XAiMcpToolDescriptor
{
public string Name { get; set; }
public string Description { get; set; }
public JObject InputSchema { get; set; }
public string RequiredPolicy { get; set; }
public bool RequiresAuthentication { get; set; } = false;
public Func<JObject, CancellationToken, Task<string>> Execute { get; set; }
}
}
+183 -20
View File
@@ -190,30 +190,51 @@ namespace xAiModels.Providers
/// Load List of Conversations for Specified Project ...
/// </summary>
/// <param name="projectId"></param>
/// <param name="connectionId"></param>
/// <param name="ownerId"></param>
/// <param name="fillMessages"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiConversationDto>> LoadConversations(
Guid projectId,
Guid? projectId,
string ownerId = null,
bool fillMessages = false,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (projectId.IsNull() ||
projectId.IsDefaultGuid()
)
// Validate ...
if (ownerId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Normalize ...
if (projectId.IsNull() ||
!projectId.HasValue
)
{
//
var defaultProject = await GetDefaultProject(
ownerId: ownerId,
connectionId: null,
cancellationToken: cancellationToken
);
if (defaultProject.IsNullOrDefault())
{
XException.InvalidData.Throw();
}
//
projectId = defaultProject.Id;
}
//
// Retrieve Project ...
var project = await projectRepositoryService.GetAsync(
id: projectId,
id: projectId.Value,
includeBuilder: null,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
@@ -271,26 +292,60 @@ namespace xAiModels.Providers
/// Load Messages of Specified Conversation ...
/// </summary>
/// <param name="conversationId"></param>
/// <param name="ownerId"></param>
/// <param name="connectionId"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<IEnumerable<XAiMessageDto>> LoadMessages(
Guid conversationId,
Guid? conversationId,
string ownerId = null,
string connectionId = null,
CancellationToken cancellationToken = default
)
{
//
// Validate Args ...
if (conversationId.IsNull() ||
conversationId.IsDefaultGuid()
)
if (ownerId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Normalize Conversation id ...
if (conversationId.IsNull() ||
!conversationId.HasValue)
{
//
var defaultProject = await GetDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (defaultProject.IsNullOrDefault())
{
XException.InvalidData.Throw();
}
//
var defaultConversation = await GetDefaultConversation(
ownerId: ownerId,
connectionId: connectionId,
projectId: defaultProject.Id,
cancellationToken: cancellationToken
);
if (defaultConversation.IsNullOrDefault())
{
XException.InvalidData.Throw();
}
//
conversationId = defaultConversation.Id;
}
//
var conversation = await conversationRepositoryService.GetAsync(
id: conversationId,
includeBuilder: null,
id: conversationId.Value,
ignoreSoftDeleteds: true,
cancellationToken: cancellationToken
);
@@ -482,8 +537,12 @@ namespace xAiModels.Providers
// Checking Resources ...
//
// Titles ...
#region Titles ...
//
var titleResource = string.Empty;
//
// Provided in Locales ...
if (!item.TitleResource.IsNullOrDefault() &&
item.TitleResource.Locales.HasChild())
{
@@ -526,8 +585,38 @@ namespace xAiModels.Providers
}
//
// Descriptions ...
// Provided in Title (defaultLanguage) ...
if (!item.Title.IsNullOrEmpty() &&
titleResource.IsNullOrEmpty() &&
item.TitleResource.IsNullOrDefault())
{
//
var resource = await projectTitleResourceProvider.AddOrUpdateLocale(
locale: new XLocaleResourceDto
{
Value = item.Title,
Language = defaultLanguage,
},
owner: ownerId,
identifier: result.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!resource.IsNullOrDefault() &&
titleResource.IsNullOrEmpty())
{
titleResource = resource.Resource;
}
}
#endregion
//
#region Descriptions ...
//
var descriptionResource = string.Empty;
//
// Provided in Locales ...
if (!item.DescriptionResource.IsNullOrDefault() &&
item.DescriptionResource.Locales.HasChild())
{
@@ -569,6 +658,32 @@ namespace xAiModels.Providers
}
}
//
// Provided in Description (defaultLanguage) ...
if (!item.Description.IsNullOrEmpty() &&
descriptionResource.IsNullOrEmpty() &&
item.DescriptionResource.IsNullOrDefault())
{
//
var resource = await projectDescriptionResourceProvider.AddOrUpdateLocale(
locale: new XLocaleResourceDto
{
Value = item.Description,
Language = defaultLanguage,
},
owner: ownerId,
identifier: result.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!resource.IsNullOrDefault() &&
descriptionResource.IsNullOrEmpty())
{
descriptionResource = resource.Resource;
}
}
#endregion
//
// Update Data ...
result.Title = titleResource;
@@ -663,7 +778,7 @@ namespace xAiModels.Providers
/// <returns></returns>
public async Task<XAiConversationDto> CreateConversation(
string ownerId,
Guid projectId,
Guid? projectId,
XAiConversationDto item = null,
string connectionId = null,
CancellationToken cancellationToken = default
@@ -671,16 +786,34 @@ namespace xAiModels.Providers
{
//
// Validate Args ...
if (projectId.IsNull() ||
projectId.IsDefaultGuid())
if (ownerId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
if (!projectId.HasValue ||
projectId.Value.IsDefaultGuid())
{
//
var defaultProject = await GetDefaultProject(
ownerId: ownerId,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (defaultProject.IsNullOrDefault())
{
XException.ActionFailed.Throw();
}
//
projectId = defaultProject.Id;
}
//
// Handle Proejct ...
XAiProjectDto project = await projectRepositoryService.GetAsync(
id: projectId,
id: projectId.Value,
includeBuilder: null,
ignoreSoftDeleteds: true,
// fillConversations: false,
@@ -734,8 +867,12 @@ namespace xAiModels.Providers
// Checking Resources ...
//
// Titles ...
#region Titles ...
//
var titleResource = string.Empty;
//
// Locales ...
if (!item.TitleResource.IsNullOrDefault() &&
item.TitleResource.Locales.HasChild())
{
@@ -777,6 +914,32 @@ namespace xAiModels.Providers
}
}
//
// Title ...
if (!item.Title.IsNullOrEmpty() &&
titleResource.IsNullOrEmpty() &&
item.TitleResource.IsNullOrDefault())
{
//
var resource = await conversationTitleResourceProvider.AddOrUpdateLocale(
locale: new XLocaleResourceDto
{
Value = item.Title,
Language = defaultLanguage,
},
owner: ownerId,
identifier: result.Id,
connectionId: connectionId,
cancellationToken: cancellationToken
);
if (!resource.IsNullOrDefault() &&
titleResource.IsNullOrEmpty())
{
titleResource = resource.Resource;
}
}
#endregion
//
// Update Data ...
result.Title = titleResource;
@@ -811,7 +974,7 @@ namespace xAiModels.Providers
);
}
}
//
//`
// Check Default Conversation ...
else
{
+1 -1
View File
@@ -25,7 +25,6 @@
<!-- Local Modules -->
<ItemGroup>
<!-- <PackageReference Include="xDashboard.xStringService" Version="1.0.0" /> -->
</ItemGroup>
<!-- Local Dependencies -->
@@ -36,6 +35,7 @@
<!-- Dependencies -->
<ItemGroup>
<PackageReference Include="OpenAI" Version="2.14.0" />
<PackageReference Include="TimeZoneConverter" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.AI" Version="10.4.1" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.10.0" />
</ItemGroup>