last Modules Update ...
This commit is contained in:
+169
-69
@@ -66,6 +66,7 @@ using Newtonsoft.Json.Serialization;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using IdentityModel.AspNetCore.OAuth2Introspection;
|
||||
using xAiService.DI;
|
||||
|
||||
namespace xAiApi
|
||||
{
|
||||
@@ -237,6 +238,10 @@ namespace xAiApi
|
||||
// Register Chat With Documents Services (Text Chunker + In-Memory Vector Store) ...
|
||||
services.AddXAiChatWithDocuments();
|
||||
|
||||
//
|
||||
// Register XAiMcpClient ...
|
||||
services.AddXAiMcpClient();
|
||||
|
||||
//
|
||||
// Persistent RAG (Knowledge over XAiVector Table) ...
|
||||
services.AddXRagService();
|
||||
@@ -3687,6 +3692,28 @@ namespace xAiApi.Extensions
|
||||
return result;
|
||||
}
|
||||
|
||||
// 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;
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3903,6 +3930,7 @@ using System.Linq.Expressions;
|
||||
using xAiModels.Models.Entities;
|
||||
using System.Collections.Generic;
|
||||
using ModelContextProtocol.Client;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace xAiApi.Interfaces
|
||||
{
|
||||
@@ -3920,7 +3948,7 @@ namespace xAiApi.Interfaces
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<IList<McpClientTool>> GetAvailableToolsAsync(
|
||||
Task<IList<AITool>> GetAvailableToolsAsync(
|
||||
bool forceOwner = false,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -3930,11 +3958,13 @@ namespace xAiApi.Interfaces
|
||||
/// Test Specified Mcp Server ...
|
||||
/// </summary>
|
||||
/// <param name="server"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<string> TestServerAsync(
|
||||
XAiMcpServerDto server,
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
@@ -4368,6 +4398,8 @@ namespace xAiApi.Interfaces
|
||||
/// <param name="projectId"></param>
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="extractFileContents"></param>
|
||||
/// <param name="addFilesToKnowledge"></param>
|
||||
/// <param name="files"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
@@ -4380,6 +4412,8 @@ namespace xAiApi.Interfaces
|
||||
Guid? projectId = null,
|
||||
Guid? conversationId = null,
|
||||
string connectionId = null,
|
||||
bool extractFileContents = false,
|
||||
bool addFilesToKnowledge = true,
|
||||
IFormFileCollection files = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -4395,6 +4429,8 @@ namespace xAiApi.Interfaces
|
||||
/// <param name="projectId"></param>
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="extractFileContents"></param>
|
||||
/// <param name="addFilesToKnowledge"></param>
|
||||
/// <param name="files"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
@@ -4407,6 +4443,8 @@ namespace xAiApi.Interfaces
|
||||
Guid? projectId = null,
|
||||
Guid? conversationId = null,
|
||||
string connectionId = null,
|
||||
bool extractFileContents = false,
|
||||
bool addFilesToKnowledge = true,
|
||||
IFormFileCollection files = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -7038,23 +7076,24 @@ using System.Threading;
|
||||
using System.Text.Json;
|
||||
using xAiApi.Interfaces;
|
||||
using xCommons.Providers;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using xAiModels.Constants;
|
||||
using xAiService.Services;
|
||||
using xAiModels.Extensions;
|
||||
using xAiService.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xAiModels.Models.Dtos;
|
||||
using xIdentityModels.Models;
|
||||
using System.Threading.Tasks;
|
||||
using System.Linq.Expressions;
|
||||
using xCommons.Configurations;
|
||||
using Microsoft.Extensions.AI;
|
||||
using xAiModels.Providers.Hubs;
|
||||
using xAiModels.Models.Entities;
|
||||
using xAiModels.Interfaces.Dtos;
|
||||
using xIdentityHelper.Extensions;
|
||||
using System.Collections.Generic;
|
||||
using xIdentityService.Interfaces;
|
||||
using ModelContextProtocol.Client;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using xAiModels.Interfaces.Entities;
|
||||
@@ -7068,6 +7107,10 @@ namespace xAiApi.Providers
|
||||
/// </summary>
|
||||
public class XAiMcpServerProvider : IXAiMcpServerProvider, IAsyncDisposable
|
||||
{
|
||||
//
|
||||
private readonly XAiMcpSessionStore sessionStore;
|
||||
private readonly XAiMcpHttpTransport mcpTransport;
|
||||
|
||||
//
|
||||
private readonly XAppConfiguration configuration;
|
||||
private readonly IHubContext<XAiDataProviderHub> hub;
|
||||
@@ -7081,15 +7124,17 @@ namespace xAiApi.Providers
|
||||
//
|
||||
private readonly ConcurrentDictionary<Guid, XAiMcpServerDto> mcpServers = [];
|
||||
private readonly ConcurrentDictionary<(Guid, string), DateTime> clientExpirations = new();
|
||||
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), McpClient> clients = new();
|
||||
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<McpClientTool>> tools = new();
|
||||
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), XAiMcpClient> clients = new();
|
||||
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), IList<AITool>> tools = new();
|
||||
|
||||
//
|
||||
private bool isInitialized = false;
|
||||
private readonly SemaphoreSlim initLock = new(1, 1);
|
||||
|
||||
public XAiMcpServerProvider(
|
||||
XAiMcpSessionStore sessionStore,
|
||||
XAppConfiguration configuration,
|
||||
XAiMcpHttpTransport mcpTransport,
|
||||
IHubContext<XAiDataProviderHub> hub,
|
||||
IXIdentityProvider identityProvider,
|
||||
ILogger<XAiMcpServerProvider> logger,
|
||||
@@ -7103,6 +7148,8 @@ namespace xAiApi.Providers
|
||||
//
|
||||
this.hub = hub;
|
||||
this.logger = logger;
|
||||
this.sessionStore = sessionStore;
|
||||
this.mcpTransport = mcpTransport;
|
||||
this.identityProvider = identityProvider;
|
||||
this.mcpServerEnricher = mcpServerEnricher;
|
||||
this.validationProvider = validationProvider;
|
||||
@@ -7133,7 +7180,7 @@ namespace xAiApi.Providers
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<IList<McpClientTool>> GetAvailableToolsAsync(
|
||||
public async Task<IList<AITool>> GetAvailableToolsAsync(
|
||||
bool forceOwner = false,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -7237,11 +7284,13 @@ namespace xAiApi.Providers
|
||||
/// Test Specified Mcp Server ...
|
||||
/// </summary>
|
||||
/// <param name="server"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> TestServerAsync(
|
||||
XAiMcpServerDto server,
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -7254,8 +7303,8 @@ namespace xAiApi.Providers
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(server.TimeoutSeconds));
|
||||
|
||||
//
|
||||
var client = await CreateClientAsync(server, userInfo, cts.Token);
|
||||
await client.PingAsync(cancellationToken: cts.Token);
|
||||
var client = CreateClientAsync(server, connectionId, userInfo);
|
||||
// await client.PingAsync(cancellationToken: cts.Token);
|
||||
var serverTools = await client.ListToolsAsync(cancellationToken: cts.Token);
|
||||
|
||||
//
|
||||
@@ -7394,7 +7443,7 @@ namespace xAiApi.Providers
|
||||
{
|
||||
//
|
||||
mcpServers[result.Id] = result;
|
||||
await ConnectAndValidateAsync(result, userInfo, cancellationToken);
|
||||
await ConnectAndValidateAsync(result, connectionId, userInfo);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -7577,7 +7626,7 @@ namespace xAiApi.Providers
|
||||
|
||||
//
|
||||
// Reconnect ...
|
||||
await ConnectAndValidateAsync(result, userInfo, cancellationToken);
|
||||
await ConnectAndValidateAsync(result, connectionId, userInfo, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -7896,7 +7945,7 @@ namespace xAiApi.Providers
|
||||
{
|
||||
//
|
||||
mcpServers[exists.Id] = exists;
|
||||
await ConnectAndValidateAsync(exists, userInfo, cancellationToken);
|
||||
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -7987,7 +8036,7 @@ namespace xAiApi.Providers
|
||||
{
|
||||
//
|
||||
mcpServers[exists.Id] = exists;
|
||||
await ConnectAndValidateAsync(exists, userInfo, cancellationToken);
|
||||
await ConnectAndValidateAsync(exists, connectionId, userInfo, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -8323,41 +8372,23 @@ namespace xAiApi.Providers
|
||||
=> json.IsNullOrEmpty() ? null
|
||||
: JsonSerializer.Deserialize<List<string>>(json);
|
||||
|
||||
private async Task<McpClient> CreateClientAsync(
|
||||
private XAiMcpClient CreateClientAsync(
|
||||
XAiMcpServerDto descriptor,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null
|
||||
)
|
||||
{
|
||||
//
|
||||
// Descriptor Headers ...
|
||||
var headers = ParseJsonDict(descriptor.Headers) ?? [];
|
||||
|
||||
//
|
||||
// Attach User Info ...
|
||||
if (!userInfo.IsNull() && !userInfo.AccessToken.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
headers[XAuthorization.ExpiresAt] = $"${userInfo.ExpiresAt}";
|
||||
headers[XAuthorization.RefreshToken] = $"${userInfo.RefreshToken}";
|
||||
headers[XAuthorization.XPoweredBy] = $"{configuration.XPoweredValue}";
|
||||
headers[XAuthorization.Header] = $"${XAuthorization.TokenIdentifier} {userInfo.AccessToken}";
|
||||
}
|
||||
|
||||
//
|
||||
// Initialize Transport ...
|
||||
var transport = new HttpClientTransport(new HttpClientTransportOptions
|
||||
{
|
||||
AdditionalHeaders = headers,
|
||||
Endpoint = new Uri(descriptor.Endpoint),
|
||||
TransportMode = HttpTransportMode.AutoDetect
|
||||
});
|
||||
|
||||
//
|
||||
var result = await McpClient
|
||||
.CreateAsync(
|
||||
transport,
|
||||
cancellationToken: cancellationToken);
|
||||
var result = new XAiMcpClient(
|
||||
logger: logger,
|
||||
userInfo: userInfo,
|
||||
transport: mcpTransport,
|
||||
serverId: descriptor.Id,
|
||||
sessionStore: sessionStore,
|
||||
connectionId: connectionId,
|
||||
appConfiguration: configuration,
|
||||
endpoint: new Uri(descriptor.Endpoint)
|
||||
);
|
||||
|
||||
//
|
||||
return result;
|
||||
@@ -8365,6 +8396,7 @@ namespace xAiApi.Providers
|
||||
|
||||
private async Task ConnectAndValidateAsync(
|
||||
XAiMcpServerDto descriptor,
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -8379,31 +8411,26 @@ namespace xAiApi.Providers
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(descriptor.TimeoutSeconds));
|
||||
|
||||
//
|
||||
// Create Client ...
|
||||
var client = await CreateClientAsync(
|
||||
userInfo: userInfo,
|
||||
descriptor: descriptor,
|
||||
cancellationToken: cts.Token
|
||||
var client = CreateClientAsync(
|
||||
userInfo: userInfo,
|
||||
descriptor: descriptor,
|
||||
connectionId: connectionId
|
||||
);
|
||||
|
||||
//
|
||||
// Ping Server ...
|
||||
await client.PingAsync(cancellationToken: cts.Token);
|
||||
await client.InitializeAsync(cts.Token);
|
||||
|
||||
//
|
||||
// Retrieve Server Tools ...
|
||||
var serverTools = await client
|
||||
.ListToolsAsync(
|
||||
cancellationToken: cts.Token
|
||||
);
|
||||
var clientTools = await client.ListToolsAsync(cts.Token);
|
||||
var aiTools = clientTools.ToAITools(client);
|
||||
|
||||
//
|
||||
// Key for Cache ...
|
||||
var key = (descriptor.Id, userInfo.UserId);
|
||||
|
||||
//
|
||||
tools[key] = aiTools;
|
||||
clients[key] = client;
|
||||
tools[key] = serverTools;
|
||||
mcpServers[descriptor.Id] = descriptor;
|
||||
clientExpirations[key] = DateTime.UtcNow.AddMinutes(15);
|
||||
|
||||
@@ -8411,17 +8438,16 @@ namespace xAiApi.Providers
|
||||
logger.LogInformation(
|
||||
"MCP '{Name}': {Count} Tools Detected for {UserId} ...",
|
||||
descriptor.Name,
|
||||
serverTools.Count,
|
||||
aiTools.Count,
|
||||
userInfo.UserId
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
} catch(Exception ex)
|
||||
{
|
||||
//
|
||||
logger.LogWarning(ex,
|
||||
"MCP '{Name}': Connection Established Failed, Ignored ...",
|
||||
descriptor.Name
|
||||
);
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9687,6 +9713,7 @@ using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xAiApi.Interfaces.Extractors;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.IO;
|
||||
|
||||
namespace xAiApi.Providers
|
||||
{
|
||||
@@ -10049,7 +10076,10 @@ namespace xAiApi.Providers
|
||||
connectionId: null,
|
||||
conversationId: null,
|
||||
persistPrompt: false,
|
||||
additionalContents: null,
|
||||
addFilesToKnowledge: false,
|
||||
resolveConversation: false,
|
||||
extractFileContents: false,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
@@ -10130,7 +10160,10 @@ namespace xAiApi.Providers
|
||||
connectionId: null,
|
||||
conversationId: null,
|
||||
persistPrompt: false,
|
||||
additionalContents: null,
|
||||
resolveConversation: false,
|
||||
addFilesToKnowledge: false,
|
||||
extractFileContents: false,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
@@ -10182,6 +10215,8 @@ namespace xAiApi.Providers
|
||||
/// <param name="projectId"></param>
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="extractFileContents"></param>
|
||||
/// <param name="addFilesToKnowledge"></param>
|
||||
/// <param name="files"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
@@ -10194,6 +10229,8 @@ namespace xAiApi.Providers
|
||||
Guid? projectId = null,
|
||||
Guid? conversationId = null,
|
||||
string connectionId = null,
|
||||
bool extractFileContents = false,
|
||||
bool addFilesToKnowledge = true,
|
||||
IFormFileCollection files = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -10218,10 +10255,13 @@ namespace xAiApi.Providers
|
||||
userInfo: userInfo,
|
||||
persistPrompt: true,
|
||||
projectId: projectId,
|
||||
additionalContents: null,
|
||||
resolveConversation: true,
|
||||
connectionId: connectionId,
|
||||
conversationId: conversationId,
|
||||
cancellationToken: cancellationToken
|
||||
cancellationToken: cancellationToken,
|
||||
extractFileContents: extractFileContents,
|
||||
addFilesToKnowledge: addFilesToKnowledge
|
||||
);
|
||||
|
||||
//
|
||||
@@ -10285,6 +10325,8 @@ namespace xAiApi.Providers
|
||||
/// <param name="projectId"></param>
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="extractFileContents"></param>
|
||||
/// <param name="addFilesToKnowledge"></param>
|
||||
/// <param name="files"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
@@ -10297,6 +10339,8 @@ namespace xAiApi.Providers
|
||||
Guid? projectId = null,
|
||||
Guid? conversationId = null,
|
||||
string connectionId = null,
|
||||
bool extractFileContents = false,
|
||||
bool addFilesToKnowledge = true,
|
||||
IFormFileCollection files = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
[EnumeratorCancellation]
|
||||
@@ -10322,10 +10366,13 @@ namespace xAiApi.Providers
|
||||
userInfo: userInfo,
|
||||
persistPrompt: true,
|
||||
projectId: projectId,
|
||||
additionalContents: null,
|
||||
resolveConversation: true,
|
||||
connectionId: connectionId,
|
||||
conversationId: conversationId,
|
||||
cancellationToken: cancellationToken
|
||||
cancellationToken: cancellationToken,
|
||||
extractFileContents: extractFileContents,
|
||||
addFilesToKnowledge: addFilesToKnowledge
|
||||
);
|
||||
|
||||
//
|
||||
@@ -10999,7 +11046,7 @@ namespace xAiApi.Providers
|
||||
if (!datetimeContext.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
systemText +=
|
||||
systemText +=
|
||||
$"{datetimeContext}{Environment.NewLine}{Environment.NewLine}";
|
||||
}
|
||||
|
||||
@@ -11125,17 +11172,20 @@ namespace xAiApi.Providers
|
||||
/// <summary>
|
||||
/// Retrieve Prepared Chat Context ...
|
||||
/// </summary>
|
||||
/// <param name="prompt"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="topK"></param>
|
||||
/// <param name="type"></param>
|
||||
/// <param name="prompt"></param>
|
||||
/// <param name="minScore"></param>
|
||||
/// <param name="projectId"></param>
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="persistPrompt"></param>
|
||||
/// <param name="connectionId"></param>
|
||||
/// <param name="conversationId"></param>
|
||||
/// <param name="resolveConversation"></param>
|
||||
/// <param name="files"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="resolveConversation"></param>
|
||||
/// <param name="persistPrompt"></param>
|
||||
/// <param name="extractFileContents"></param>
|
||||
/// <param name="addFilesToKnowledge"></param>
|
||||
/// <param name="additionalContents"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<XPreparedChatContext> PrepareChatRequirementsAsync(
|
||||
@@ -11150,6 +11200,8 @@ namespace xAiApi.Providers
|
||||
bool resolveConversation,
|
||||
IFormFileCollection files,
|
||||
XUserClaimsInfoDto userInfo,
|
||||
bool extractFileContents = true,
|
||||
bool addFilesToKnowledge = false,
|
||||
IList<AIContent> additionalContents = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -11240,7 +11292,8 @@ namespace xAiApi.Providers
|
||||
// Ingest Files if Provided and also Resolve Conversation Flagged ...
|
||||
if (
|
||||
files.HasChild() &&
|
||||
resolveConversation
|
||||
resolveConversation &&
|
||||
addFilesToKnowledge
|
||||
)
|
||||
{
|
||||
//
|
||||
@@ -11283,6 +11336,53 @@ namespace xAiApi.Providers
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// If there isn't Files need to add Files to Knowledge ...
|
||||
if (files.HasChild() &&
|
||||
!addFilesToKnowledge
|
||||
)
|
||||
{
|
||||
//
|
||||
// Extract File Content and add them to Additional Contents ...
|
||||
foreach (var file in files)
|
||||
{
|
||||
//
|
||||
var mimeType = file.ContentType?.ToLowerInvariant() ?? string.Empty;
|
||||
if (mimeType.IsNullOrEmpty() ||
|
||||
!fileContentExtractor.CanExtract(mimeType))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
//
|
||||
using var stream = file.OpenReadStream();
|
||||
|
||||
//
|
||||
// Extract File Content if necessary ...
|
||||
if (extractFileContents)
|
||||
{
|
||||
//
|
||||
var content = await fileContentExtractor.ExtractAsync(
|
||||
fileStream: stream,
|
||||
mimeType: mimeType,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
if (!content.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
var fileContent = new TextContent($"File:{Environment.NewLine}{file.FileName}{Environment.NewLine}{content}");
|
||||
additionalContents = [.. additionalContents, fileContent];
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//
|
||||
var fileContent = await DataContent.LoadFromAsync(stream, mimeType, cancellationToken);
|
||||
additionalContents = [.. additionalContents, fileContent];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Request Knowledge ...
|
||||
var knowledgeRequest = new XAiKnowledgeAskRequest
|
||||
+28
@@ -311,6 +311,34 @@ namespace xAiApi.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\Controllers\TestIdentity.cs
|
||||
|
||||
using xCommons.Providers;
|
||||
using xCommons.Configurations;
|
||||
using xIdentityHelper.Controllers;
|
||||
using xIdentityService.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xAiMcpServer.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// Test all Authentication Policies ...
|
||||
/// </summary>
|
||||
public class TestIdentity : XTestIdentityControllerBase {
|
||||
public TestIdentity (
|
||||
ILogger<TestIdentity> logger,
|
||||
XAppConfiguration appConfiguration,
|
||||
IXIdentityProvider identityProvider,
|
||||
XValidationProvider validationProvider
|
||||
) : base (
|
||||
logger,
|
||||
appConfiguration,
|
||||
identityProvider,
|
||||
validationProvider
|
||||
) { }
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\xAiMcpServer\DI\DiExtensions.cs
|
||||
|
||||
using System.Linq;
|
||||
+333
@@ -379,6 +379,51 @@ namespace xAiModels.Constants
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpConstants.cs
|
||||
|
||||
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 = "";
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpMethods.cs
|
||||
|
||||
using xExceptions.Attributes;
|
||||
|
||||
namespace xAiModels.Constants
|
||||
{
|
||||
public enum XAiMcpMethods
|
||||
{
|
||||
[StringValue("initialize")]
|
||||
Initialize,
|
||||
|
||||
[StringValue("tools/list")]
|
||||
ToolsList,
|
||||
|
||||
[StringValue("tools/call")]
|
||||
ToolsCall,
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Constants\XAiMcpServerUsageScope.cs
|
||||
|
||||
using xExceptions.Attributes;
|
||||
@@ -1778,6 +1823,36 @@ 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1915,6 +1990,172 @@ namespace xAiModels.Helpers
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpHeaderBuilder.cs
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiMcpSseReader.cs
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Helpers\XAiModelsHelper.cs
|
||||
|
||||
using System;
|
||||
@@ -4797,6 +5038,98 @@ namespace xAiModels.Interfaces.Entities
|
||||
{ }
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcError.cs
|
||||
|
||||
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; }
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcRequest.cs
|
||||
|
||||
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; }
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpJsonRpcResponse.cs
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDefinition.cs
|
||||
|
||||
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; }
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiModels\Models\XAiMcpToolDescriptor.cs
|
||||
|
||||
using System;
|
||||
+687
-1
@@ -125,10 +125,46 @@ namespace xAiService.Controllers
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\DI\XDIHelperExtension.cs
|
||||
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using xAiModels.Constants;
|
||||
using xAiService.Services;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace xAiService.DI
|
||||
{
|
||||
public static partial class XDIHelperExtension
|
||||
{ }
|
||||
{
|
||||
/// <summary>
|
||||
/// Register XAiMcpClient in DI ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
public static void AddXAiMcpClient(
|
||||
this IServiceCollection source
|
||||
)
|
||||
{
|
||||
//
|
||||
// Register Http Client ...
|
||||
source.AddHttpClient(
|
||||
XAiMcpConstants.XAiMcpClientName,
|
||||
client =>
|
||||
{
|
||||
client.Timeout = Timeout.InfiniteTimeSpan;
|
||||
}
|
||||
)
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
|
||||
{
|
||||
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
|
||||
});
|
||||
|
||||
//
|
||||
source.AddScoped<XAiMcpHttpTransport>();
|
||||
source.AddSingleton<XAiMcpSessionStore>();
|
||||
|
||||
//
|
||||
source.AddHostedService<XAiMcpSessionCleanupService>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\DIExtensions.cs
|
||||
@@ -183,9 +219,13 @@ namespace xAiService.Extensions
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Extensions\XAiServiceExtensions.cs
|
||||
|
||||
using xAiModels.Models;
|
||||
using xCommons.Extensions;
|
||||
using xAiService.Services;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityModels.Models;
|
||||
using Microsoft.Extensions.AI;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace xAiService.Extensions
|
||||
{
|
||||
@@ -225,6 +265,36 @@ namespace xAiService.Extensions
|
||||
invalidException.Throw();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts To AITools ...
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="client"></param>
|
||||
/// <returns></returns>
|
||||
public static IList<AITool> ToAITools(
|
||||
this IList<XAiMcpToolDefinition> source,
|
||||
XAiMcpClient client
|
||||
)
|
||||
{
|
||||
//
|
||||
if (client.IsNullOrDefault())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = new List<AITool>();
|
||||
|
||||
//
|
||||
foreach (var tool in source)
|
||||
{
|
||||
result.Add(new XAiMcpAIFunction(client, tool));
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -540,6 +610,366 @@ namespace xAiService.Interfaces
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpAIFunction.cs
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// a Customized AIFunction Implementation ...
|
||||
/// </summary>
|
||||
public class XAiMcpAIFunction : AIFunction
|
||||
{
|
||||
//
|
||||
private readonly XAiMcpClient client;
|
||||
private readonly JsonElement jsonSchema;
|
||||
private readonly XAiMcpToolDefinition definition;
|
||||
|
||||
public XAiMcpAIFunction(
|
||||
XAiMcpClient client,
|
||||
XAiMcpToolDefinition definition
|
||||
)
|
||||
{
|
||||
//
|
||||
if (client.IsNull() || definition.IsNull())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
this.client = client;
|
||||
this.definition = definition;
|
||||
|
||||
//
|
||||
jsonSchema = definition.InputSchema.Clone();
|
||||
}
|
||||
|
||||
//
|
||||
public override string Name => definition.Name;
|
||||
public override JsonElement JsonSchema => jsonSchema;
|
||||
public override string Description => definition.Description;
|
||||
|
||||
/// <summary>
|
||||
/// Invoke Tool ...
|
||||
/// </summary>
|
||||
/// <param name="arguments"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
protected override async ValueTask<object> InvokeCoreAsync(
|
||||
AIFunctionArguments arguments,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var jsonArgs = ToJsonObject(arguments);
|
||||
return await client.CallToolAsync(
|
||||
definition.Name,
|
||||
jsonArgs,
|
||||
cancellationToken
|
||||
);
|
||||
}
|
||||
|
||||
private JsonObject ToJsonObject(AIFunctionArguments arguments)
|
||||
{
|
||||
//
|
||||
var result = new JsonObject();
|
||||
if (arguments.IsNull() ||
|
||||
arguments is null)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
foreach (var kvp in arguments)
|
||||
{
|
||||
result[kvp.Key] = JsonSerializer.SerializeToNode(kvp.Value);
|
||||
}
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpClient.cs
|
||||
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xAiModels.Helpers;
|
||||
using xAiModels.Constants;
|
||||
using xCommons.Extensions;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Threading.Tasks;
|
||||
using xIdentityModels.Models;
|
||||
using xCommons.Configurations;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpClient : IAsyncDisposable
|
||||
{
|
||||
//
|
||||
private readonly Uri endpoint;
|
||||
private readonly Guid serverId;
|
||||
private readonly ILogger logger;
|
||||
private readonly string connectionId;
|
||||
private readonly XUserClaimsInfoDto userInfo;
|
||||
private readonly XAiMcpHttpTransport transport;
|
||||
private readonly XAiMcpSessionStore sessionStore;
|
||||
private readonly XAppConfiguration appConfiguration;
|
||||
|
||||
//
|
||||
public string ServerName { get; private set; }
|
||||
public bool IsInitialized { get; private set; }
|
||||
public string ServerVersion { get; private set; }
|
||||
public string ProtocolVersion { get; private set; } = XAiMcpConstants.XAiMcpProtocol;
|
||||
|
||||
public XAiMcpClient(
|
||||
Uri endpoint,
|
||||
Guid serverId,
|
||||
ILogger logger,
|
||||
XAiMcpHttpTransport transport,
|
||||
XAiMcpSessionStore sessionStore,
|
||||
XAppConfiguration appConfiguration,
|
||||
string connectionId = null,
|
||||
XUserClaimsInfoDto userInfo = null
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
this.serverId = serverId;
|
||||
this.endpoint = endpoint;
|
||||
this.userInfo = userInfo;
|
||||
this.transport = transport;
|
||||
this.sessionStore = sessionStore;
|
||||
this.connectionId = connectionId;
|
||||
this.appConfiguration = appConfiguration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize MCP Server ...
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task InitializeAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//
|
||||
if (IsInitialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
var request = new XAiMcpJsonRpcRequest
|
||||
{
|
||||
Method = XAiMcpMethods.Initialize.GetStringValue(),
|
||||
Params = new
|
||||
{
|
||||
capabilities = new { tools = new { } },
|
||||
protocolVersion = XAiMcpConstants.XAiMcpProtocol,
|
||||
clientInfo = new {
|
||||
name = XAiMcpConstants.serverInfoNameValue,
|
||||
version = XAiMcpConstants.serverInfoVersionValue
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
var headers = XAiMcpHeaderBuilder.Build(
|
||||
userInfo: userInfo,
|
||||
connectionId: connectionId,
|
||||
appConfiguration: appConfiguration
|
||||
);
|
||||
|
||||
//
|
||||
var response = await transport
|
||||
.SendAsync(
|
||||
endpoint,
|
||||
headers,
|
||||
request,
|
||||
cancellationToken
|
||||
);
|
||||
if (!response.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException($"Initialize failed: {response.Error?.Message}");
|
||||
}
|
||||
|
||||
//
|
||||
var result = response.Result?.Deserialize<JsonElement>();
|
||||
if (result?.TryGetProperty(XAiMcpConstants.ProtocolVersionKey, out var pv) == true)
|
||||
{
|
||||
ProtocolVersion = pv.GetString() ?? ProtocolVersion;
|
||||
}
|
||||
if (result?.TryGetProperty(XAiMcpConstants.ServerInfoKey, out var si) == true)
|
||||
{
|
||||
//
|
||||
ServerName = si.TryGetProperty(XAiMcpConstants.ServerInfoNameKey, out var n) ? n.GetString() : null;
|
||||
ServerVersion = si.TryGetProperty(XAiMcpConstants.ServerInfoVersionKey, out var v) ? v.GetString() : null;
|
||||
}
|
||||
|
||||
//
|
||||
IsInitialized = true;
|
||||
logger.LogInformation(
|
||||
"MCP initialized: {Name} v{Version} (protocol {PV})",
|
||||
ServerName,
|
||||
ServerVersion,
|
||||
ProtocolVersion
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a List of Available Tools on Initialize MCP Server ...
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<IList<XAiMcpToolDefinition>> ListToolsAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
//
|
||||
await EnsureInitializedAsync(cancellationToken);
|
||||
|
||||
//
|
||||
var request = new XAiMcpJsonRpcRequest
|
||||
{
|
||||
Method = XAiMcpMethods.ToolsList.GetStringValue()
|
||||
};
|
||||
|
||||
//
|
||||
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
|
||||
var headers = XAiMcpHeaderBuilder.Build(
|
||||
userInfo: userInfo,
|
||||
appConfiguration: appConfiguration,
|
||||
connectionId: connectionId,
|
||||
sessionId: sessionId,
|
||||
protocolVersion: ProtocolVersion
|
||||
);
|
||||
|
||||
//
|
||||
var response = await transport
|
||||
.SendAsync(
|
||||
endpoint,
|
||||
headers,
|
||||
request,
|
||||
cancellationToken
|
||||
);
|
||||
if (!response.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException($"tools/list failed: {response.Error?.Message}");
|
||||
}
|
||||
|
||||
//
|
||||
var toolsArray = response.Result?.Deserialize<JsonElement>();
|
||||
if (toolsArray?.TryGetProperty("tools", out var tools) != true)
|
||||
{
|
||||
return new List<XAiMcpToolDefinition>();
|
||||
}
|
||||
|
||||
//
|
||||
return tools.Deserialize<List<XAiMcpToolDefinition>>() ?? new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call Specified Tools of MCP Server ...
|
||||
/// </summary>
|
||||
/// <param name="toolName"></param>
|
||||
/// <param name="arguments"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> CallToolAsync(
|
||||
string toolName,
|
||||
JsonObject arguments,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
await EnsureInitializedAsync(cancellationToken);
|
||||
|
||||
//
|
||||
var request = new XAiMcpJsonRpcRequest
|
||||
{
|
||||
Method = XAiMcpMethods.ToolsCall.GetStringValue(),
|
||||
Params = new
|
||||
{
|
||||
name = toolName,
|
||||
arguments = arguments ?? new JsonObject()
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
var sessionId = sessionStore.Get(serverId, userInfo.UserId);
|
||||
var headers = XAiMcpHeaderBuilder.Build(
|
||||
userInfo: userInfo,
|
||||
sessionId: sessionId,
|
||||
connectionId: connectionId,
|
||||
protocolVersion: ProtocolVersion,
|
||||
appConfiguration: appConfiguration
|
||||
);
|
||||
|
||||
//
|
||||
var response = await transport
|
||||
.SendAsync(
|
||||
endpoint,
|
||||
headers,
|
||||
request,
|
||||
cancellationToken
|
||||
);
|
||||
if (!response.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException($"tools/call failed: {response.Error?.Message}");
|
||||
}
|
||||
|
||||
//
|
||||
var result = response.Result?.Deserialize<JsonElement>();
|
||||
if (result?.TryGetProperty(XAiMcpConstants.ContentKey, out var content) == true &&
|
||||
content.ValueKind == JsonValueKind.Array &&
|
||||
content.GetArrayLength() > 0
|
||||
)
|
||||
{
|
||||
//
|
||||
var first = content[0];
|
||||
if (first.TryGetProperty(XAiMcpConstants.TextKey, out var text))
|
||||
{
|
||||
return text.GetString() ?? string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return result?.GetRawText() ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispose Instanced Client ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
//
|
||||
#region Private ...
|
||||
private async Task EnsureInitializedAsync(CancellationToken ct)
|
||||
{
|
||||
//
|
||||
if (!IsInitialized)
|
||||
{
|
||||
await InitializeAsync(ct);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHandler.cs
|
||||
|
||||
using System;
|
||||
@@ -833,6 +1263,262 @@ namespace xAiService.Services
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpHttpTransport.cs
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using xAiModels.Models;
|
||||
using xAiModels.Helpers;
|
||||
using xAiModels.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpHttpTransport
|
||||
{
|
||||
//
|
||||
private readonly IHttpClientFactory httpClientFactory;
|
||||
private readonly ILogger<XAiMcpHttpTransport> logger;
|
||||
|
||||
public XAiMcpHttpTransport(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ILogger<XAiMcpHttpTransport> logger
|
||||
)
|
||||
{
|
||||
//
|
||||
this.logger = logger;
|
||||
this.httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
public async Task<XAiMcpJsonRpcResponse> SendAsync(
|
||||
Uri endpoint,
|
||||
Dictionary<string, string> headers,
|
||||
XAiMcpJsonRpcRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
var client = httpClientFactory.CreateClient(XAiMcpConstants.XAiMcpClientName);
|
||||
client.Timeout = Timeout.InfiniteTimeSpan;
|
||||
|
||||
//
|
||||
using var httpRequest = new HttpRequestMessage(HttpMethod.Post, endpoint);
|
||||
|
||||
//
|
||||
// Add all Headers ...
|
||||
foreach (var header in headers)
|
||||
{
|
||||
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||
}
|
||||
|
||||
//
|
||||
// Prepare For Accepting SSE and JSON-RPC ...
|
||||
httpRequest.Headers.Accept.Clear();
|
||||
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
|
||||
|
||||
//
|
||||
var json = JsonSerializer.Serialize(request);
|
||||
httpRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
headers.TryGetValue(XAiMcpConstants.XAiMcpSessionIdentifier, out var sessionId);
|
||||
|
||||
//
|
||||
logger.LogDebug(
|
||||
"MCP → {Method} | {Url} | Session={Session}",
|
||||
request.Method,
|
||||
endpoint,
|
||||
sessionId
|
||||
);
|
||||
|
||||
//
|
||||
var response = await client
|
||||
.SendAsync(
|
||||
httpRequest,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
//
|
||||
var errorBody = await response.Content.ReadAsStringAsync();
|
||||
logger.LogError("MCP HTTP {Status} | {Body}", (int)response.StatusCode, errorBody);
|
||||
|
||||
//
|
||||
throw new HttpRequestException(
|
||||
$"MCP request failed: {response.StatusCode}. Body: {errorBody}");
|
||||
}
|
||||
|
||||
//
|
||||
// Content Type Detection ...
|
||||
var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/json";
|
||||
if (contentType.Contains("text/event-stream"))
|
||||
{
|
||||
//
|
||||
// SSE Answer ...
|
||||
var stream = await response.Content.ReadAsStreamAsync();
|
||||
await foreach (var data in XAiMcpSseReader.ReadAsync(stream, cancellationToken))
|
||||
{
|
||||
//
|
||||
var parsed = JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(data);
|
||||
if (parsed?.Id == request.Id || parsed?.Id is null)
|
||||
{
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
throw new InvalidOperationException("SSE stream ended without matching response.");
|
||||
}
|
||||
else
|
||||
{
|
||||
//
|
||||
// Simple JSON answer ...
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<XAiMcpJsonRpcResponse>(body);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionCleanupService.cs
|
||||
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpSessionCleanupService : BackgroundService
|
||||
{
|
||||
//
|
||||
private readonly XAiMcpSessionStore store;
|
||||
private readonly ILogger<XAiMcpSessionCleanupService> logger;
|
||||
|
||||
public XAiMcpSessionCleanupService(
|
||||
XAiMcpSessionStore store,
|
||||
ILogger<XAiMcpSessionCleanupService> logger
|
||||
)
|
||||
{
|
||||
//
|
||||
this.store = store;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
//
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
//
|
||||
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
|
||||
var removed = store.CleanupExpired();
|
||||
if (removed > 0)
|
||||
{
|
||||
//
|
||||
logger
|
||||
.LogInformation("MCP Session Cleanup: {Count} expired sessions removed", removed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpSessionStore.cs
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace xAiService.Services
|
||||
{
|
||||
public class XAiMcpSessionStore
|
||||
{
|
||||
//
|
||||
private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(15);
|
||||
private readonly ConcurrentDictionary<(Guid ServerId, string UserId), SessionEntry> sessions = new();
|
||||
|
||||
public string Get(
|
||||
Guid serverId,
|
||||
string userId
|
||||
)
|
||||
{
|
||||
//
|
||||
if (!sessions.TryGetValue((serverId, userId), out var entry))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
// Expriration Check ...
|
||||
if (DateTime.UtcNow - entry.LastAccessAt > Ttl)
|
||||
{
|
||||
//
|
||||
sessions.TryRemove((serverId, userId), out _);
|
||||
return null;
|
||||
}
|
||||
|
||||
//
|
||||
entry.LastAccessAt = DateTime.UtcNow;
|
||||
return entry.SessionId;
|
||||
}
|
||||
|
||||
public void Set(
|
||||
Guid serverId,
|
||||
string userId,
|
||||
string sessionId
|
||||
)
|
||||
{
|
||||
//
|
||||
sessions[(serverId, userId)] = new SessionEntry
|
||||
{
|
||||
SessionId = sessionId,
|
||||
LastAccessAt = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
public void Remove(
|
||||
Guid serverId,
|
||||
string userId
|
||||
) => sessions.TryRemove((serverId, userId), out _);
|
||||
|
||||
public int CleanupExpired()
|
||||
{
|
||||
//
|
||||
var count = 0;
|
||||
var now = DateTime.UtcNow;
|
||||
foreach (var kv in sessions)
|
||||
{
|
||||
//
|
||||
if (now - kv.Value.LastAccessAt > Ttl)
|
||||
{
|
||||
if (sessions.TryRemove(kv.Key, out _))
|
||||
{
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
return count;
|
||||
}
|
||||
|
||||
private class SessionEntry
|
||||
{
|
||||
public string SessionId { get; set; }
|
||||
public DateTime LastAccessAt { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xAiService\Services\XAiMcpToolBlueprint.cs
|
||||
|
||||
using System;
|
||||
Reference in New Issue
Block a user