Jump to content
과거의 기술자료(읽기 전용): https://tech.devgear.co.kr ×
과거의 기술자료(읽기 전용): https://tech.devgear.co.kr

Recommended Posts

에 포스트됨

원문 정보 (최종 번역일: 2026년 10월 15일):

AI가 보급되면서 우리 생활의 여러 장면에서 AI를 활용하게 되었다. 문서 작성, 이미지 생성, 상담 등 생성형 AI는 지금까지 채팅 형식의 대화가 주된 사용 방식이었다. 하지만 최근에는 “AI 에이전트”로서의 활용에도 관심이 모이고 있다.

AI 에이전트 활용을 생각할 때 또 하나 주목할 것이 “MCP(Model Context Protocol)”이다. MCP를 사용하면 AI가 외부 도구나 서비스에 접근할 수 있게 된다. Kai(카이)에도 MCP 서버를 등록해서 사용하는 기능이 마련되어 있다.

이번 글에서는 MCP 서버의 기본 구조를 배운다. 그런 다음 실제로 RAD Studio(라드 스튜디오)에서 MCP 서버를 만들어 Kai에서 사용해 본다.

“MCP 서버”라고 하면 조금 어렵게 느껴질 수 있다. 하지만 기본 구조를 하나씩 살펴보면, 의외로 단순한 구조임을 알 수 있다.

목차

AI 세계의 USB-C?

MCP는 흔히 “AI 세계의 USB-C”라고 표현한다. 하지만 나는 얼핏 알기 쉬워 보이는 이 설명을 한동안 이해하지 못했다.

애초에 AI에 USB-C 같은 외부 연결 구조가 왜 필요한가. 왜 Type-C인가, Type-A는 안 되는가… 지금 생각하면 상당히 엉뚱한 것에 신경 쓰느라, 본질적인 부분에 주목하지 못했다.

만약 여러분도 “USB-C라고 해도 와닿지 않는다”고 느낀다면, 조금 다르게 생각해 보자.

“MCP는 AI가 사용하도록 만든 플러그인 규격”이라고 생각하면 이해하기 쉬울 수 있다.

MCP 자체는 어디까지나 프로토콜, 즉 통신을 위한 공통 규칙이다. 그런 의미에서 “USB”라는 비유는 상당히 정확하다. MCP라는 공통 규격을 지원하면, AI 애플리케이션에서 다양한 데이터와 도구를 공통된 방법으로 사용할 수 있게 된다.

예를 들어 데이터베이스 검색, 파일 조작, 외부 서비스에서 정보 가져오기 같은 기능을 MCP 서버의 도구(tool)로 마련해 둔다. 그러면 AI는 채팅 대화뿐 아니라, 그 외부 기능(tool)을 사용하면서 작업을 수행할 수 있게 된다. 말하자면 일반 AI를 위한 '플러그인 같은 것'을 사용자가 직접 만들어 제공할 수 있다.

MCP는 원래 Anthropic사에서 공개한 오픈 프로토콜이다. 현재는 Linux Foundation 산하의 Agentic AI Foundation(AAIF)에 기증되어, 오픈 프로젝트로 운영되고 있다.

Anthropic사 이외의 다양한 AI 제품과 서비스에서도 MCP를 채택하고 있다. 그래서 MCP를 지원하는 MCP 서버라면, 특정 AI 벤더에 한정되지 않는다. 지원하는 MCP의 사양과 기능에 맞춰, 다양한 AI 애플리케이션에서 사용할 수 있다.

 

MCP 서버를 만들 때 알아야 할 세 가지

MCP 서버의 구조는 그렇게 복잡하지 않다. 먼저 MCP 서버를 만들 때 알아 두면 좋은 세 가지 포인트를 살펴보자.

① AI 클라이언트와의 통신에는 JSON을 사용한다

MCP에서는 클라이언트가 MCP 서버에 접속해서, 서버가 공개하는 도구를 사용한다. 이 통신에는 JSON-RPC 2.0 사양을 따르는 메시지가 사용된다.

② 트랜스포트 방식 알아 두기

MCP 서버를 만들 때는 트랜스포트 방식(클라이언트와 서버 사이의 통신 방법)을 이해하고 결정하는 것이 중요하다. 트랜스포트 방식은 크게 다음 두 가지가 있다.

(1) stdio(표준 입출력) 방식

stdio 방식에서는 MCP 클라이언트와 MCP 서버가 표준 입력과 표준 출력을 사용해 데이터를 주고받는다. Delphi(델파이)라면 콘솔 애플리케이션에서 Readln, Writeln 등을 사용한다. 그렇게 ①에서 설명한 JSON-RPC 2.0 사양을 따르는 데이터를 송수신한다.

(2) Streamable HTTP 방식

Streamable HTTP 방식에서는 HTTP(HTTPS)를 사용해 MCP 클라이언트와 MCP 서버 사이에서 데이터를 주고받는다.

③ 메서드 이름 이해하기

MCP 사양에는 MCP 서버와 클라이언트 사이에서 통신하기 위한 명령(메서드)이 정해져 있다. MCP 서버를 만들 때는 먼저 다음 메서드를 알아 두면 좋다.

(1) initialize

MCP 클라이언트와 MCP 서버가 처음 접속할 때 사용하는 메서드이다. 클라이언트가 사용하는 MCP 프로토콜 버전과 지원하는 기능 등을 MCP 서버에 전달한다. 그러면 MCP 서버도 자신이 지원하는 정보를 돌려준다.

(2) notifications/initialized

initialize로 초기화가 끝났음을 MCP 클라이언트가 MCP 서버에 알리기 위한 메서드이다.

(3) server/discover

클라이언트가 “이 서버는 무엇을 지원하는가”를 확인하기 위한 메서드이다. MCP 서버는 지원하는 MCP 프로토콜 버전과 기능 등의 정보를 돌려준다.

※ MCP 버전에 따라 초기화 방식이 다르다. initialize와 notifications/initialized는 기존 사양에서 사용하고, 2026-07-28 사양에서는 server/discover가 도입되었다.

(4) tools/list

클라이언트가 “이 MCP 서버에는 어떤 도구가 마련되어 있는가”를 확인하기 위한 메서드이다. 예를 들어 “DoSomething”이라는 도구를 구현했다면, 그 도구의 이름, 설명, 필요한 아규먼트 등을 tools/list에 대한 응답으로 공개한다.

 

MCP 서버에 독자적인 기능 구현하기

지금까지 소개한 메서드 이름은 MCP 사양에서 미리 정해 둔 것이다. 한편 실제로 AI가 사용하는 기능은 “도구”로 MCP 서버에 구현한다. 도구의 이름은 개발자가 정할 수 있다. 그림은 MCP 서버와 MCP 클라이언트(AI) 사이의 통신 흐름이다.

MCP_AI_Drawing_Process_600.png

예를 들어 “DoSomething”이라는 도구를 공개했다면, MCP 클라이언트는 tools/list로 그 존재를 알게 된다. 실제로 실행할 때는 tools/call 메서드를 사용해 “DoSomething”을 호출한다. 참고로 MCP 메서드의 통신 절차는 MCP 버전에 따라 다르다. 어느 버전으로 구현해야 하는지는 사용을 전제로 하는 클라이언트(AI)와 그 버전에 따라 달라진다.

 

RAD Studio로 만드는 첫 MCP 서버

RAD Studio를 사용해 MCP 서버를 만들어 보자. 이번에는 Kai에서 사용하는 것을 전제로, 프롬프트가 끝나면 알림을 보내는 MCP 서버를 만든다. 알림에는 ShowMessage를 사용한다. 응용 예시로는 Windows 토스트 기능이나 외부 알림 서비스와 연동하는 방법도 생각할 수 있다.

도구 이름은 DoSomething이라는 범용적인 이름으로 해 둔다. 그 밖의 실행 환경은 다음과 같다.

  • MCP 서버 이름: MyMCPServer
  • 도구 이름: DoSomething
  • 프로젝트 이름: MyMCPServer
  • 기능 개요: Kai에서 MCP 서버로 사용하는 것을 전제로, 작업이 끝났을 때 AI가 DoSomething 도구를 호출한다. 그러면 ShowMessage를 사용해 사용자에게 알린다.
  • 개발 언어: Delphi 또는 C++Builder(C++빌더)
  • 사용하는 AI 모델(CLI): OpenAI(Codex) 버전 1.11 ※ MCP 버전은 2025-06-18판

코딩은 Kai 환경을 쓸 수 있으므로 AI에게 맡기자. 프롬프트는 다음과 같이 한다. (전체 샘플 코드는 글 끝에 싣는다)

Kai에서 사용할 MCP 서버를 만들고 싶어
・툴 이름은 DoSomething
・프롬프트 작업이 끝났을 때 AI에 의해 호출되며, 작업이 완료되었음을 ShowMessage로 출력할 것
・메시지 본문은 AI가 생성하여 전달한 인자 값을 사용할 것
・메시지를 포함해 모든 한글이 올바르게 표시되도록 필요한 곳에 UTF8을 적용할 것 
・데모 프로그램이므로 복잡한 예외 처리나 에러 체크는 생략할 것
・프로토콜은 2025-06-18 버전을 준수할 것
・AI로부터의 입력과 MCP 서버의 응답 데이터(JSON)를 확인하기 위해 EXE와 동일한 경로에 mcp-json.log 로그를 남길 것

생성된 코드를 조금 들여다보자. 다음 코드는 메인 루틴에 해당하는 부분이다. 구조가 아주 단순함을 알 수 있다.

var
  Line: string;
  Request: TJSONObject;
begin
  // ① 각종 초기화 처리
  Application.Initialize;
  Application.Title := 'Kai Completion Demo';
  SetTextCodePage(Input, CP_UTF8);
  SetTextCodePage(Output, CP_UTF8);
  LogFileName := TPath.Combine(ExtractFilePath(ParamStr(0)), 'mcp-json.log');

  // ② Eof까지 루프
  while not Eof(Input) do
  begin
    Readln(Input, Line);
    LogJSON('AI -> SERVER', Line);  // ②-1 로그 출력
    Request := TJSONObject.ParseJSONValue(Line) as TJSONObject;  // ②-2 입력값을 JSON으로 변환
    HandleRequest(Request);          // ②-3 요청 내용에 따라 각종 처리 실행
    Request.Free;
  end;
end.

메인 루틴은 아주 단순하다. ①에서 각종 초기화 처리를 한 다음, Input 변수에 연결된 표준 입력이 끝에 도달할 때까지 루프한다. 받은 데이터는 ②-2에서 JSON으로 변환되고, ②-3에서 각종 처리로 나뉘어 전달된다.

MCP 서버 등록

다음으로, 빌드한 Exe를 Kai의 MCP 서버로 등록한다. 다음은 그 등록 예시이다.

KaiOption_600.png

RAD Studio IDE에서 Tools > Options > Kai > Chat > MCP Servers > Custom을 선택한다.

서버를 추가하는 (+) 버튼을 클릭하고, 속성을 다음과 같이 설정한다.

  • Name: MyMCPServer (또는 임의의 이름)
  • Type: Local
  • Start Command: 만든 MCP 서버의 전체 경로 (예시에서는 “C:\Users\Public\Documents\MyMCPServer\Win64\Debug\MyMCPServer.exe”)

입력을 마쳤으면 저장을 클릭하고, RAD Studio를 재시작한다.

동작 테스트

만든 MCP 서버가 기대한 대로 동작하는지 확인한다. RAD Studio IDE에서 View > Kai - Chat을 선택해 채팅 창을 열고, 새 세션을 시작한다.

새 세션이 만들어지는 것과 동시에 작업 관리자를 열면, 만든 MyMCPServer.exe가 실행된 것을 확인할 수 있다. 이 상태에서 Run > Attach to Process를 실행하면, RAD Studio에서 디버깅을 할 수도 있다.

image.png

다음으로 프롬프트를 아래와 같이 입력해서, 작업이 끝날 때 알림이 오는지 확인한다.

Hello world 콘솔 애플리케이션을 만들어줘. 작업이 끝나면 DoSomething 도구를 사용해서 사용자에게 알려줘

그림은 프롬프트가 실행되어 프로젝트가 만들어진 직후의 상태이다. 보다시피 메시지 박스가 표시되어 있다. 참고로 메시지 박스의 문구는 MCP 서버 쪽에서 준비한 정해진 문장이 아니다. AI 쪽에서 작성한 문장을 그대로 표시하고 있다.

다음 텍스트는 MCP 클라이언트와 서버의 통신 로그이다.

2026-10-01 13:21:31.446 AI -> SERVER
{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{"experimental":{"codex/auth-change":{}},"elicitation":{"form":{},"url":{}}},"clientInfo":{"name":"codex-mcp-client","title":"Codex","version":"0.156.1"}}}

2026-10-01 13:21:31.446 SERVER -> AI
{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{}},"serverInfo":{"name":"KaiCompletionDemo","version":"1.0.0"},"instructions":"When you have completed the user request, call DoSomething once before your final answer. Compose a short completion message in the user language and pass it as the message argument."}}

2026-10-01 13:21:31.452 AI -> SERVER
{"jsonrpc":"2.0","method":"notifications/initialized"}

2026-10-01 13:21:31.457 AI -> SERVER
{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"progressToken":0}}}

2026-10-01 13:21:31.464 SERVER -> AI
{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"DoSomething","description":"When you have completed the user request, call DoSomething once before your final answer. Compose a short completion message in the user language and pass it as the message argument. Displays the message in a Windows dialog; returns after OK is pressed.","inputSchema":{"type":"object","properties":{"message":{"type":"string","description":"AI-written completion message describing the finished work."}},"required":["message"],"additionalProperties":false}}]}}

2026-10-01 13:22:44.966 AI -> SERVER
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"_meta":{"callId":"exec-8ae428a5-bd76-4540-a8c5-feafc7877b32","x-codex-turn-metadata":{"session_id":"01a0f5b2-3202-7ba1-8c3a-415f01336e87","thread_id":"01a0f5b2-3202-7ba1-8c3a-415f01336e87","reasoning_effort":"low","turn_id":"01a0f5b2-4b98-7140-85f5-82848c39069b","model":"gpt-6-astra","sandbox":"none","sandbox_mode":"danger-full-access","auto_review_enabled":false,"node_repl_auto_review_required":true,"node_repl_disabled":false,"turn_started_at_unix_ms":1790828497821,"codex_version":"0.156.1"},"threadId":"01a0f5b2-3202-7ba1-8c3a-415f01336e87","sessionId":"01a0f5b2-3202-7ba1-8c3a-415f01336e87","windowId":"01a0f5b2-3202-7ba1-8c3a-415f01336e87:0","itemId":"ctc_006f5ee1e2f384f6016abde01331f887d084f75cd32d4b50d9","progressToken":1},"name":"DoSomething","arguments":{"message":"Hello world를 표시하는 Delphi 콘솔 애플리케이션을 HelloWorldConsole 폴더에 만들었습니다. RAD Studio에서 빌드에 성공했고, 실행 결과 ‘Hello world’와 정상 종료(종료 코드 0)를 확인했습니다."}}}

로그는 2행이 한 쌍으로 구성된다. 첫 행은 기록 시각과 통신 방향(AI→MCP 서버 또는 MCP→AI)이다. 둘째 행은 실제 통신 내용이다. 통신 내용이 JSON 형식으로 주고받아지고 있음을 알 수 있다. 처음에 설명한 대로, JSON 포맷은 MCP 사양으로 공식 사이트에 정의되어 있다.

MCP Connect로 더 간결하게

RAD Studio 13.2부터는 “MCPConnect”를 사용해 MCP 서버를 더 손쉽게 개발할 수 있게 되었다.

image-150x150.png

MCPConnect에는 MCP 서버 구현에 필요한 기본 기능이 미리 라이브러리로 마련되어 있다. 그래서 통신 처리와 각종 기능을 처음부터 구현할 필요가 없고, 더 단순한 코드로 MCP 서버를 구축할 수 있다. 또한 MCPConnect에는 MCP 서버 작성용 마법사도 있다. 용도에 맞는 스켈레톤을 만들어 주므로, 처음 MCP 서버를 개발하는 사람도 부드럽게 개발을 시작할 수 있다.

image-3.png

MCPConnect는 애드온으로 GetIt(겟잇)에서 받을 수 있다. 또한 Paolo Rossi가 쓴 MCP 서버 만들기 (Delphi 안에서 MCPConnect를 사용)와 Luca Minuti가 쓴 MCPConnect: MCP 서버를 안전하게 보호하는 방법(둘 다 한국어 번)에서는 MCP의 기초 지식과 함께 MCPConnect를 더 자세히 설명한다. 이 글들도 꼭 읽어 보기 바란다.

맺음말: 넓어지는 MCP 서버의 세계

RAD Studio로 만드는 MCP 서버는 Kai에서 사용할 도구를 만들 때는 물론, 본격적인 AI 에이전트로 사용할 도구를 개발할 때도 이번에 소개한 구조가 기본이 된다. RAD Studio로 MCP 서버를 개발하는 장점 중 하나로, 기존 프로그램 자산을 활용할 수 있다는 점을 들 수 있다. 예를 들어 기존 업무 애플리케이션에 구현된 비즈니스 로직을 AI 에이전트가 사용하는 경우를 생각해 보자.

MCP_AI_Drawing_Example_600.png

지금까지 UI로 사용자가 조작하던 처리를 MCP 서버를 통해 실행할 수 있게 하면, 기존 작업흐름과 함께 AI가 사용할 수 있는 작업흐름을 추가할 수 있다.

이처럼 MCP 서버는 새로운 도구를 개발하는 용도만이 아니라, 지금까지 축적해 온 프로그램 자산과 AI를 이어 주는 다리로도 활용할 수 있다.

참고

샘플 코드

Delphi

program MyMCPServer;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  Winapi.Windows,
  System.SysUtils,
  System.Classes,
  System.JSON,
  System.IOUtils,
  Vcl.Forms,
  Vcl.Dialogs;

const
  ProtocolVersion = '2025-06-18';
  CompletionInstruction =
    'When you have completed the user request, call DoSomething once before ' +
    'your final answer. Compose a short completion message in the user language ' +
    'and pass it as the message argument.';

var
  LogFileName: string;

// 통신 방향과 JSON 메시지를 일시와 함께 로그 파일에 추가한다.
procedure LogJSON(const Direction, JSON: string);
begin
  TFile.AppendAllText(LogFileName,
    FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now) + ' ' + Direction +
    sLineBreak + JSON + sLineBreak + sLineBreak, TEncoding.UTF8);
end;

// JSON-RPC 성공 응답을 로그에 기록하고, 표준 출력으로 보낸다.
procedure SendResult(const ID: TJSONValue; const Value: TJSONObject);
var
  Response: TJSONObject;
  JSON: string;
begin
  Response := TJSONObject.Create;
  Response.AddPair('jsonrpc', '2.0');
  Response.AddPair('id', ID.Clone as TJSONValue);
  Response.AddPair('result', Value);
  JSON := Response.ToJSON;
  LogJSON('SERVER -> AI', JSON);
  Writeln(Output, JSON);
  Flush(Output);
  Response.Free;
end;

// 프로토콜 버전과 서버 정보를 포함한 초기화 응답을 만든다.
function InitializeResult: TJSONObject;
begin
  Result := TJSONObject.Create;
  Result.AddPair('protocolVersion', ProtocolVersion);
  Result.AddPair('capabilities',
    TJSONObject.Create.AddPair('tools', TJSONObject.Create));
  Result.AddPair('serverInfo',
    TJSONObject.Create.AddPair('name', 'KaiCompletionDemo')
      .AddPair('version', '1.0.0'));
  Result.AddPair('instructions', CompletionInstruction);
end;

// 공개 도구의 설명과 아규먼트 스키마를 포함한 도구 목록을 만든다.
function ToolList: TJSONObject;
var
  Tool, Schema, Properties: TJSONObject;
begin
  Properties := TJSONObject.Create.AddPair('message',
    TJSONObject.Create.AddPair('type', 'string')
      .AddPair('description',
        'AI-written completion message describing the finished work.'));
  Schema := TJSONObject.Create.AddPair('type', 'object')
    .AddPair('properties', Properties)
    .AddPair('required', TJSONArray.Create.Add('message'))
    .AddPair('additionalProperties', TJSONBool.Create(False));
  Tool := TJSONObject.Create.AddPair('name', 'DoSomething')
    .AddPair('description', CompletionInstruction +
      ' Displays the message in a Windows dialog; returns after OK is pressed.')
    .AddPair('inputSchema', Schema);
  Result := TJSONObject.Create.AddPair('tools', TJSONArray.Create(Tool));
end;

// 수신한 요청에 따라 초기화, 도구 목록 조회, 메시지 표시 등을 처리한다.
procedure HandleRequest(const Request: TJSONObject);
var
  ID: TJSONValue;
  MethodName, MessageText: string;
  Params: TJSONObject;
begin
  // Notifications (including notifications/initialized) have no response.
  ID := Request.GetValue('id');
  if ID = nil then
    Exit;

  MethodName := Request.GetValue<string>('method');
  if MethodName = 'initialize' then
    SendResult(ID, InitializeResult)
  else if MethodName = 'ping' then
    SendResult(ID, TJSONObject.Create)
  else if MethodName = 'tools/list' then
    SendResult(ID, ToolList)
  else if MethodName = 'tools/call' then
  begin
    Params := Request.GetValue<TJSONObject>('params');
    // Demo: assumes a valid DoSomething call with a string message.
    MessageText := Params.GetValue<TJSONObject>('arguments')
      .GetValue<string>('message');
    ShowMessage(MessageText);
    SendResult(ID, TJSONObject.Create.AddPair('content',
      TJSONArray.Create(TJSONObject.Create.AddPair('type', 'text')
        .AddPair('text', 'Completion message displayed: ' + MessageText))));
  end;
end;

var
  Line: string;
  Request: TJSONObject;
begin
  Application.Initialize;
  Application.Title := 'Kai Completion Demo';
  SetTextCodePage(Input, CP_UTF8);
  SetTextCodePage(Output, CP_UTF8);
  LogFileName := TPath.Combine(ExtractFilePath(ParamStr(0)), 'mcp-json.log');

  while not Eof(Input) do
  begin
    Readln(Input, Line);
    LogJSON('AI -> SERVER', Line);
    Request := TJSONObject.ParseJSONValue(Line) as TJSONObject;
    HandleRequest(Request);
    Request.Free;
  end;
end.

C++Builder

// 헤더 파일은 생략한다
#include <vcl.h>
#pragma hdrstop
#include <System.JSON.hpp>
#include <System.IOUtils.hpp>
#include <Vcl.Dialogs.hpp>
#include <iostream>
#include <memory>
#include <string>

#pragma argsused
using namespace System;
using namespace System::Json;
using namespace System::Sysutils;

static const UnicodeString ProtocolVersion = L"2025-06-18";
static const UnicodeString CompletionInstruction =
    L"When you have completed the user request, call DoSomething once before "
    L"your final answer. Compose a short completion message in the user language "
    L"and pass it as the message argument.";
static UnicodeString LogFileName;

// 통신 방향과 JSON 메시지를 일시와 함께 로그 파일에 추가한다.
static void LogJSON(const UnicodeString &direction, const UnicodeString &json)
{
    System::Ioutils::TFile::AppendAllText(LogFileName,
        FormatDateTime(L"yyyy-mm-dd hh:nn:ss.zzz", Now()) + L" " + direction +
        L"\r\n" + json + L"\r\n\r\n", TEncoding::UTF8);
}

// JSON-RPC 응답을 만들어 로그에 기록하고, UTF-8로 표준 출력에 보낸다.
static void SendResult(TJSONValue *id, TJSONObject *value)
{
    std::unique_ptr<TJSONObject> response(new TJSONObject());
    response->AddPair(L"jsonrpc", L"2.0");
    response->AddPair(L"id", static_cast<TJSONValue *>(id->Clone()));
    response->AddPair(L"result", value);
    UnicodeString json = response->ToJSON();
    LogJSON(L"SERVER -> AI", json);
    UTF8String utf8(json);
    std::cout.write(utf8.c_str(), utf8.Length());
    std::cout << std::endl;
}

// 프로토콜 버전, 서버 정보, 기능과 지시를 포함한 초기화 응답을 만든다.
static TJSONObject *InitializeResult()
{
    TJSONObject *result = new TJSONObject();
    result->AddPair(L"protocolVersion", ProtocolVersion);
    result->AddPair(L"capabilities",
        (new TJSONObject())->AddPair(L"tools", new TJSONObject()));
    result->AddPair(L"serverInfo", (new TJSONObject())
        ->AddPair(L"name", L"KaiCompletionDemo")->AddPair(L"version", L"1.0.0"));
    result->AddPair(L"instructions", CompletionInstruction);
    return result;
}

// DoSomething 도구의 설명과 입력 스키마를 포함한 도구 목록을 만든다.
static TJSONObject *ToolList()
{
    TJSONObject *properties = (new TJSONObject())->AddPair(L"message",
        (new TJSONObject())->AddPair(L"type", L"string")->AddPair(L"description",
            L"AI-written completion message describing the finished work."));
    TJSONObject *schema = (new TJSONObject())->AddPair(L"type", L"object")
        ->AddPair(L"properties", properties)
        ->AddPair(L"required", (new TJSONArray())->Add(UnicodeString(L"message")))
        ->AddPair(L"additionalProperties", new TJSONBool(false));
    TJSONObject *tool = (new TJSONObject())->AddPair(L"name", L"DoSomething")
        ->AddPair(L"description", CompletionInstruction +
            L" Displays the message in a Windows dialog; returns after OK is pressed.")
        ->AddPair(L"inputSchema", schema);
    TJSONArray *tools = new TJSONArray();
    tools->AddElement(tool);
    return (new TJSONObject())->AddPair(L"tools", tools);
}

// 요청의 메서드에 따라 응답하고, 도구를 호출할 때 메시지를 표시한다.
static void HandleRequest(TJSONObject *request)
{
    TJSONValue *id = request->GetValue(L"id");
    if (!id)
        return;
    UnicodeString method = request->GetValue(L"method")->Value();
    if (method == L"initialize")
        SendResult(id, InitializeResult());
    else if (method == L"ping")
        SendResult(id, new TJSONObject());
    else if (method == L"tools/list")
        SendResult(id, ToolList());
    else if (method == L"tools/call")
    {
        TJSONObject *params = static_cast<TJSONObject *>(request->GetValue(L"params"));
        TJSONObject *arguments = static_cast<TJSONObject *>(params->GetValue(L"arguments"));
        UnicodeString message = arguments->GetValue(L"message")->Value();
        Vcl::Dialogs::ShowMessage(message);
        TJSONArray *content = new TJSONArray();
        content->AddElement((new TJSONObject())->AddPair(L"type", L"text")
            ->AddPair(L"text", L"Completion message displayed: " + message));
        SendResult(id, (new TJSONObject())->AddPair(L"content", content));
    }
}

// 애플리케이션과 로그를 초기화하고, 표준 입력의 JSON-RPC 메시지를 순서대로 처리한다.
int main(int argc, char *argv[])
{
    Application->Initialize();
    Application->Title = L"Kai Completion Demo";
    LogFileName = System::Ioutils::TPath::Combine(
        ExtractFilePath(ParamStr(0)), L"mcp-json.log");
    // One UTF-8 JSON-RPC message per line. stdout contains JSON only.
    std::string bytes;
    while (std::getline(std::cin, bytes))
    {
        if (!bytes.empty() && bytes.back() == '\r')
            bytes.pop_back();
        UnicodeString line = UTF8ToString(UTF8String(bytes.c_str()));
        LogJSON(L"AI -> SERVER", line);
        std::unique_ptr<TJSONValue> request(TJSONObject::ParseJSONValue(line));
        HandleRequest(static_cast<TJSONObject *>(request.get()));
    }
    return 0;
}

데모 영상 보기(한국어)

 

 

이 토의에 참여하세요

지금 바로 의견을 남길 수 있습니다. 그리고 나서 가입해도 됩니다. 이미 회원이라면, 지금 로그인하고 본인 계정으로 의견을 남기세요.

Guest
이 토픽(기고/질문)에 답하기

×   서식있는 텍스트로 붙여넣기.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   이전에 작성한 콘텐츠가 복원되었습니다..   편집창 비우기

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

중요한 정보

이용약관 개인정보보호정책 이용규칙 이 사이트가 더 잘 작동하기 위해 방문자의 컴퓨터에 쿠키가 배치됩니다. 쿠키 설정 변경에서 원하는 설정을 할 수 있습니다. 변경하지 않으면 쿠키를 허용하는 것으로 이해합니다.