• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Introducing Attributes Support for MCP Servers in Delphi

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,565
Баллы
155
Building MCP (Model Context Protocol) servers just got significantly easier with the new attributes support in TMS AI Studio. This powerful feature allows developers to transform any Delphi class into a fully functional MCP server using simple attribute decorators, eliminating the need for manual tool registration and reducing boilerplate code.



What Are MCP Attributes?


MCP attributes are custom Delphi attributes that you can apply to your classes and methods to automatically expose them as MCP tools. Instead of manually creating tool definitions, registering methods, and managing parameters, you simply decorate your existing code with attributes and let the framework handle the rest.

Key Benefits


✅ Rapid Development: Turn existing business logic into MCP tools in minutes rather than hours.
✅ Clean Code: Keep your domain logic separate from MCP infrastructure concerns.
✅ Type Safety: Leverage Delphi's RTTI (Runtime Type Information) for automatic parameter validation and type conversion.
✅ Declarative Style: Express your intent clearly with self-documenting attributes.

Available Attributes


The TMS MCP framework provides a comprehensive set of attributes:

Tool Declaration

  • TTMSMCPTool - Marks a method as an MCP tool
Metadata Attributes

  • TTMSMCPName - Overrides the default name
  • TTMSMCPDescription - Adds descriptive text for AI models
Tool Behavior Hints

  • TTMSMCPReadOnly - Indicates read-only operations
  • TTMSMCPDestructive - Warns of destructive operations
  • TTMSMCPIdempotent - Indicates idempotent operations (safe to repeat)
  • TTMSMCPOpenworld - Allows flexible parameter handling
Parameter Modifiers

  • TTMSMCPOptional - Marks parameters as optional
Quick Start Example


Here's a simple calculator server implementation using attributes:


type
TCalculatorServer = class(TPersistent)
public
[TTMSMCPTool]
[TTMSMCPName('add')]
[TTMSMCPDescription('Add two numbers together')]
function Add(a, b: Integer): Integer;

[TTMSMCPTool]
function Multiply(a: Double; [TTMSMCPOptional] b: Double = 5): Double;

[TTMSMCPTool]
[TTMSMCPIdempotent]
function Divide(a, b: Double): Double;
end;

implementation

function TCalculatorServer.Add(a, b: Integer): Integer;
begin
Result := a + b;
end;

function TCalculatorServer.Multiply(a, b: Double): Double;
begin
Result := a * b;
end;

function TCalculatorServer.Divide(a, b: Double): Double;
begin
if b = 0 then
raise Exception.Create('Division by zero is not allowed');
Result := a / b;
end;
Creating the Server


With your class decorated, creating an MCP server is remarkably simple:


var
MCPServer: TTMSMCPAttributedServer;
Calculator: TCalculatorServer;
begin
Calculator := TCalculatorServer.Create;
MCPServer := TTMSMCPServerFactory.CreateFromObject(Calculator);
MCPServer.ServerName := 'CalculatorServer';

try
MCPServer.Start;
MCPServer.Run;
finally
MCPServer.Free;
Calculator.Free;
end;
end;

The TTMSMCPServerFactory class provides convenient factory methods:

  • CreateFromObject - Creates a server from an existing object instance
  • CreateFromClass - Creates a server from a class type
Advanced Features

Optional Parameters


Use TTMSMCPOptional to mark parameters as optional with default values:


[TTMSMCPTool]
function Multiply(a: Double;
[TTMSMCPOptional] b: Double = 5): Double;
Custom Names and Descriptions


Override default method names and add helpful descriptions:


[TTMSMCPTool]
[TTMSMCPName('sqrt')]
[TTMSMCPDescription('Calculate square root of a number')]
function SquareRoot([TTMSMCPName('value')] a: Double): Double;
Tool Behavior Hints


Provide hints to AI models about operation characteristics:


[TTMSMCPTool]
[TTMSMCPIdempotent] // Safe to call multiple times
function GetBalance(accountId: string): Double;

[TTMSMCPTool]
[TTMSMCPDestructive] // Warn about data modification
procedure DeleteAccount(accountId: string);

[TTMSMCPTool]
[TTMSMCPReadOnly] // No side effects
function QueryData(filter: string): TStringList;
Multiple Target Classes


You can register multiple classes to a single server:


MCPServer := TTMSMCPAttributedServer.Create(nil);
MCPServer.AddClass(TCalculatorServer);
MCPServer.AddClass(TFileSystemServer);
MCPServer.AddObject(MyCustomObject);
Under the Hood


The attributes system leverages Delphi's powerful RTTI capabilities to:

  1. Discover methods marked with TTMSMCPTool at runtime
  2. Extract metadata from attribute decorators
  3. Generate MCP tool definitions automatically
  4. Create method wrappers that handle JSON parameter conversion
  5. Execute methods with proper type conversion and error handling

The TTMSMCPRttiTool class extends the base tool class to provide RTTI-based parameter handling and automatic JSON serialization/deserialization.

Best Practices


Use Descriptive Names: Even though attributes allow custom names, choose meaningful method names as a foundation.

Add Descriptions: Help AI models understand your tools by providing clear descriptions.

Handle Errors: Raise meaningful exceptions that will be converted to proper MCP error responses.

Mark Optional Parameters: Use TTMSMCPOptional with default values for better flexibility.

Use Behavior Hints: Apply TTMSMCPIdempotent, TTMSMCPReadOnly, and TTMSMCPDestructive appropriately to guide AI models.

Type Everything: Explicitly declare types using type attributes for clarity and validation.

Start Building the Future Today


The AI revolution is here, and with TMS AI Studio, Delphi developers are perfectly positioned to be at the forefront. Whether you're building intelligent business applications, creating AI-powered tools, or exploring the possibilities of the Model Context Protocol, TMS AI Studio gives you everything you need to succeed.

Ready to transform your development process?

Starting at 225 EUR for a single developer license, TMS AI Studio offers exceptional value for the comprehensive AI development toolkit it provides.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Join the growing community of developers who are already building tomorrow's AI applications with TMS AI Studio. The future of intelligent software development starts here.

TMS Software Delphi  Components



TMS AI Studio requires Delphi 11.0 or higher.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу