290 lines
8.2 KiB
C#
290 lines
8.2 KiB
C#
using System;
|
|
using System.Threading;
|
|
using xAiModels.Models;
|
|
using Newtonsoft.Json.Linq;
|
|
using xAiService.Interfaces;
|
|
using System.Threading.Tasks;
|
|
using System.Collections.Generic;
|
|
using xIdentityModels.Models;
|
|
using xCommons.Extensions;
|
|
using System.Linq;
|
|
using xIdentityService.Interfaces;
|
|
|
|
namespace xAiService.Services
|
|
{
|
|
public class XAiMcpHandler : IXAiMcpHandler
|
|
{
|
|
//
|
|
private readonly XAiMcpToolScanner scanner;
|
|
private readonly IXPolicyHandler policyHandler;
|
|
private readonly IXAiMcpUserContext userContext;
|
|
private readonly IServiceProvider serviceProvider;
|
|
private readonly Dictionary<string, XAiMcpToolDescriptor> tools = new();
|
|
|
|
public XAiMcpHandler(
|
|
XAiMcpToolScanner scanner,
|
|
IXPolicyHandler policyHandler,
|
|
IXAiMcpUserContext userContext,
|
|
IServiceProvider serviceProvider
|
|
)
|
|
{
|
|
//
|
|
this.scanner = scanner;
|
|
this.userContext = userContext;
|
|
this.policyHandler = policyHandler;
|
|
this.serviceProvider = serviceProvider;
|
|
|
|
//
|
|
RegisterTools();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Process Specified JSON-RPC Request ...
|
|
/// </summary>
|
|
/// <param name="request"></param>
|
|
/// <param name="userInfo"></param>
|
|
/// <param name="connectionId"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
public async Task<JObject> ProcessAsync(
|
|
JObject request,
|
|
string connectionId = null,
|
|
XUserClaimsInfoDto userInfo = null,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Filling User Context ...
|
|
userContext.Set(userInfo, connectionId);
|
|
|
|
//
|
|
try
|
|
{
|
|
//
|
|
var id = request["id"];
|
|
var method = request["method"]?.ToString();
|
|
|
|
//
|
|
return method switch
|
|
{
|
|
"initialize" => HandleInitialize(id),
|
|
"tools/list" => HandleToolsList(id, userInfo),
|
|
"tools/call" => await HandleToolCallAsync(request, id, userInfo, cancellationToken),
|
|
"ping" => HandlePing(id),
|
|
_ => CreateError(id, -32601, $"Method not found: {method}")
|
|
};
|
|
}
|
|
finally
|
|
{
|
|
userContext.Clear();
|
|
}
|
|
}
|
|
|
|
//
|
|
#region Private ...
|
|
private JObject HandleInitialize(JToken id)
|
|
{
|
|
return CreateResult(id, new JObject
|
|
{
|
|
["protocolVersion"] = "2024-11-05",
|
|
["capabilities"] = new JObject
|
|
{
|
|
["tools"] = new JObject { ["listChanged"] = true }
|
|
},
|
|
["serverInfo"] = new JObject
|
|
{
|
|
["name"] = "xAiMcpServer",
|
|
["version"] = "1.0.0"
|
|
}
|
|
});
|
|
}
|
|
|
|
private JObject HandleToolsList(
|
|
JToken id,
|
|
XUserClaimsInfoDto userInfo
|
|
)
|
|
{
|
|
var jsonTools = new JArray();
|
|
foreach (var tool in tools.Values)
|
|
{
|
|
//
|
|
if (!tool.RequiredPolicy.IsNullOrEmpty() &&
|
|
!CheckPolicy(userInfo, tool.RequiredPolicy))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
//
|
|
jsonTools.Add(new JObject
|
|
{
|
|
["name"] = tool.Name,
|
|
["description"] = tool.Description,
|
|
["inputSchema"] = tool.InputSchema
|
|
});
|
|
}
|
|
|
|
//
|
|
return CreateResult(id, new JObject { ["tools"] = jsonTools });
|
|
}
|
|
|
|
private async Task<JObject> HandleToolCallAsync(
|
|
JObject request,
|
|
JToken id,
|
|
XUserClaimsInfoDto userInfo,
|
|
CancellationToken ct
|
|
)
|
|
{
|
|
//
|
|
var toolName = request["params"]?["name"]?.ToString();
|
|
var args = request["params"]?["arguments"] as JObject;
|
|
|
|
//
|
|
if (!tools.ContainsKey(toolName))
|
|
{
|
|
return CreateError(id, -32602, $"Tool not found: {toolName}");
|
|
}
|
|
|
|
//
|
|
var tool = tools[toolName];
|
|
|
|
//
|
|
// Check User Info Required or not ...
|
|
|
|
//
|
|
// Level 1 ...
|
|
if (userInfo.IsNull() && tool.RequiresAuthentication)
|
|
{
|
|
return CreateError(id, -32001, $"Authentication required for tool: {toolName}");
|
|
}
|
|
|
|
//
|
|
// Level 2 ...
|
|
if (!tool.RequiredPolicy.IsNullOrEmpty() &&
|
|
!CheckPolicy(userInfo, tool.RequiredPolicy))
|
|
{
|
|
return CreateError(id, -32002, $"Access denied for tool: {toolName}");
|
|
}
|
|
|
|
//
|
|
var result = await tool.Execute(args, ct);
|
|
return CreateResult(id, new JObject
|
|
{
|
|
["content"] = new JArray
|
|
{
|
|
new JObject
|
|
{
|
|
["type"] = "text",
|
|
["text"] = result
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
private JObject CreateResult(
|
|
JToken id,
|
|
JObject result
|
|
)
|
|
{
|
|
//
|
|
return new JObject
|
|
{
|
|
["jsonrpc"] = "2.0",
|
|
["id"] = id,
|
|
["result"] = result
|
|
};
|
|
}
|
|
|
|
private JObject CreateError(
|
|
JToken id,
|
|
int code,
|
|
string message
|
|
)
|
|
{
|
|
//
|
|
return new JObject
|
|
{
|
|
["jsonrpc"] = "2.0",
|
|
["id"] = id,
|
|
["error"] = new JObject
|
|
{
|
|
["code"] = code,
|
|
["message"] = message
|
|
}
|
|
};
|
|
}
|
|
|
|
private void RegisterTools()
|
|
{
|
|
//
|
|
// 1) Manually Register Tools ...
|
|
RegisterManualTools();
|
|
|
|
//
|
|
// 2) Register Scanned Tools uding Reflection ...
|
|
foreach (var blueprint in scanner.Blueprints)
|
|
{
|
|
//
|
|
// Prevent Double Registration if Name Exists ...
|
|
if (tools.ContainsKey(blueprint.Name))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
//
|
|
tools[blueprint.Name] = blueprint.ToDescriptor(serviceProvider);
|
|
}
|
|
}
|
|
|
|
private void RegisterManualTools()
|
|
{
|
|
// Manually Tools Registration ...
|
|
// tools["search_knowledge"] = new XAiMcpToolDescriptor
|
|
// {
|
|
// Name = "search_knowledge",
|
|
// Description = "Search in knowledge base",
|
|
// InputSchema = new JObject
|
|
// {
|
|
// ["type"] = "object",
|
|
// ["properties"] = new JObject
|
|
// {
|
|
// ["query"] = new JObject { ["type"] = "string" }
|
|
// },
|
|
// ["required"] = new JArray("query")
|
|
// },
|
|
// Execute = async (args, ct) =>
|
|
// {
|
|
// var query = args?["query"]?.ToString() ?? "";
|
|
// return $"Results for: {query}";
|
|
// }
|
|
// };
|
|
}
|
|
|
|
private JObject HandlePing(JToken id)
|
|
{
|
|
return CreateResult(id, new JObject());
|
|
}
|
|
|
|
private bool CheckPolicy(XUserClaimsInfoDto user, string policy)
|
|
{
|
|
//
|
|
var result = false;
|
|
|
|
//
|
|
if (user.IsNullOrDefault())
|
|
{
|
|
return result;
|
|
}
|
|
|
|
//
|
|
// Handle Authorization ...
|
|
result = policyHandler.IsPolicyPassed(
|
|
policy: policy,
|
|
roles: user.Roles
|
|
);
|
|
|
|
//
|
|
return result;
|
|
}
|
|
#endregion
|
|
}
|
|
} |