+
مدلهای زبانی ممکن است ورودیهای نامعتبر یا مخرب ارسال کنند. اعتبارسنجی ورودی، خط دفاعی نهایی قبل از اجرای منطق تجاری است. دو رویکرد اصلی وجود دارد:
+
+
الف) Data Annotations (ساده و اعلانی)
+
مناسب برای قوانین ساده مانند اجباری بودن، طول رشته، و محدوده عددی. این Attributeها هم در JSON Schema تولیدی اثر میگذارند و هم قابل اجرا هستند:
+
+
using System.ComponentModel.DataAnnotations;
+
+public class CreateUserRequest
+{
+ [Required(ErrorMessage = "Name is required.")]
+ [StringLength(100, MinimumLength = 2)]
+ public string Name { get; set; }
+
+ [Range(18, 120, ErrorMessage = "Age must be between 18 and 120.")]
+ public int Age { get; set; }
+
+ [EmailAddress]
+ public string Email { get; set; }
+}
+
+[McpServerTool, Description("Creates a new user.")]
+public static string CreateUser(CreateUserRequest request)
+{
+ // اعتبارسنجی دستی
+ var context = new ValidationContext(request);
+ var results = new List<ValidationResult>();
+ if (!Validator.TryValidateObject(request, context, results, validateAllProperties: true))
+ {
+ var errors = string.Join("; ", results.Select(r => r.ErrorMessage));
+ throw new ArgumentException($"Validation failed: {errors}");
+ }
+
+ return $"User {request.Name} created.";
+}
+
+
ب) FluentValidation (برای قوانین پیچیده)
+
برای قوانین شرطی، وابسته به چند فیلد، یا اعتبارسنجیهای پیچیدهتر:
+
+
using FluentValidation;
+
+public class UpdateOrderValidator : AbstractValidator<UpdateOrderRequest>
+{
+ public UpdateOrderValidator()
+ {
+ RuleFor(x => x.OrderId).NotEmpty().WithMessage("Order ID is required.");
+ RuleFor(x => x.Quantity).GreaterThan(0).WithMessage("Quantity must be positive.");
+ RuleFor(x => x.DiscountCode)
+ .MaximumLength(20)
+ .When(x => !string.IsNullOrEmpty(x.DiscountCode));
+ }
+}
+
+[McpServerTool, Description("Updates an order.")]
+public static async Task<string> UpdateOrder(UpdateOrderRequest request)
+{
+ var validator = new UpdateOrderValidator();
+ var result = await validator.ValidateAsync(request);
+ if (!result.IsValid)
+ throw new ArgumentException(result.ToString());
+
+ return $"Order {request.OrderId} updated.";
+}
+
+
+ 💡 نکته: SDK بهطور خودکار JSON Schema را از امضای متد تولید میکند. اگر از Data Annotations استفاده کنید، محدودیتها (مانند maxLength، minimum، required) در Schema ظاهر میشوند و مدل زبانی از قبل میداند چه ورودی معتبر است. این کار نرخ خطا را بهطور قابلتوجهی کاهش میدهد.
+
+
+
+ ⚠️ هشدار: اعتبارسنجی سمت سرور را هرگز حذف نکنید، حتی اگر Schema محدودیتها را نشان دهد. مدل زبانی همیشه از Schema پیروی نمیکند و ممکن است مقادیر خارج از محدوده ارسال کند.
+
+