diff --git a/Controllers/XAiMcpControllerBase.cs b/Controllers/XAiMcpControllerBase.cs index df16212..64ec1c7 100644 --- a/Controllers/XAiMcpControllerBase.cs +++ b/Controllers/XAiMcpControllerBase.cs @@ -9,10 +9,12 @@ using Microsoft.AspNetCore.Http; using xIdentityService.Interfaces; using Microsoft.Extensions.Logging; using xIdentityService.Controllers; +using Microsoft.AspNetCore.Authorization; namespace xAiService.Controllers { [Route("mcp")] + [AllowAnonymous] public abstract class XAiMcpControllerBase : XBaseIdentityApiV1Controller { private readonly IXAiMcpHandler mcpHandler; diff --git a/Extensions/DIExtensions.cs b/Extensions/DIExtensions.cs index 20aee46..5b0302a 100644 --- a/Extensions/DIExtensions.cs +++ b/Extensions/DIExtensions.cs @@ -1,3 +1,6 @@ +using System; +using System.Linq; +using System.Reflection; using xAiService.Services; using xAiService.Interfaces; using Microsoft.Extensions.DependencyInjection; @@ -14,6 +17,26 @@ namespace xAiService.Extensions this IServiceCollection source ) { + // + // Register MCP Tool Scanner ... + source.AddSingleton(sp => + { + // + // Scan All Exists Assemblies ... + var asms = AppDomain.CurrentDomain + .GetAssemblies() + .Where(a => !a.IsDynamic && + a.GetName().Name != null && + a.GetName().Name!.StartsWith("xAi", StringComparison.OrdinalIgnoreCase)) + .Append(Assembly.GetEntryAssembly()!) + .ToArray(); + + // + return new XAiMcpToolScanner(asms); + }); + + // + // 2) Register MCP Handler ... source.AddScoped(); } } diff --git a/Helpers/XAiMcpArgumentHelper.cs b/Helpers/XAiMcpArgumentHelper.cs new file mode 100644 index 0000000..a208c5b --- /dev/null +++ b/Helpers/XAiMcpArgumentHelper.cs @@ -0,0 +1,127 @@ +using System; +using Newtonsoft.Json.Linq; + +namespace xAiService.Helpers +{ + public static class XAiMcpArgumentHelper + { + /// + /// Bind Parameters ... + /// + /// + /// + /// + public static object Bind( + JToken token, + Type targetType + ) + { + // + var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; + + // + // Null Handling ... + if (token == null || token.Type == JTokenType.Null || token.Type == JTokenType.Undefined) + { + // + if (!targetType.IsValueType || Nullable.GetUnderlyingType(targetType) != null) + { + return null; + } + + // + return Activator.CreateInstance(targetType); + } + + // + // Primitive Types ... + + // + if (underlying == typeof(string)) + { + return token.ToString(); + } + + // + if (underlying == typeof(int)) + { + return token.Value(); + } + + // + if (underlying == typeof(long)) + { + return token.Value(); + } + + // + if (underlying == typeof(short)) + { + return token.Value(); + } + + // + if (underlying == typeof(float)) + { + return token.Value(); + } + + // + if (underlying == typeof(double)) + { + return token.Value(); + } + + // + if (underlying == typeof(decimal)) + { + return token.Value(); + } + + // + if (underlying == typeof(bool)) + { + return token.Value(); + } + + // + if (underlying == typeof(Guid)) + { + return token.Value(); + } + + // + if (underlying == typeof(DateTime)) + { + return token.Value(); + } + + // + // Enum ... + if (underlying.IsEnum) + { + return Enum.Parse(underlying, token.ToString(), ignoreCase: true); + } + + // + // Arrays ... + if (underlying.IsArray && token is JArray jarr) + { + // + var elementType = underlying.GetElementType(); + var arr = Array.CreateInstance(elementType, jarr.Count); + for (var i = 0; i < jarr.Count; i++) + { + arr.SetValue(Bind(jarr[i], elementType), i); + } + + // + return arr; + } + + // + // Fallback: JSON Deserialize + return token.ToObject(underlying); + } + } +} \ No newline at end of file diff --git a/Helpers/XAiMcpResultExtractionHelper.cs b/Helpers/XAiMcpResultExtractionHelper.cs new file mode 100644 index 0000000..87891cb --- /dev/null +++ b/Helpers/XAiMcpResultExtractionHelper.cs @@ -0,0 +1,105 @@ +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Helpers +{ + public static class XAiMcpResultExtractionHelper + { + /// + /// Extract Specified Object Result of Method Invoking ... + /// + /// + /// + /// + public static async Task ExtractAsync( + object raw, + Type returnType + ) + { + // + // Task / Task + if (raw is Task task) + { + // + await task.ConfigureAwait(false); + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(Task<>)) + { + // + var value = returnType.GetProperty("Result").GetValue(task); + return Format(value); + } + + // + return string.Empty; + } + + // + // ValueTask (non-generic) + if (returnType == typeof(ValueTask)) + { + // + await ((ValueTask)raw).ConfigureAwait(false); + return string.Empty; + } + + // + // ValueTask ... + if (returnType.IsGenericType && + returnType.GetGenericTypeDefinition() == typeof(ValueTask<>)) + { + // + var asTask = (Task)returnType.GetMethod("AsTask").Invoke(raw, null); + await asTask.ConfigureAwait(false); + var value = asTask.GetType().GetProperty("Result").GetValue(asTask); + + // + return Format(value); + } + + // + // void / T Syncron ... + return Format(raw); + } + + // + #region Private ... + /// + /// Format Extracted Response ... + /// /// + /// + /// + private static string Format(object value) + { + // + if (value == null) + { + return string.Empty; + } + + // + if (value is string s) + { + return s; + } + + // + if (value is JToken jt) + { + return jt.ToString(Formatting.None); + } + + // + if (value.GetType().IsPrimitive || value is decimal) + { + return value.ToString(); + } + + // + return JToken.FromObject(value).ToString(Formatting.None); + } + #endregion + } +} \ No newline at end of file diff --git a/Services/XAiMcpHandler.cs b/Services/XAiMcpHandler.cs index 43e150f..858511f 100644 --- a/Services/XAiMcpHandler.cs +++ b/Services/XAiMcpHandler.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using xAiModels.Models; using Newtonsoft.Json.Linq; @@ -9,10 +10,21 @@ namespace xAiService.Services { public class XAiMcpHandler : IXAiMcpHandler { + // + private readonly XAiMcpToolScanner scanner; + private readonly IServiceProvider serviceProvider; private readonly Dictionary tools = new(); - public XAiMcpHandler() + public XAiMcpHandler( + XAiMcpToolScanner scanner, + IServiceProvider serviceProvider + ) { + // + this.scanner = scanner; + this.serviceProvider = serviceProvider; + + // RegisterTools(); } @@ -146,25 +158,47 @@ namespace xAiService.Services private void RegisterTools() { // - tools["search_knowledge"] = new XAiMcpToolDescriptor + // 1) Manually Register Tools ... + RegisterManualTools(); + + // + // 2) Register Scanned Tools uding Reflection ... + foreach (var blueprint in scanner.Blueprints) { - Name = "search_knowledge", - Description = "Search in knowledge base", - InputSchema = new JObject + // + // Prevent Double Registration if Name Exists ... + if (tools.ContainsKey(blueprint.Name)) { - ["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}"; + 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) diff --git a/Services/XAiMcpToolBlueprint.cs b/Services/XAiMcpToolBlueprint.cs new file mode 100644 index 0000000..93e053e --- /dev/null +++ b/Services/XAiMcpToolBlueprint.cs @@ -0,0 +1,111 @@ +using System; +using xAiModels.Models; +using System.Threading; +using System.Reflection; +using xAiService.Helpers; +using Newtonsoft.Json.Linq; +using System.Threading.Tasks; + +namespace xAiService.Services +{ + public class XAiMcpToolBlueprint + { + public string Name { get; set; } + public string Description { get; set; } + public JObject InputSchema { get; set; } + + internal MethodInfo Method { get; set; } + internal Type DeclaringType { get; set; } + + /// + /// Create an Specific Descriptor which can Execute on Current IServiceProvider ... + /// + /// + /// + public XAiMcpToolDescriptor ToDescriptor(IServiceProvider serviceProvider) + { + // + var result = new XAiMcpToolDescriptor + { + Name = Name, + Description = Description, + InputSchema = InputSchema, + Execute = BuildExecute(serviceProvider) + }; + + // + return result; + } + + /// + /// Build Tools Execution for MCP Method ... + /// + /// + /// + private Func> BuildExecute( + IServiceProvider serviceProvider + ) + { + // + var method = Method; + var declaringType = DeclaringType; + return async (args, ct) => + { + // + try + { + // + // 1. Make/Retrieve Instance ... + var instance = method.IsStatic + ? null + : (serviceProvider.GetService(declaringType) + ?? Activator.CreateInstance(declaringType)); + + // + // 2. Binding Method Arguments ... + var parameters = method.GetParameters(); + var values = new object[parameters.Length]; + for (var i = 0; i < parameters.Length; i++) + { + // + var p = parameters[i]; + + // + // Handle CancellationToken Token ... + if (p.ParameterType == typeof(CancellationToken)) + { + values[i] = ct; + continue; + } + + // + // Retrieve Param Attribute ... + var attr = p.GetCustomAttribute(); + var jsonName = attr?.Name ?? p.Name; + values[i] = XAiMcpArgumentHelper.Bind(args?[jsonName], p.ParameterType); + } + + // + // 3. Invoke and Await ... + object raw; + try + { + raw = method.Invoke(instance, values); + } + catch (TargetInvocationException tie) when (tie.InnerException != null) + { + throw tie.InnerException; + } + + // + // 4. Extract Invoking Result ... + return await XAiMcpResultExtractionHelper.ExtractAsync(raw, method.ReturnType); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + }; + } + } +} \ No newline at end of file diff --git a/Services/XAiMcpToolScanner.cs b/Services/XAiMcpToolScanner.cs new file mode 100644 index 0000000..60a14e9 --- /dev/null +++ b/Services/XAiMcpToolScanner.cs @@ -0,0 +1,226 @@ +using System; +using System.Linq; +using System.Threading; +using System.Reflection; +using Newtonsoft.Json.Linq; +using xAiModels.Attributes; +using System.ComponentModel; +using System.Collections.Generic; + +namespace xAiService.Services +{ + public class XAiMcpToolScanner + { + private readonly Assembly[] assemblies; + private readonly Lazy> blueprints; + + public XAiMcpToolScanner(IEnumerable assemblies) + { + // + this.assemblies = assemblies? + .Where(a => a != null && !a.IsDynamic) + .Distinct() + .ToArray() ?? []; + + // + blueprints = new Lazy>( + Scan, + LazyThreadSafetyMode.ExecutionAndPublication + ); + } + + public IReadOnlyList Blueprints => blueprints.Value; + + // + #region Private ... + private IReadOnlyList Scan() + { + // + var result = new List(); + var seenNames = new HashSet(StringComparer.Ordinal); + foreach (var asm in assemblies) + { + // + foreach (var type in SafeGetTypes(asm)) + { + // + if (type.GetCustomAttribute() == null) { + continue; + } + + // + foreach (var method in type.GetMethods( + BindingFlags.Public | + BindingFlags.Instance | + BindingFlags.Static)) + { + // + var attr = method.GetCustomAttribute(); + if (attr == null) + { + continue; + } + + // + var name = string.IsNullOrWhiteSpace(attr.Name) + ? method.Name + : attr.Name.Trim(); + + if (!seenNames.Add(name)) + { + // + throw new InvalidOperationException( + $"Duplicate MCP tool name '{name}' detected in {type.FullName}.{method.Name}."); + } + + // + var description = attr.Description + ?? method.GetCustomAttribute()?.Description + ?? string.Empty; + + // + result.Add(new XAiMcpToolBlueprint + { + Name = name, + Method = method, + DeclaringType = type, + Description = description, + InputSchema = BuildInputSchema(method) + }); + } + } + } + + return result; + } + + private static JObject BuildInputSchema(MethodInfo method) + { + // + var properties = new JObject(); + var required = new JArray(); + + // + foreach (var p in method.GetParameters()) + { + // + // CancellationToken doesnt exists in Schema ... + if (p.ParameterType == typeof(CancellationToken)) + { + continue; + } + + // + var attr = p.GetCustomAttribute(); + var jsonName = attr?.Name ?? p.Name; + var description = attr?.Description + ?? p.GetCustomAttribute()?.Description + ?? string.Empty; + + // + var propSchema = new JObject + { + ["type"] = MapJsonType(p.ParameterType) + }; + + // + if (!string.IsNullOrWhiteSpace(description)) + { + propSchema["description"] = description; + } + + // + // Define Items Array ... + var underlying = Nullable.GetUnderlyingType(p.ParameterType) ?? p.ParameterType; + if (underlying.IsArray) + { + // + propSchema["items"] = new JObject + { + ["type"] = MapJsonType(underlying.GetElementType()) + }; + } + + // + properties[jsonName] = propSchema; + + // Check is Required ... + var isRequired = attr?.Required ?? true; + if (isRequired) + { + required.Add(jsonName); + } + } + + // + var result = new JObject + { + ["type"] = "object", + ["required"] = required, + ["properties"] = properties, + }; + + // + return result; + } + + private static string MapJsonType(Type type) + { + // + var t = Nullable.GetUnderlyingType(type) ?? type; + + // + if (t == typeof(string) || t == typeof(char) || t == typeof(Guid) || t == typeof(DateTime)) + { + return "string"; + } + + // + if (t == typeof(int) || t == typeof(long) || t == typeof(short) || t == typeof(byte)) + { + return "integer"; + } + + // + if (t == typeof(float) || t == typeof(double) || t == typeof(decimal)) + { + return "number"; + } + + // + if (t == typeof(bool)) + { + return "boolean"; + } + + // + if (t.IsArray || typeof(System.Collections.IEnumerable).IsAssignableFrom(t)) + { + return "array"; + } + + // + if (t.IsEnum) + { + return "string"; + } + + // + return "object"; + } + + private static IEnumerable SafeGetTypes(Assembly asm) + { + // + try + { + return asm.GetTypes(); + } + catch (ReflectionTypeLoadException ex) + { + return ex.Types.Where(t => t != null)!; + } + } + #endregion + } +} \ No newline at end of file diff --git a/xAiService.csproj b/xAiService.csproj index c9b4752..9cdeb9a 100644 --- a/xAiService.csproj +++ b/xAiService.csproj @@ -32,7 +32,6 @@ -