Skip to content
Back to search

Delphi-MCP-Server

Native Delphi Server implementation of the Model Context Protocol (MCP)

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/GDKsoftware/Delphi-MCP-Server with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/GDKsoftware/Delphi-MCP-Server'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/gdksoftware--delphi-mcp-server/badge.svg)](/listings/gdksoftware--delphi-mcp-server)

HTML

<a href="/listings/gdksoftware--delphi-mcp-server"><img src="/api/listings/gdksoftware--delphi-mcp-server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

For Standalone Usage

1. Clone the repository:

git clone https://github.com/GDKsoftware/delphi-mcp-server.git
cd delphi-mcp-server

2. Build the project:

Windows Build

build.bat

Or specify configuration and platform:

build.bat Debug Win32
build.bat Release Win64

The script picks up the highest TaurusTLS version installed in the CatalogRepository of the Studio release that `DELPHI_PATH` points at. To build against a copy somewhere else, set `TAURUS_PATH` to its `Source` directory first:

set TAURUS_PATH=C:\path\to\TaurusTLS\Source
build.bat Release Win64

Linux Build

**Prerequisites:** - Delphi Enterprise with Linux platform support - PAServer running on Linux target machine - Linux SDK configured in RAD Studio

From the batch file:

build.bat Release Linux64

Or from RAD Studio IDE: 1. Open MCPServer.dproj 2. Select Linux64 platform 3. Build

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,374 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # Delphi MCP Server
  2. ![Delphi](https://img.shields.io/badge/Delphi-11%2B-red)
  3. ![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux-lightgrey)
  4. ![License](https://img.shields.io/badge/license-MIT-blue)
  5. ![MCP](https://img.shields.io/badge/MCP-2026--07--28%20(dual--era)-green)
  6. A Model Context Protocol (MCP) server implementation in Delphi, designed to integrate with Claude Code, Codex, and other MCP-compatible clients for AI-powered Delphi development workflows.
  7. ## Table of Contents
  8. - [Features](#features)
  9. - [Requirements](#requirements)
  10. - [Installation](#installation)
  11. - [Transport Modes](#transport-modes)
  12. - [Protocol Versions and Dual-Era Behaviour](#protocol-versions-and-dual-era-behaviour)
  13. - [Using as a Library](#using-as-a-library)
  14. - [Integration with Claude Code](#integration-with-claude-code)
  15. - [Integration with Codex](#integration-with-codex)
  16. - [Testing with MCP Inspector](#testing-with-mcp-inspector)
  17. - [Available Example Tools](#available-example-tools)
  18. - [Available Example Prompts](#available-example-prompts)
  19. - [Available Example Resources](#available-example-resources)
  20. - [Configuration](#configuration)
  21. - [Authentication](#authentication)
  22. - [Network and Security](#network-and-security)
  23. - [License](#license)
  24. - [Contributing](#contributing)
  25. - [About GDK Software](#about-gdk-software)
  26. - [Support](#support)
  27. - [Commercial Support](#commercial-support)
  28. ## Features
  29. - **Dual-era MCP**: Serves MCP 2026-07-28 (per-request `_meta`, `server/discover`) and the initialize-based revisions 2025-06-18 and 2025-11-25 on the same endpoint and the same stdio process; see [Protocol versions](#protocol-versions-and-dual-era-behaviour)
  30. - **Dual Transport Support**: HTTP (Streamable HTTP with SSE) and STDIO (stdin/stdout)
  31. - **Dual Response Mode**: Supports both JSON-RPC and Server-Sent Events in the same server
  32. - **Tool System**: Extensible tool system with RTTI-based discovery and execution
  33. - **Resource Management**: Modular resource system supporting various content types
  34. - **Security**: `Origin` and `Host` validation against DNS rebinding on every request, loopback binding by default, CORS headers for browser clients, request size and nesting limits, opt-in bearer authentication with OAuth 2.1 resource-server discovery
  35. - **Multi round-trip requests, streaming and subscriptions**: `InputRequiredResult` with signed `requestState`, progress and log notifications on the response stream, `subscriptions/listen` for change notifications
  36. - **Native HTTP stack**: Indy HTTP server with keep-alive, no external runtime
  37. - **Optional Parameters**: Support for optional tool parameters using custom attributes
  38. - **Cross-Platform**: Supports Windows (Win32/Win64) and Linux (x64)
  39. ## Requirements
  40. - Delphi 11 Alexandria or later. The source uses no language feature beyond inline variables (10.3) and no RTL unit newer than Delphi 11; development happens on Delphi 12 Athens, which is what the default project files target.
  41. - Windows (Win32/Win64) or Linux (x64)
  42. - No external dependencies (all required libraries included)
  43. ### Building with Delphi 11 Alexandria
  44. `build.bat` and `build-tests.bat` compile the `.dpr` directly, so only `DELPHI_PATH` needs to point at your installation:
  45. ```bash
  46. set DELPHI_PATH=C:\Program Files (x86)\Embarcadero\Studio\22.0
  47. build.bat
  48. ```
  49. For the IDE and for the Linux64 build, open `src/MCPServer.D11.dproj` (tests: `tests/MCPServerTests.D11.dproj`) instead of the Athens project files. They carry the same units and settings, write their output to a separate `D11` subdirectory, and exist because Alexandria will not load a `ProjectVersion 20.3` project file.
  50. ## Installation
  51. ### For Standalone Usage
  52. 1. Clone the repository:
  53. ```bash
  54. git clone https://github.com/GDKsoftware/delphi-mcp-server.git
  55. cd delphi-mcp-server
  56. ```
  57. 2. Build the project:
  58. #### Windows Build
  59. ```bash
  60. build.bat
  61. ```
  62. Or specify configuration and platform:
  63. ```bash
  64. build.bat Debug Win32
  65. build.bat Release Win64
  66. ```
  67. The script picks up the highest TaurusTLS version installed in the CatalogRepository of the Studio release that `DELPHI_PATH` points at. To build against a copy somewhere else, set `TAURUS_PATH` to its `Source` directory first:
  68. ```bash
  69. set TAURUS_PATH=C:\path\to\TaurusTLS\Source
  70. build.bat Release Win64
  71. ```
  72. #### Linux Build
  73. **Prerequisites:**
  74. - Delphi Enterprise with Linux platform support
  75. - PAServer running on Linux target machine
  76. - Linux SDK configured in RAD Studio
  77. From the batch file:
  78. ```bash
  79. build.bat Release Linux64
  80. ```
  81. Or from RAD Studio IDE:
  82. 1. Open MCPServer.dproj
  83. 2. Select Linux64 platform
  84. 3. Build
  85. ## Transport Modes
  86. The server supports two transport modes:
  87. ### HTTP Transport (Default)
  88. Start the server without arguments for HTTP transport with Server-Sent Events (SSE):
  89. ```bash
  90. Win32\Debug\MCPServer.exe
  91. ```
  92. The server will listen on `http://localhost:3000/mcp` by default (configurable via settings.ini).
  93. **Use HTTP transport for:**
  94. - Claude Code (SSE support)
  95. - MCP Inspector
  96. - Web-based clients
  97. - Remote connections
  98. ### STDIO Transport
  99. Start the server with `--stdio` flag for stdin/stdout communication:
  100. ```bash
  101. Win32\Debug\MCPServer.exe --stdio
  102. ```
  103. The server will:
  104. - Read JSON-RPC messages from stdin, UTF-8, one per line, no byte-order mark
  105. - Write JSON-RPC messages to stdout the same way
  106. - Log diagnostic messages to stderr, never to stdout
  107. - Answer `notifications/cancelled` by stopping the named request; it gets no response
  108. - Send `notifications/progress` for a request that carries `_meta.progressToken`, before its response
  109. - Exit within `[Server] MaxConcurrentRequests` worker threads' drain time (2 seconds by default) once stdin closes
  110. **Use STDIO transport for:**
  111. - Codex (OpenAI)
  112. - Local MCP clients that use process spawning
  113. - Automated testing and scripting
  114. **Supported flag variants:** `--stdio`, `-stdio`, `/stdio`
  115. By default requests are answered one at a time, in the order they arrive.
  116. `[Server] MaxConcurrentRequests` in `settings.ini` raises the number of worker
  117. threads for a client that issues concurrent requests over the same process; a
  118. stdio server never writes `settings.ini` on its own, so this and the other
  119. `[Server]` limits still need explicit configuration when they should differ
  120. from the defaults.
  121. A tool sees the request it is answering through `TMCPRequestContext.Current`:
  122. `CheckCancelled` raises once the client cancels, `ReportProgress` sends a
  123. `notifications/progress` when the request carries a progress token, and
  124. `Log` sends a `notifications/message` when the request carries
  125. `_meta.io.modelcontextprotocol/logLevel` and the message's level is at or
  126. above it. See `test_tool_with_progress` and `test_logging_tool` in
  127. `MCPServer.Tool.ContentSamples` for worked examples.
  128. Over HTTP the same notifications reach the client on the response: when the
  129. request accepts `text/event-stream` and a tool sends one, the response turns
  130. into an SSE stream (chunked, `X-Accel-Buffering: no`) that carries the
  131. notifications first and the JSON-RPC response as its last event. A request
  132. that sends none is answered as before. A client that closes the stream
  133. cancels the request: the server's next write to it fails and the tool sees
  134. `IsCancelled`. That is the HTTP cancellation. A `notifications/cancelled`
  135. naming the same request is answered `202` and dropped, because the tracker a
  136. request consults is its own response stream and a notification always arrives
  137. on a connection of its own; only over stdio, where every message shares one
  138. channel, does the notification stop a running request.
  139. ### Change notifications (`subscriptions/listen`)
  140. A modern client that wants to hear about changes opens a long-lived
  141. `subscriptions/listen` request with a `notifications` filter
  142. (`toolsListChanged`, `promptsListChanged`, `resourcesListChanged`,
  143. `resourceSubscriptions`: a list of URIs). `TMCPSubscriptionsManager`
  144. (`MCPServer.SubscriptionsManager`) answers with
  145. `notifications/subscriptions/acknowledged` carrying the honoured filter and
  146. keeps the stream open: over HTTP as an SSE response with a keep-alive comment
  147. every 15 seconds, over stdio on a thread of its own so the worker threads stay
  148. free. Every message on the subscription carries
  149. `_meta.io.modelcontextprotocol/subscriptionId`, the JSON-RPC id of the
  150. `subscriptions/listen` request. Closing the SSE stream, or sending
  151. `notifications/cancelled` for that id over stdio, ends the subscription;
  152. when the server stops (or stdin closes) it answers the request with a
  153. completion result first.
  154. Notifications are delivered synchronously on the thread that causes the
  155. change, so a subscriber that stops reading can hold up that thread until its
  156. socket buffer drains.
  157. Assign the manager as `ChangeNotifier` of the tools, prompts and resources
  158. managers, as `MCPServer.dpr` does, and the `tools`, `prompts` and `resources`
  159. capabilities announce `listChanged` (and `resources.subscribe`) to modern
  160. clients. `AddTool`, `RemoveTool`, `AddPrompt`, `RemovePrompt`, `AddResource`,
  161. `RemoveResource` and `AddResourceTemplate` then notify the subscribed clients,
  162. and `TMCPResourcesManager.ResourceUpdated(Uri)` reports a changed resource to
  163. the clients that subscribed to that URI. Without a `ChangeNotifier` nothing is
  164. announced and nothing is sent.
  165. ## Protocol Versions and Dual-Era Behaviour
  166. The server decides per request which protocol era it is speaking; nothing is negotiated per connection and no session is minted.
  167. | Request | Era | Served as |
  168. |---|---|---|
  169. | `params._meta` with `io.modelcontextprotocol/protocolVersion` | modern | `2026-07-28`. `clientCapabilities` is required (`-32602`); an unknown revision gets `-32022` with the supported list; `initialize`, `ping`, `logging/setLevel` and `resources/subscribe` do not exist in this era (`-32601`). |
  170. | `initialize` without modern `_meta` | legacy | The requested revision when it is `2025-06-18` or `2025-11-25`, otherwise `2025-11-25`. The result carries `capabilities` and `serverInfo` only. |
  171. | `server/discover` without `_meta` | modern, malformed | `-32602` |
  172. | Anything else | legacy | The revision negotiated by `initialize` on this stdio process, the `MCP-Protocol-Version` header on HTTP, or `2025-11-25` when nothing is known. |
  173. Modern results carry `resultType`, `_meta.io.modelcontextprotocol/serverInfo` and, on `server/discover`, `tools/list`, `resources/list`, `resources/templates/list` and `resources/read`, the cache hints `ttlMs` and `cacheScope`. Legacy results are unchanged. Client responses (`result` or `error` without `method`) are ignored.
  174. Legacy clients do not get the features that 2026-07-28 deprecates or removes. `logging/setLevel`, `resources/subscribe` and `resources/unsubscribe` answer `-32601`, and the `initialize` result does not announce `logging` or `resources.subscribe`. The server sends no requests to the client (`sampling/createMessage`, `elicitation/create`, `roots/list`), so a request whose tool, resource or prompt needs input from the client answers `-32603`. Modern clients get these through `_meta["io.modelcontextprotocol/logLevel"]`, `subscriptions/listen` and the multi round-trip requests described under [Asking the client for input](#asking-the-client-for-input-multi-round-trip-requests).
  175. Over HTTP, modern requests must carry `MCP-Protocol-Version`, `Mcp-Method` and, for `tools/call`, `resources/read`, `prompts/get` and `tasks/*`, `Mcp-Name` (the tool or prompt name, the resource URI or the task id; Base64 sentinel encoding accepted); a missing or different header is `400` with `-32020`. Modern protocol errors get `400`, an unknown method `404`; legacy requests get `200` for every JSON-RPC error, except `400` for an unknown `MCP-Protocol-Version` header. Notifications get `202` with an empty body. Every 4xx to a modern request carries a JSON-RPC error body, so dual-era clients can tell a modern server from a legacy one.
  176. Handlers can read the era, the negotiated revision and the client's declared capabilities through `TMCPRequestContext.Current` (`MCPServer.RequestContext`) or by implementing `IMCPCapabilityManagerEx`, and can raise `EMCPError` (`MCPServer.Errors`) to send a specific JSON-RPC error code.
  177. `settings.ini` keys: `[Server] Title`, `Description`, `WebsiteUrl` and `Instructions` fill `serverInfo` and `instructions`; `[Protocol] LenientModernPing` answers `ping` in the modern era anyway, `DiscoverListsLegacyVersions` also lists the legacy revisions in `server/discover`, and `DiscoverTtlMs` is the cache hint on `server/discover`.
  178. `2025-03-26` is accepted on `initialize` but answered with `2025-11-25`; JSON-RPC batch arrays are rejected with `-32600`.
  179. ## Using as a Library
  180. The Delphi MCP Server is designed to be used both as a standalone application and as a library for your own MCP server implementations. This section covers how to integrate it into your existing Delphi projects.
  181. ### Project Setup for Library Usage
  182. #### Option 1: Git Submodule (Recommended)
  183. ```bash
  184. # Add MCPServer as a submodule to your project
  185. git submodule add https://github.com/GDKsoftware/delphi-mcp-server.git lib/mcpserver
  186. git submodule update --init --recursive
  187. ```
  188. #### Option 2: Direct Source Inclusion
  189. Copy the `src` folder from MCPServer into your project and add the units to your uses clauses.
  190. #### Delphi Project Configuration
  191. 1. **Search Paths**: Add the MCPServer source directories to your project search path:
  192. - `lib\mcpserver\src\Core`
  193. - `lib\mcpserver\src\Managers`
  194. - `lib\mcpserver\src\Protocol`
  195. - `lib\mcpserver\src\Server`
  196. - `lib\mcpserver\src\Tools`
  197. - `lib\mcpserver\src\Resources`
  198. - `lib\mcpserver\src\Prompts`
  199. 2. **Required Units**: `MCPServer.Host` is the only unit a host needs; it pulls
  200. in the managers, the HTTP server and the stdio transport:
  201. ```pascal
  202. MCPServer.Host, // TMCPServerHost, the library facade
  203. MCPServer.Types, // Interfaces, protocol constants, schema attributes
  204. MCPServer.Registration // TMCPRegistry, for self-registering tools
  205. ```
  206. Composing the managers by hand instead needs `MCPServer.Settings`,
  207. `MCPServer.ManagerRegistry`, `MCPServer.CoreManager`, the managers you want,
  208. and `MCPServer.IdHTTPServer` or `MCPServer.StdioTransport`.
  209. ### Library Integration
  210. `TMCPServerHost` (`MCPServer.Host`) is the whole composition behind one class:
  211. it builds the managers, owns the HTTP server and drives either transport.
  212. `StartHttp` returns as soon as the server listens, so the host fits into an
  213. application that has a message loop of its own:
  214. ```pascal
  215. program YourMCPServer;
  216. {$APPTYPE CONSOLE}
  217. uses
  218. System.SysUtils,
  219. MCPServer.Host in 'lib\mcpserver\src\Server\MCPServer.Host.pas',
  220. YourProject.Tool.Custom in 'YourProject.Tool.Custom.pas';
  221. begin
  222. const Host = TMCPServerHost.Create;
  223. try
  224. Host.Settings.Port := 3000;
  225. Host.AddTool(TCustomTool.Create);
  226. Host.StartHttp;
  227. Writeln('MCP Server running on port ', Host.BoundPort);
  228. Readln;
  229. Host.Stop;
  230. finally
  231. Host.Free;
  232. end;
  233. end.
  234. ```
  235. **What a host starts with.** Nothing. A fresh host publishes only the tools,
  236. resources, resource templates and prompts it was handed through `AddTool`,
  237. `AddResource` and `AddPrompt`, so two hosts in one process publish exactly what
  238. each of them was given. `SeedFromGlobalRegistry := True` takes everything from
  239. `TMCPRegistry` instead, which is what the standalone server does; set it before
  240. the first call that builds the managers, or it raises
  241. `EMCPConfigurationError`. `[Server] ExposeDiagnosticsResources` is honoured
  242. either way: with it off, `server://status`, `logs://recent` and `logs://{level}`
  243. never reach the lists.
  244. **Settings.** `Create` reads no file at all and starts from the built-in
  245. defaults, which `Host.Settings` then lets you change in code.
  246. `Create(SettingsFile)` reads the `.ini` you name and writes none.
  247. `Create(Settings)` takes a `TMCPSettings` you built yourself and keep owning.
  248. Only the standalone server reads `settings.ini` from the executable's own
  249. directory.
  250. **Ports.** `Settings.Port := 0` asks the operating system for a free port and
  251. `BoundPort` reports the one it gave. A loopback server takes that same port on
  252. both its IPv4 and its IPv6 binding, so `localhost` reaches it whichever family
  253. the client resolves first. `StartHttp` and `Stop` are both idempotent.
  254. **Transports.** `RunStdio` blocks and is a console entry point only: the stdio
  255. transport claims stdout and redirects the logger to stderr for the whole
  256. process, so a GUI application must never call it. `RunStdioWith(Input, Output)`
  257. runs the same dispatch over two streams, which is how a test drives one line in
  258. and reads one line out.
  259. Composing the managers by hand still works, and is what to do when you need a
  260. manager the host does not build:
  261. ```pascal
  262. var
  263. ManagerRegistry: IMCPManagerRegistry;
  264. begin
  265. const Settings = TMCPSettings.Create;
  266. try
  267. ManagerRegistry := TMCPManagerRegistry.Create;
  268. ManagerRegistry.RegisterManager(TMCPCoreManager.Create(Settings));
  269. ManagerRegistry.RegisterManager(TMCPToolsManager.Create(False));
  270. ManagerRegistry.RegisterManager(TMCPResourcesManager.Create(False));
  271. const Server = TMCPIdHTTPServer.Create(nil);
  272. try
  273. Server.Settings := Settings;
  274. Server.ManagerRegistry := ManagerRegistry;
  275. Server.Start;
  276. Writeln('MCP Server running on port ', Server.BoundPort);
  277. Readln;
  278. Server.Stop;
  279. finally
  280. Server.Free;
  281. end;
  282. finally
  283. Settings.Free;
  284. end;
  285. end.
  286. ```
  287. #### Library checklist
  288. - **Register before you start, or hand them over afterwards.** The parameterless `TMCPToolsManager.Create`, `TMCPResourcesManager.Create` and `TMCPPromptsManager.Create` read `TMCPRegistry` once, so a registration made after the managers exist is not picked up: register your tools, resources and prompts (normally from unit `initialization` sections) first. `Create(False)`, and a `TMCPServerHost` left at its default `SeedFromGlobalRegistry`, read the registry not at all and publish only what you hand them, which you can do at any time.
  289. - **STDIO: keep stdout clean.** Everything on stdout must be an MCP message. `TMCPStdioTransport.Create` forces `TLogger.UseStdErr := True` and sets `TLogger.StdoutReserved`, so console logging goes to stderr and an attempt to switch it back is refused with a one-time warning. Never `Writeln` from tools, managers or resources; log through `TLogger`.
  290. - **`server://status` is registered by default** by the unit initialization of `MCPServer.Resource.Server`, and reaches every manager that seeds from the registry. `TServerStatusResource.SetNamePrefix('myapp_')` renames it to `server://myapp_status`; call it before the managers are created. `[Server] ExposeDiagnosticsResources = false` keeps it, `logs://recent` and `logs://{level}` out of the lists altogether.
  291. - **Error codes and protocol constants** live in `MCPServer.Types` (`JSONRPC_*`, `MCP_ERROR_*`, `MCP_PROTOCOL_VERSION_*`, `MCP_META_*`, and the header names `MCP_HEADER_SESSION_ID`, `MCP_HEADER_PROTOCOL_VERSION`, `MCP_HEADER_METHOD` and `MCP_HEADER_NAME`). The `JSONRPC_*` names in `MCPServer.JsonRpcProcessor` remain as aliases. `TMCPHeaderValue.Encode` (`MCPServer.HttpHeaders`) writes a value into a header the way `TryDecode` reads one back: a header-safe value passes through, anything else is wrapped in the `=?base64?...?=` sentinel.
  292. - **Prompts and completion are optional managers**, registered the same way as tools and resources: `ManagerRegistry.RegisterManager(TMCPPromptsManager.Create)` and, if you want argument completion, `ManagerRegistry.RegisterManager(TMCPCompletionManager.Create(PromptsManager, ResourcesManager))` (it needs the concrete manager instances, not the `IMCPCapabilityManager` interface, to look prompts and resource templates up by name). The `prompts` and `completions` capabilities are only advertised when these managers are registered.
  293. ### Creating Custom Tools
  294. ```pascal
  295. unit YourProject.Tool.Custom;
  296. interface
  297. uses
  298. MCPServer.Tool.Base,
  299. MCPServer.Types,
  300. MCPServer.Registration;
  301. type
  302. TCustomToolParams = class
  303. private
  304. FInput: string;
  305. FCount: Integer;
  306. public
  307. [SchemaDescription('Text input to process')]
  308. property Input: string read FInput write FInput;
  309. [Optional]
  310. [SchemaDescription('Number of times to repeat (default: 1)')]
  311. property Count: Integer read FCount write FCount;
  312. end;
  313. TCustomTool = class(TMCPToolBase<TCustomToolParams>)
  314. protected
  315. function ExecuteWithParams(const AParams: TCustomToolParams): string; override;
  316. public
  317. constructor Create; override;
  318. end;
  319. implementation
  320. constructor TCustomTool.Create;
  321. begin
  322. inherited;
  323. FName := 'custom_tool';
  324. FDescription := 'A custom tool that processes input';
  325. end;
  326. function TCustomTool.ExecuteWithParams(const AParams: TCustomToolParams): string;
  327. var
  328. I: Integer;
  329. Output: string;
  330. begin
  331. Output := '';
  332. for I := 1 to AParams.Count do
  333. Output := Output + AParams.Input + #13#10;
  334. Result := 'Processed: ' + Output;
  335. end;
  336. initialization
  337. TMCPRegistry.RegisterTool('custom_tool',
  338. function: IMCPTool
  339. begin
  340. Result := TCustomTool.Create;
  341. end
  342. );
  343. end.
  344. ```
  345. Arguments are validated against the generated schema before the tool runs: a
  346. missing property without `[Optional]`, a value of the wrong JSON type or an
  347. unknown enumeration name is answered as an `isError` result that names the
  348. parameter. Integer properties are published as `integer`, `TDateTime` as a
  349. `string` with `format: date-time`, enumerations and sets with their names;
  350. `[SchemaTitle]`, `[SchemaFormat]`, `[SchemaMinimum]` and `[SchemaMaximum]`
  351. add the corresponding keywords.
  352. Dates and times travel as ISO 8601 strings in both directions, the shape
  353. their schema announces:
  354. | Delphi type | Schema | Written as | Read from |
  355. |---|---|---|---|
  356. | `TDateTime` | `string`, `format: date-time` | `2026-10-18T14:30:00.000+02:00` | an ISO 8601 date-time; without an offset it is local time |
  357. | `TDate` | `string`, `format: date` | `2026-10-18` | `yyyy-mm-dd` only |
  358. | `TTime` | `string` with a `pattern` and a description | `14:30:00`, or `14:30:00.250` | `hh:mm`, `hh:mm:ss`, `hh:mm:ss.fff` |
  359. A `TDateTime` with `Z` or an offset is converted to the local time of the
  360. server; one without keeps the clock time it was sent with, so
  361. `2026-10-18T14:30:00` arrives as 14:30 and goes back out with the local offset.
  362. A `TDate` is written without its time of day and a `TTime` without its date.
  363. A `TTime` carries no zone, so it is written without an offset, and a time with
  364. `Z` or an offset is refused rather than read as something it is not. That is
  365. why its schema has no `format: time`: JSON Schema defines that as RFC 3339
  366. `full-time`, which requires seconds and a zone offset. The `pattern` accepts
  367. exactly the text the server reads. A value of the wrong shape is refused with
  368. the shape the parameter expects. `[SchemaDescription]` and `[SchemaPattern]`
  369. on a `TTime` replace the generated description and pattern.
  370. #### Records in a schema
  371. A record is described exactly the way a class is: `type: object` with one
  372. `properties` member per **public field**, and a `required` array holding the
  373. fields that carry no `[Optional]`. Records nest, hold arrays, hold classes and
  374. sit inside classes; the walk stops at the same depth guard the class walk uses,
  375. so a record that reaches itself through a `TArray<T>` cannot recurse forever.
  376. Every attribute that works on a class property works on a record field:
  377. `[SchemaDescription]`, `[SchemaTitle]`, `[SchemaFormat]`, `[SchemaMinimum]`,
  378. `[SchemaMaximum]`, `[SchemaMinLength]`, `[SchemaMaxLength]`, `[SchemaPattern]`,
  379. `[SchemaDefault]`, `[SchemaName]` and `[Optional]`.
  380. ```pascal
  381. type
  382. TMoney = record
  383. [SchemaDescription('Amount in the smallest unit')]
  384. [SchemaMinimum(0)]
  385. Amount: Double;
  386. [SchemaName('currency_code')]
  387. [SchemaPattern('^[A-Z]{3}$')]
  388. Currency: string;
  389. [Optional]
  390. Note: string;
  391. end;
  392. ```
  393. ```json
  394. {
  395. "type": "object",
  396. "properties": {
  397. "amount": { "type": "number", "description": "Amount in the smallest unit", "minimum": 0 },
  398. "currency_code": { "type": "string", "pattern": "^[A-Z]{3}$" },
  399. "note": { "type": "string" }
  400. },
  401. "required": ["amount", "currency_code"]
  402. }
  403. ```
  404. The same shape crosses the wire in both directions: `MCPServer.Serializer`
  405. builds the record from a JSON object and writes it back out, with enumerations
  406. by name, `TDateTime`, `TDate` and `TTime` as ISO 8601, and an absent
  407. `[Optional]` field left at the default of its type. A record is a value, so
  408. nothing about it is freed after a call; an object a record holds is owned by
  409. the call and freed with it.
  410. **What a record needs from RTTI.** The generator reads a record's fields and
  411. their attributes through extended RTTI, so the unit that declares the record
  412. must publish field RTTI for the visibility the fields have. Delphi's default
  413. (`FIELDS([vcPrivate, vcProtected, vcPublic])`) already does, so a record in an
  414. ordinary unit needs nothing. A unit that narrows the setting must keep public
  415. fields in it:
  416. ```pascal
  417. {$RTTI EXPLICIT FIELDS([vcPublic])}
  418. ```
  419. A record whose fields are invisible has nothing to describe. As a property of a
  420. parameter class it keeps the `{"type": "string"}` every record was published as
  421. before, so a tool that has always listed goes on listing. As a parameter of a
  422. method tool it is refused instead, naming the record and this directive,
  423. because a tool written against this version should not ship a schema that does
  424. not match what the method takes.
  425. The same split applies to a type with no JSON shape at all: a pointer, a
  426. procedure or method reference, a class reference, an interface or a variant is
  427. published as `string` on the class walk, the way it always was, and refused as
  428. a method parameter, naming the parameter and its type. One property the
  429. generator cannot describe therefore never costs a `tools/list` its other tools.
  430. A field, property or array element whose type carries no RTTI at all is refused
  431. wherever it appears, naming the member, because there is nothing left to fall
  432. back on. Private fields are skipped silently, because a private field is not
  433. part of the wire.
  434. **`TGUID`.** A `TGUID` is a record, but its `D4` member is an anonymous array
  435. that `System` publishes no type for, so a `TGUID` has no members to walk. It is
  436. published as `{"type": "string", "format": "uuid"}` and travels as
  437. `f81d4fae-7dec-11d0-a765-00a0c91e6bf6`, written in lower case without braces
  438. and read with or without them.
  439. A tool that returns more than text overrides `ExecuteWithContext` and builds
  440. a `TMCPToolResult` (`MCPServer.Tool.Result`):
  441. ```pascal
  442. function TChartTool.ExecuteWithContext(const AParams: TChartParams;
  443. const Context: IMCPRequestContext): TValue;
  444. begin
  445. Result := TMCPToolResult.Create
  446. .AddText('Chart for ' + AParams.Series)
  447. .AddImage(RenderPng(AParams), 'image/png')
  448. .AddResourceLink('chart://' + AParams.Series, AParams.Series, '', 'image/png');
  449. end;
  450. ```
  451. The builder also has `AddAudio`, `AddEmbeddedText`, `AddEmbeddedBlob`,
  452. `WithAnnotations` (for the last block), `SetStructuredContent`, `SetMeta` and
  453. `SetError`. Raise `EMCPToolError` for a failure the model should see as an
  454. `isError` result; the request context gives the protocol era and the
  455. client's `_meta`. Tools that inherit from `TMCPToolBase<T, R>` return an
  456. object that becomes `structuredContent` plus a text block with the same
  457. JSON. Set `FAnnotations` or `FIcons` in the constructor to publish them in
  458. `tools/list`; `MarkReadOnly` writes the `readOnlyHint` and `openWorldHint`
  459. pair for a tool that only reads (pass `True` when it reaches outside the
  460. server). `MCPServer.Tool.ContentSamples`
  461. has one small example per content type.
  462. ### A tool from a method
  463. `TMCPMethodTool` (`MCPServer.Tool.Method`) turns a method you already have into
  464. a tool. The input schema comes from the parameter list, the arguments are
  465. marshalled onto it, the method is invoked, and its result is converted back to
  466. JSON:
  467. ```pascal
  468. type
  469. TOrderService = class
  470. public
  471. function PlaceOrder([SchemaDescription('Customer code')] const Customer: string;
  472. [Optional] const Quantity: Integer): string;
  473. end;
  474. var
  475. Context: TRttiContext;
  476. begin
  477. const Service = TOrderService.Create;
  478. const Method = Context.GetType(TOrderService).GetMethod('PlaceOrder');
  479. Host.AddTool(TMCPMethodTool.Create(TValue.From<TOrderService>(Service), Method,
  480. 'place_order', 'Places an order'));
  481. end;
  482. ```
  483. A parameter is published under its lower-cased name, or under `[SchemaName]`
  484. when it carries one, and is required unless it carries `[Optional]`; every
  485. schema attribute that works on a class property works on a parameter. The
  486. method needs RTTI, which a public method of a class compiled with the default
  487. `{$RTTI}` settings has, and `MarkReadOnly` writes the `readOnlyHint` pair the
  488. same way it does for `TMCPToolBase`.
  489. The result of a procedure is `{"ok": true}` and the result of a function is
  490. `{"result": <value>}`, which is what `GetOutputSchema` describes. A descendant
  491. that overrides `ResultToJson` replaces that object wholesale, so its envelope is
  492. the whole structured result and is not nested under `result`; such a descendant
  493. overrides `GetOutputSchema` with it, or the two disagree.
  494. **Who frees what.** Every object the tool marshalled from the arguments, and
  495. every object the method returned, is freed after the call, along with the
  496. elements of a returned dynamic array of objects. That is the wrong rule for a
  497. method that keeps what it is handed, which is the ordinary `Add(Item)` shape in
  498. Delphi, and for a method that hands back something it still owns. Both are
  499. virtual, so a descendant says so:
  500. ```pascal
  501. type
  502. TAdoptingTool = class(TMCPMethodTool)
  503. protected
  504. procedure ReleaseArguments(const Owned: TList<TObject>); override;
  505. procedure ReleaseResult(const Value: TValue; const ResultType: TRttiType); override;
  506. end;
  507. procedure TAdoptingTool.ReleaseArguments(const Owned: TList<TObject>);
  508. begin
  509. end;
  510. procedure TAdoptingTool.ReleaseResult(const Value: TValue; const ResultType: TRttiType);
  511. begin
  512. end;
  513. ```
  514. An untyped parameter, and a `var` or `out` parameter, have no place in a schema:
  515. a tool answers with its result, not through its arguments. Both are refused when
  516. the tool is created, with an `EArgumentException` naming the parameter.
  517. The three generator entry points are usable on their own:
  518. `TMCPSchemaGenerator.GenerateSchemaFromMethod` builds the input schema of a
  519. parameter list, `GenerateSchemaFromType` the schema of a single type, and
  520. `GenerateSchemaFromMethodResult` the `{"result": ...}` wrapper of a return type
  521. (`nil` for a procedure, and for a return type that has no JSON shape). `$schema`
  522. from `[SchemaDialect]` belongs to a root schema only and is never copied into a
  523. parameter or result member. The marshal underneath them is public too:
  524. `TMCPSerializer.JsonToValue` builds a `TValue` of a given `TRttiType` from a
  525. `TJSONValue` and appends every object it created to the list you pass, and
  526. `TMCPSerializer.ValueToJson` writes one back out.
  527. ### Asking the client for input (multi round-trip requests)
  528. MCP 2026-07-28 replaced server-initiated requests (`elicitation/create`,
  529. `sampling/createMessage`, `roots/list`) with multi round-trip requests: the
  530. server answers `tools/call`, `resources/read` or `prompts/get` with an
  531. `InputRequiredResult` that lists what it needs, the client gathers the
  532. answers and retries the same request with `inputResponses` (and the
  533. server's opaque `requestState`). A tool, resource or prompt that needs input
  534. raises `EMCPInputRequired` (`MCPServer.Mrtr`); the request context carries
  535. the answers on the retry:
  536. ```pascal
  537. function TGreetTool.ExecuteWithContext(const Params: TNoParams;
  538. const Context: IMCPRequestContext): TValue;
  539. var
  540. Response: TJSONObject;
  541. begin
  542. var Name := '';
  543. if Context.TryGetInputResponse('user_name', Response) then
  544. Name := TMCPInputResponse.ElicitationField(Response, 'name');
  545. if Name = '' then
  546. raise EMCPInputRequired.Create(TMCPInputRequests.Create
  547. .AddElicitation('user_name', 'What is your name?', TMCPInputRequests.FieldSchema('name')));
  548. Result := TMCPToolResult.Text(Format('Hello, %s!', [Name]));
  549. end;
  550. ```
  551. `TMCPInputRequests` builds the `inputRequests` map (`AddElicitation`,
  552. `AddSampling`, `AddListRoots`); `TMCPInputResponse` reads the answers
  553. (`ElicitationContent`, `ElicitationField`, `SamplingText`, `Roots`). The
  554. processor only sends input requests the client declared a capability for
  555. (`elicitation`, `sampling`, `roots`) and answers `-32021` otherwise, so a
  556. tool can check `Context.HasClientCapability` first and ask for what the
  557. client can deliver. Missing or wrong answers are handled by raising again:
  558. the client gets a fresh `InputRequiredResult`.
  559. State that must survive the round trip goes into the second constructor
  560. argument: `EMCPInputRequired.Create(Requests, State)` with a `TJSONObject`.
  561. The processor seals it into `requestState` (HMAC-SHA256 over the state, the
  562. method, a digest of the request parameters, the principal and an expiry)
  563. and opens it on the retry into `Context.RequestState`; a tampered, expired
  564. or foreign token is `-32602`. `[Security] RequestStateKey` in `settings.ini`
  565. is the signing secret (set the same value on every instance behind a load
  566. balancer; empty means a random key per process) and
  567. `RequestStateTtlSeconds` the token lifetime (600 by default).
  568. Clients on the 2025 revisions cannot answer input requests, so a request
  569. that raises `EMCPInputRequired` in the legacy era is answered with
  570. `-32603`. `MCPServer.Tool.InputRequiredSamples` and
  571. `test_input_required_result_prompt` are the examples the conformance suite
  572. exercises.
  573. ### Creating Custom Resources
  574. ```pascal
  575. unit YourProject.Resource.Custom;
  576. interface
  577. uses
  578. System.SysUtils,
  579. MCPServer.Resource.Base,
  580. MCPServer.Registration;
  581. type
  582. TCustomData = class
  583. private
  584. FMessage: string;
  585. FTimestamp: TDateTime;
  586. public
  587. property Message: string read FMessage write FMessage;
  588. property Timestamp: TDateTime read FTimestamp write FTimestamp;
  589. end;
  590. TCustomResource = class(TMCPResourceBase<TCustomData>)
  591. protected
  592. function GetResourceData: TCustomData; override;
  593. public
  594. constructor Create; override;
  595. end;
  596. implementation
  597. constructor TCustomResource.Create;
  598. begin
  599. inherited;
  600. FURI := 'custom://data';
  601. FName := 'Custom Data';
  602. FDescription := 'Custom resource data';
  603. FMimeType := 'application/json';
  604. end;
  605. function TCustomResource.GetResourceData: TCustomData;
  606. begin
  607. Result := TCustomData.Create;
  608. Result.Message := 'Hello from custom resource';
  609. Result.Timestamp := Now;
  610. end;
  611. initialization
  612. TMCPRegistry.RegisterResource('custom://data',
  613. function: IMCPResource
  614. begin
  615. Result := TCustomResource.Create;
  616. end
  617. );
  618. end.
  619. ```
  620. `FTitle`, `FSize` and `FAnnotations` are published in `resources/list`;
  621. `FTtlMs` and `FCacheScope` (`private` unless set) are the cache hints modern
  622. clients get on `resources/read`. A binary resource implements
  623. `IMCPBinaryResource.ReadBinary` and is delivered as a `blob`;
  624. `MCPServer.Resource.Samples` shows a text and a binary example. A URI that is
  625. not registered is answered with a JSON-RPC error (`-32002` for
  626. initialize-based clients, `-32602` for modern clients), a read that raises
  627. with `-32603`.
  628. ### Resource Templates
  629. A template matches a family of URIs and resolves the actual resource from
  630. the captured variables. It supports RFC 6570 level 1 (`{var}`, one path
  631. segment) and a level 2 subset (`{+var}`, the rest of the URI including
  632. `/`); `{/var}` and `{?var}` are not implemented.
  633. ```pascal
  634. unit YourProject.Resource.CustomTemplate;
  635. interface
  636. uses
  637. MCPServer.Resource.Base,
  638. MCPServer.Registration;
  639. type
  640. TCustomTemplate = class(TMCPResourceTemplateBase)
  641. public
  642. constructor Create; override;
  643. function CreateResource(const URI: string; Vars: TMCPTemplateVars): IMCPResource; override;
  644. end;
  645. implementation
  646. constructor TCustomTemplate.Create;
  647. begin
  648. inherited;
  649. FUriTemplate := 'custom://{id}';
  650. FName := 'Custom item';
  651. FMimeType := 'application/json';
  652. end;
  653. function TCustomTemplate.CreateResource(const URI: string; Vars: TMCPTemplateVars): IMCPResource;
  654. begin
  655. Result := TCustomResource.CreateForId(URI, Vars['id']);
  656. end;
  657. initialization
  658. TMCPRegistry.RegisterResourceTemplate('custom://{id}',
  659. function: IMCPResourceTemplate
  660. begin
  661. Result := TCustomTemplate.Create;
  662. end
  663. );
  664. end.
  665. ```
  666. `CreateResource` gets the actual requested URI (not the template) and the
  667. captured variables, and returns an ordinary `IMCPResource` (typically a
  668. `TMCPResourceBase<T>` with a constructor of your own choosing, since the
  669. registry never constructs a template's resources itself); `resources/read`
  670. tries an exact match first, then each registered template in order. See
  671. `MCPServer.Resource.Samples` (`test://template/{id}/data`) and
  672. `MCPServer.Resource.Logs` (`logs://{level}`, reusing the existing log
  673. filtering) for worked examples.
  674. ### Creating Custom Prompts
  675. ```pascal
  676. unit YourProject.Prompt.Custom;
  677. interface
  678. uses
  679. MCPServer.Types,
  680. MCPServer.Prompt.Base,
  681. MCPServer.Registration;
  682. type
  683. TCustomPromptParams = class
  684. private
  685. FTopic: string;
  686. public
  687. [SchemaDescription('What to write about')]
  688. property Topic: string read FTopic write FTopic;
  689. end;
  690. TCustomPrompt = class(TMCPPromptBase<TCustomPromptParams>)
  691. protected
  692. function ExecuteWithParams(const Params: TCustomPromptParams;
  693. Messages: TMCPPromptMessages): string; override;
  694. public
  695. constructor Create; override;
  696. end;
  697. implementation
  698. constructor TCustomPrompt.Create;
  699. begin
  700. inherited;
  701. FName := 'custom_prompt';
  702. FDescription := 'Asks the model to write about a topic';
  703. end;
  704. function TCustomPrompt.ExecuteWithParams(const Params: TCustomPromptParams;
  705. Messages: TMCPPromptMessages): string;
  706. begin
  707. Messages.AddText('user', 'Write a short paragraph about ' + Params.Topic + '.');
  708. Result := 'Writing prompt';
  709. end;
  710. initialization
  711. TMCPRegistry.RegisterPrompt('custom_prompt',
  712. function: IMCPPrompt
  713. begin
  714. Result := TCustomPrompt.Create;
  715. end
  716. );
  717. end.
  718. ```
  719. The argument list in `prompts/list` comes from `T`'s string properties, the
  720. same `[SchemaDescription]`/`[Optional]` attributes tools use; a required
  721. argument missing from `arguments` is `-32602`, since `prompts/get` has no
  722. `isError` result to report it through instead. `TMCPPromptMessages` builds
  723. the messages: `AddText`, `AddImage`, `AddAudio`, `AddResourceLink`,
  724. `AddEmbeddedText`, `AddEmbeddedBlob`, `AddEmbeddedResource` (wraps an
  725. existing `IMCPResource`) and `WithAnnotations` for the last message added.
  726. For a prompt with no natural parameter class, derive from the non-generic
  727. `TMCPPromptBase` instead and set `FArguments` directly. `MCPServer.Prompt.SummarizeLogs`
  728. and `MCPServer.Prompt.ContentSamples` show both content and templates in use.
  729. A prompt or resource template that wants to offer argument completion
  730. implements `IMCPCompletable` (`function Complete(const ArgumentName, Value: string;
  731. const Context: TArray<TPair<string, string>>): TMCPCompletion`); a target
  732. that does not implement it answers `completion/complete` with an empty
  733. `values` array rather than an error, since not offering completion is a
  734. valid choice.
  735. ### Protocol extensions
  736. Protocol version 2026-07-28 lets a server offer extensions next to the core
  737. protocol, such as `io.modelcontextprotocol/tasks`. An extension is a capability
  738. manager that also implements `IMCPExtensionProvider`:
  739. ```pascal
  740. function GetExtensionId: string; // 'com.example/my-extension'
  741. function GetExtensionSettings: TJSONObject; // caller owns it; empty object for no settings
  742. function GetResultTypes: TArray<string>; // result types beyond complete/input_required
  743. ```
  744. Register the manager like any other (`ManagerRegistry.RegisterManager`) and
  745. `server/discover` lists it under `capabilities.extensions`. A client declares
  746. the extensions it supports per request in
  747. `_meta["io.modelcontextprotocol/clientCapabilities"].extensions`; check that
  748. with `Context.HasClientExtension(Id)` and fall back to core behaviour when it
  749. is missing, or call `Context.RequireClientExtension(Id)` to answer `-32021`
  750. when the request cannot be served without it. A result with a `resultType`
  751. the extension owns is only sent to a client that declared the extension on
  752. that request; the processor turns anything else into `-32603`, so a client
  753. never receives a result type it did not ask for.
  754. ### Long-running tool calls (tasks)
  755. A tool call normally has to finish within the client's request timeout. With
  756. the Tasks extension (`io.modelcontextprotocol/tasks`) a tool answers with a
  757. task instead; the client polls it with `tasks/get`, answers questions with
  758. `tasks/update` and stops it with `tasks/cancel`. The extension is off by
  759. default; switch it on in `settings.ini`:
  760. ```ini
  761. [Tasks]
  762. Enabled=1
  763. MaxRunningTasks=8 ; tool calls the server runs in the background at once
  764. TtlMs=3600000 ; how long a task stays retrievable; 0 = unlimited
  765. PollIntervalMs=1000 ; polling interval suggested to clients
  766. ```
  767. or set `Host.Settings.TasksEnabled := True` before the host builds its
  768. managers. A task only exists for a client that declares the extension on the
  769. request; every other client keeps getting the synchronous result.
  770. **A tool the server runs in the background.** Mark the tool class with
  771. `[TaskExecution]` (`MCPServer.Task.Types`):
  772. ```pascal
  773. [TaskExecution(TMCPTaskExecution.Optional)]
  774. TBuildTool = class(TMCPToolBase<TBuildParams>)
  775. ```
  776. `Optional` runs the tool as a task when the client supports tasks and
  777. synchronously otherwise; `Required` answers `-32021` to a client without the
  778. extension, and `-32603` while tasks are switched off. The server runs the tool on a thread pool of its own, limited to
  779. `MaxRunningTasks`, so long calls do not occupy `TThreadPool.Default`. Inside
  780. the tool nothing changes: `Context.CheckCancelled` raises once the client
  781. cancels the task, and `EMCPInputRequired` puts the task in `input_required`
  782. with the tool's input requests. When the client has answered all of them
  783. with `tasks/update`, the server runs the tool again with every answer so
  784. far, the same way a multi round-trip request is retried. A task that waits
  785. for input holds no thread, so it does not count against `MaxRunningTasks`. Progress and log
  786. notifications are not sent for a task. `Context.TaskId` holds the id of the
  787. task the tool runs for, and is empty when the tool runs synchronously.
  788. **Work that runs outside the request.** A tool that hands the work to the
  789. host, such as a build queue, implements `IMCPTaskStarter`:
  790. ```pascal
  791. procedure TBuildTool.StartTask(const Arguments: TJSONObject; const Task: IMCPTaskHandle);
  792. begin
  793. FBuildQueue.Enqueue(Arguments.GetValue<string>('project'), Task);
  794. end;
  795. ```
  796. A starter without `[TaskExecution]` is `Required`. Mark it
  797. `[TaskExecution(TMCPTaskExecution.Optional)]` to serve clients without the
  798. extension as well: they get the result of the tool's normal `Execute`, as the
  799. specification forbids a `CreateTaskResult` for a client that did not declare
  800. the extension.
  801. A starter that needs the request, such as the principal or the client's
  802. declared capabilities, implements `IMCPContextTaskStarter` instead; its
  803. `StartTask` also gets the `IMCPRequestContext` of the `tools/call`. A tool
  804. implements one of the two interfaces.
  805. `StartTask` runs on the request thread once the task exists; `Arguments` is
  806. only valid during the call. Raise `EMCPInputRequired` there for input that is
  807. needed before the task is created: the client then gets a normal
  808. `input_required` result and no task is left behind. The host reports
  809. progress from any thread through the handle: `SetStatusMessage`,
  810. `RequestInput` and `WaitForInput`, `Complete` (a `TMCPToolResult` or its
  811. JSON), `Fail` (a JSON-RPC error, which makes the task `failed`) and
  812. `IsCancelled`. A task that is completed, failed or cancelled keeps that
  813. status; later calls on its handle change nothing. `Host.Tasks.TryGetTask`
  814. returns the handle of a task by id.
  815. The server always generates the task id, with enough entropy that it cannot
  816. be guessed, as the specification requires. To tie a task to a job of its own,
  817. the host sets `Task.HostReference` (for example a job id) in `StartTask`. The
  818. store keeps it with the task, so a durable store can look up the job when the
  819. task is read, updated or cancelled; it is never sent to the client.
  820. **Keeping tasks across restarts.** Tasks live in an `IMCPTaskStore`; the
  821. default keeps them in memory. Implement the interface on your own database
  822. and set `Host.TaskStore` before the host builds its managers. `TryUpdate`
  823. must refuse to change a task that is already completed, failed or cancelled.
  824. The store holds the result, the error and the input requests as JSON text,
  825. and keeps `HostReference` as given.
  826. After a restart nothing runs for a task that was still `working`; the host
  827. decides what happens to it through `Host.Tasks.TryGetTask`. Stopping the
  828. server tells the work it runs to stop (`IsCancelled` becomes true and the
  829. request context of a running tool is cancelled), but leaves every task in the
  830. store as it was: only a client's `tasks/cancel` makes a task `cancelled`, as
  831. the specification reserves cancellation for the client.
  832. A task is bound to the principal that created it: `tasks/get`, `tasks/update`
  833. and `tasks/cancel` from any other caller answer `-32602`, the same as for an
  834. unknown task id. Status notifications (`notifications/tasks`) are not sent
  835. yet; clients poll.
  836. ## Integration with Claude Code
  837. Configure using the Streamable HTTP transport:
  838. ```bash
  839. # Basic configuration
  840. claude mcp add --transport http delphi-mcp-server http://localhost:3000/mcp
  841. # With authentication (if configured)
  842. claude mcp add --transport http delphi-mcp-server http://localhost:3000/mcp --header "Authorization: Bearer your-token"
  843. ```
  844. Make sure the server is running before connecting Claude Code.
  845. ## Integration with Codex
  846. Configure Codex to use the STDIO transport. Edit your Codex configuration file (`~/.codex/config.toml`):
  847. ```toml
  848. [mcp_servers.delphi-mcp-server]
  849. command = 'C:\path\to\MCPServer.exe'
  850. args = ["--stdio"]
  851. ```
  852. Or on Linux/macOS:
  853. ```toml
  854. [mcp_servers.delphi-mcp-server]
  855. command = '/path/to/MCPServer'
  856. args = ["--stdio"]
  857. ```
  858. **Important**: The server must be compiled and the executable path must be absolute.
  859. After configuration:
  860. 1. Restart Codex
  861. 2. Use `/mcp` command to verify the server is connected
  862. 3. Available tools will appear in the Codex interface
  863. ### HTTPS/SSL Configuration
  864. The server supports HTTPS connections when configured with SSL certificates:
  865. 1. **Generate SSL Certificates**:
  866. ```bash
  867. # Generate self-signed certificates (for development)
  868. generate-ssl-cert.bat
  869. ```
  870. This creates certificates in the `certs` directory.
  871. 2. **Configure SSL in settings.ini**:
  872. ```ini
  873. [SSL]
  874. Enabled=1 ; Use 1 (true) or 0 (false)
  875. CertFile=C:\path\to\server.crt
  876. KeyFile=C:\path\to\server.key
  877. RootCertFile=C:\path\to\ca.crt ; Optional
  878. ```
  879. 3. **Start the server**:
  880. The server will automatically use HTTPS when SSL is enabled.
  881. **Note**: For production, use certificates from a trusted Certificate Authority (CA) instead of self-signed certificates.
  882. ## Testing with MCP Inspector
  883. The easiest way to test and debug your MCP server is using the official MCP Inspector:
  884. 1. **Start the server**:
  885. ```bash
  886. # Build and run the server
  887. build.bat
  888. Win32\Debug\MCPServer.exe
  889. ```
  890. 2. **Run MCP Inspector**:
  891. ```bash
  892. # Install and run the MCP Inspector
  893. npx @modelcontextprotocol/inspector
  894. ```
  895. 3. **Connect to your server**:
  896. - **Transport**: HTTP
  897. - **URL**: `http://localhost:3000/mcp`
  898. - Click **Connect**
  899. 4. **Test functionality**:
  900. - Browse available tools and resources
  901. - Execute tools like `echo`, `get_time`, `calculate`
  902. - View resources like `project://info`, `server://status`
  903. - Monitor request/response JSON-RPC messages
  904. The Inspector provides a web interface to interact with your MCP server, making it perfect for development and debugging.
  905. ## Available Example Tools
  906. - **echo**: Echo a message back to the user
  907. - **get_time**: Get the current server time
  908. - **list_files**: List files in a directory
  909. - **calculate**: Perform basic arithmetic calculations
  910. - **test_simple_text**, **test_image_content**, **test_audio_content**,
  911. **test_embedded_resource**, **test_multiple_content_types**,
  912. **test_error_handling**, **test_tool_with_progress**, **test_logging_tool**:
  913. one small tool per content type, one that fails, one that reports progress
  914. and honours cancellation, and one that logs at every level, from
  915. `MCPServer.Tool.ContentSamples`; the conformance suite calls these by name
  916. - **json_schema_2020_12_tool**: a hand-written schema exercising `$schema`,
  917. `$defs`, `$anchor`, `$ref`, `allOf`/`anyOf` and `if`/`then`/`else`, for the
  918. conformance suite's schema-preservation check
  919. - **test_input_required_result_elicitation**, **..._sampling**,
  920. **..._list_roots**, **..._request_state**, **..._multiple_inputs**,
  921. **..._multi_round**, **..._tampered_state**, **..._capabilities**: multi
  922. round-trip requests, one per kind of client input plus signed request
  923. state across one or two round trips, from
  924. `MCPServer.Tool.InputRequiredSamples`; **test_missing_capability**
  925. requires the `sampling` client capability and answers `-32021` without it,
  926. **test_streaming_elicitation** logs to the response stream and then asks
  927. for a confirmation
  928. - **test_trigger_tool_change**, **test_trigger_prompt_change**,
  929. **test_trigger_resource_change**: add or remove `test_dynamic_tool` and
  930. `test_dynamic_prompt`, or report `test://static-text` as updated, so that
  931. clients on `subscriptions/listen` receive the change notifications, from
  932. `MCPServer.Tool.SubscriptionSamples`
  933. - **greet**, **slow_compute**, **failing_job**, **protocol_error_job**,
  934. **confirm_delete**, **multi_input**, **test_tool_with_task**: the fixtures
  935. of the conformance suite's tasks scenarios, from
  936. `MCPServer.Tool.TaskSamples`; they run as tasks when `[Tasks] Enabled=1`
  937. and the client supports the extension
  938. ## Available Example Prompts
  939. - **summarize_logs**: summarizes the server's recent log entries, optionally
  940. filtered by level (argument completion suggests the levels actually
  941. present in the log buffer)
  942. - **test_simple_prompt**, **test_prompt_with_arguments**,
  943. **test_prompt_with_embedded_resource**, **test_prompt_with_image**: one
  944. prompt per content type, from `MCPServer.Prompt.ContentSamples`; the
  945. conformance suite calls these by name
  946. - **test_input_required_result_prompt**: asks the client for a context
  947. through an elicitation input request before it renders
  948. ## Available Example Resources
  949. The server provides six resources and two resource templates, accessible via URIs:
  950. - **server://status** - Current server status and health information (request and connection counters)
  951. - **project://info** - Project information (JSON metadata with collections)
  952. - **project://readme** - This README file (markdown content)
  953. - **logs://recent** - Recent log entries from all categories (with thread safety)
  954. - **logs://{level}** - Recent log entries at one level, e.g. `logs://WARNING`
  955. - **test://template/{id}/data** - A template resource for the conformance suite
  956. - **test://static-text** - A fixed text resource
  957. - **test://static-binary** - A fixed PNG image, delivered as a `blob`
  958. ## Configuration
  959. The server supports configuration through `settings.ini` files. A default `settings.ini.example` is provided in the repository.
  960. ### Authentication
  961. The HTTP endpoint is open by default, which is fine for a loopback-only
  962. server. A server that other machines can reach should require a token:
  963. - `[Auth] BearerTokens`: comma-separated pre-shared tokens. With this set the
  964. executable installs `TMCPStaticBearerAuthorizer`; every request except
  965. `OPTIONS` and the protected resource metadata must carry
  966. `Authorization: Bearer <token>`. A missing token is `401` with a
  967. `WWW-Authenticate: Bearer` challenge, an unknown token `401` with
  968. `error="invalid_token"`, another scheme `400` with `error="invalid_request"`.
  969. Tokens are compared in constant time and never logged.
  970. - `[Auth] AuthorizationServers`: issuer URLs of the OAuth 2.1 authorization servers, published in `GET /.well-known/oauth-protected-resource` and `/.well-known/oauth-protected-resource<Endpoint>` (RFC 9728) and referenced by the `resource_metadata` parameter of every challenge, so clients can discover where to obtain a token. `ResourceUri` is the canonical URI of this server that the tokens must name as their audience (default `<Protocol>://<Host>:<Port><Endpoint>`); when it is set, the `resource_metadata` URL is derived from it (`https://host/mcp` gives `https://host/.well-known/oauth-protected-resource/mcp`), so a server behind a reverse proxy points clients at its public address. The server also answers that metadata path itself, so a `ResourceUri` whose path differs from `Endpoint` (for example `https://host/tenant/mcp` behind a proxy that forwards `/tenant/mcp` to `/mcp`) still resolves when the proxy forwards the well-known path unchanged. `ScopesSupported` lists the scopes clients may request (`offline_access` is never advertised).
  971. A library that hosts `TMCPIdHTTPServer` assigns its own `Authorizer`
  972. (`MCPServer.Authorization`):
  973. - `TMCPStaticBearerAuthorizer.Create(Tokens, Scopes)`: the pre-shared tokens,
  974. optionally limited to a set of scopes (all scopes by default).
  975. - `TMCPOAuthResourceServerAuthorizer`: the base for token validation against
  976. an authorization server. Override `ValidateToken(Token, out Claims)`; the
  977. base class then requires the `aud` claim to name `ExpectedAudience`, the
  978. `exp` claim to lie in the future, and the `RequiredScopes` to be present in
  979. `scope` or `scp`, answering `401 invalid_token` or `403 insufficient_scope`
  980. otherwise. `TMCPIntrospectionAuthorizer` implements `ValidateToken` with an
  981. RFC 7662 token introspection request (client credentials over HTTP basic
  982. authentication). Signed-JWT validation is not built in: the RTL has no JOSE
  983. library, so a deployment that validates JWTs locally supplies its own
  984. `ValidateToken` on top of its JWT library of choice.
  985. - `[RequiresScope('name')]` on a tool class makes `tools/call` answer `403`
  986. with `WWW-Authenticate: Bearer error="insufficient_scope", scope="name"`
  987. unless the caller's token grants that scope. On an open server, and over
  988. stdio, nobody holds a scope, so such a tool is unusable there.
  989. Tools see the authenticated caller as `Context.Principal` and
  990. `Context.HasScope`. The inbound token is bound to this server: a tool that
  991. calls an upstream API must obtain its own credentials and must never forward
  992. the `Authorization` header it was called with. Authentication is an HTTP
  993. concern; the stdio transport trusts the process that spawned it and never
  994. consults an authorizer.
  995. ### Network and Security
  996. - `[Server] BindAddress`: the interface to listen on. Empty (default) derives it from `Host`: a loopback `Host` binds `127.0.0.1` and `::1`, any other `Host` binds every interface. Set `0.0.0.0` to listen everywhere explicitly.
  997. - `[Security] AllowedOrigins`: origins that pass the `Origin` check next to the loopback origins (`localhost`, `127.0.0.1`, `[::1]`, any port). Comma-separated `scheme://host[:port]`; `:*` allows any port; `*` allows everything. Falls back to `[CORS] AllowedOrigins`. A rejected origin gets `403` with a JSON-RPC error body, also when CORS is disabled.
  998. - `[Security] AllowedHosts`: `Host` header values the server answers, comma-separated `host[:port]` (an entry without a port matches any port, `*` matches everything). Empty means any host. Set it when the server is reachable through a public name, so that a rebinding DNS name cannot reach it; a rejected host gets `403`.
  999. - `[Server] ExposeDiagnosticsResources`: `1` (default) registers `logs://recent`, `logs://{level}` and `server://status`; set `0` on a server that strangers can reach, the log buffer and the status counters are diagnostics.
  1000. - `[CORS] Enabled`: adds the CORS response headers for browser clients; the `Origin` check runs regardless.
  1001. - `[Server] EndpointInfoPath`: optional GET path (for example `/info`) that answers a JSON document with the endpoint URL and the protocol versions. The MCP endpoint itself only accepts POST; GET and DELETE get `405`.
  1002. - `[Server] MaxRequestBodyBytes` (4 MB) and `MaxJsonDepth` (64): larger or deeper requests get `413` or `400`; `MaxConnections`: Indy connection limit, `0` = unlimited.
  1003. ### SSL/TLS Configuration
  1004. The Delphi MCP Server supports two SSL/TLS implementations:
  1005. 1. **Standard Indy SSL** - Uses OpenSSL 1.0.2 (default if TaurusTLS not available)
  1006. 2. **TaurusTLS** - Uses OpenSSL 3.x or 4.x with modern cipher support (recommended)
  1007. #### Installing TaurusTLS
  1008. TaurusTLS provides OpenSSL 3.x and 4.x support with modern ECDHE cipher suites required by services like Cloudflare.
  1009. **Via a package manager (easiest):**
  1010. - **GetIt** (RAD Studio): Tools > GetIt Package Manager, search for "TaurusTLS", click Install
  1011. - **DPM**: `dpm install TaurusTLS_Developers.TaurusTLS`
  1012. - **TMS Smart Setup**: `tms install taurustls_developers.taurustls`
  1013. **Manual Installation:**
  1014. 1. Clone from https://github.com/TaurusTLS-Developers/TaurusTLS
  1015. 2. Open `TaurusTLS\Packages\d12\TaurusAll.groupproj`
  1016. 3. Compile `TaurusTLS_RT`
  1017. 4. Compile and install `TaurusTLS_DT`
  1018. All installation options are documented at https://taurustls.org/download.xhtml
  1019. #### Switching Between SSL Implementations
  1020. Edit `src\Server\MCPServer.IdHTTPServer.pas`:
  1021. ```pascal
  1022. // To use TaurusTLS (OpenSSL 3.x/4.x):
  1023. {$DEFINE USE_TAURUS_TLS} // Keep this line uncommented
  1024. // To use Standard Indy SSL (OpenSSL 1.0.2):
  1025. // {$DEFINE USE_TAURUS_TLS} // Comment out this line
  1026. ```
  1027. #### OpenSSL Requirements
  1028. **For TaurusTLS:**
  1029. TaurusTLS runs on OpenSSL 3.x and 4.x. Pre-compiled binaries for every supported platform, including Windows on ARM64, are published at https://github.com/TaurusTLS-Developers/OpenSSL-Distribution/releases. Full deployment instructions: https://taurustls.org/deployapps.xhtml
  1030. > **OpenSSL 4.x requires TaurusTLS 1.0.5.42 or newer.** Earlier releases only look for the 3.x, 1.1 and 1.0 library names, so a build linked against them fails at startup with `ETaurusTLSCouldNotLoadSSLLibrary: Could not load SSL library` when only 4.x libraries are present. Check `DefaultLibVersions` in `TaurusTLSConsts.pas` if you are unsure which version you have.
  1031. *Windows (dynamic linking):*
  1032. Ship the OpenSSL DLLs and `LICENSE.txt` alongside your executable:
  1033. | Target | OpenSSL 3.x | OpenSSL 4.x |
  1034. |--------|-------------|-------------|
  1035. | Win32 | `libcrypto-3.dll`, `libssl-3.dll` | `libcrypto-4.dll`, `libssl-4.dll` |
  1036. | Win64 | `libcrypto-3-x64.dll`, `libssl-3-x64.dll` | `libcrypto-4-x64.dll`, `libssl-4-x64.dll` |
  1037. | Windows ARM64EC | `libcrypto-3-arm64.dll`, `libssl-3-arm64.dll` | `libcrypto-4-arm64.dll`, `libssl-4-arm64.dll` |
  1038. Instead of copying DLLs by hand, the OpenSSL-Distribution releases also ship automated installers you can run yourself or chain from your own installer:
  1039. - **InnoSetup installer** (`openssl-<version>-Windows-installer.exe`) - one setup covering x86, x64 and ARM64EC, picking the matching runtime by CPU detection. Silent install:
  1040. ```
  1041. openssl-<version>-Windows-installer.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART
  1042. ```
  1043. - **MSIX framework packages** (`openssl-<version>-Windows-x64.msix`, `-x86.msix`, `-arm64ec.msix`) - reference them from your own `AppxManifest.xml` as a `PackageDependency` on `TaurusTLS.OpenSSL`.
  1044. *Linux (dynamic linking):*
  1045. - OpenSSL is usually installed by default; document the dependency for your end users
  1046. - Update if needed: `sudo apt-get install libssl-dev` (Debian/Ubuntu) or `sudo yum install openssl-devel` (RHEL/CentOS)
  1047. - To pin a specific version, redistribute the Linux package from the OpenSSL-Distribution releases
  1048. *macOS, iOS and Android (static linking):*
  1049. - OpenSSL is compiled into the application binary; build against the `.a` files in the `lib\static` folder of the platform archive (for example `openssl-<version>-macOS-arm64.zip`)
  1050. - Nothing to redistribute besides your application package and `LICENSE.txt`
  1051. **For Standard Indy:**
  1052. - Requires OpenSSL 1.0.2 DLLs (`libeay32.dll`, `ssleay32.dll`)
  1053. - Limited cipher support, not recommended for modern clients
  1054. #### Known Issues & Solutions
  1055. - **Cloudflare Tunnel**: Standard Indy SSL lacks ECDHE cipher support. Use TaurusTLS or run Cloudflare Tunnel with HTTP: `cloudflared tunnel --url http://localhost:8080`
  1056. - **Self-Signed Certificates**: Claude Desktop doesn't accept self-signed certificates. Use Cloudflare Tunnel or a valid certificate from a trusted CA
  1057. - **"No shared cipher" error**: Install and enable TaurusTLS for modern cipher support
  1058. - **`Could not load SSL library`**: no OpenSSL library TaurusTLS recognises was found. Either the libraries are not where the platform looks for them, or your TaurusTLS version predates 4.x support (see above)
  1059. - **The wrong OpenSSL gets loaded**: TaurusTLS asks the OS for the libraries by name, trying the version suffixes newest first, and takes the first hit anywhere on the platform's library search path. Another OpenSSL installation can therefore win over the one you shipped, and your application runs on a version you never tested. Set the `OPENSSL_LIBRARY_PATH` environment variable to an absolute directory to pin the choice; it applies on every platform
  1060. ## License
  1061. This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
  1062. ## Contributing
  1063. We welcome contributions! Here's how to help:
  1064. ### Reporting Issues
  1065. - Use [GitHub Issues](https://github.com/GDKsoftware/delphi-mcp-server/issues) for bugs and feature requests
  1066. - Include Delphi version, platform, and reproduction steps
  1067. ### Pull Requests
  1068. 1. Fork the repository
  1069. 2. Create a feature branch: `git checkout -b feature/my-feature`
  1070. 3. Follow the existing code style: inline variables, named constants instead of literals, typed exceptions, no comments in code
  1071. 4. Test your changes
  1072. 5. Submit a pull request
  1073. ### Development Setup
  1074. - Requires Delphi 11 Alexandria or later; the project files target Delphi 12 Athens
  1075. - Open `MCPServer.dproj` or build with `build.bat`; on Alexandria use `MCPServer.D11.dproj`
  1076. - Test with `npx @modelcontextprotocol/inspector` or Claude Code or similar
  1077. ### Automated tests
  1078. The `tests` folder holds a DUnitX project that drives the JSON-RPC layer, the HTTP transport and the stdio transport in-process and pins the wire behaviour with golden files (`tests\golden`, see the README there).
  1079. ```bat
  1080. build-tests.bat Debug Win64
  1081. tests\Win64\Debug\MCPServerTests.exe
  1082. ```
  1083. `build-tests.bat [Config] [Platform]` compiles `tests\MCPServerTests.dpr` for Win32 or Win64; the program takes the usual DUnitX switches (`-xml:<file>` for an NUnit report, `-run:<test>` for a selection). Set the environment variable `MCP_GOLDEN_RECORD=1` for one run to re-record the golden expectations, then review the diff.
  1084. ### Conformance suite
  1085. `conformance.bat` runs the [MCP conformance suite](https://github.com/modelcontextprotocol/conformance) against a build of the server: it starts `MCPServer.exe` from a temporary folder with tasks enabled on a free port, runs the active server suite and the tasks scenarios, and stops the server again.
  1086. ```bat
  1087. build.bat Release Win64
  1088. conformance.bat -ConformancePath C:\dev\conformance
  1089. ```
  1090. `-Platform` and `-Config` pick the build (default `Win64` `Release`). `-ConformancePath` (or the environment variable `MCP_CONFORMANCE_PATH`) points to a clone of the conformance repository with `npm install` run in it; without it the published npm package runs, which may not know the newest scenarios yet. `conformance-baseline.yml` lists the failures the server is known to have, with the reason for each; the script fails on any other failure and on a baseline entry that starts to pass. Note that `build.bat` stops every running `MCPServer.exe`, so do not build while the suite runs.
  1091. ## About GDK Software
  1092. [GDK Software](https://www.gdksoftware.com) is a Delphi specialist: we build, upgrade and maintain Delphi applications worldwide, and offer Delphi and AI consultancy and AI training.
  1093. ## Support
  1094. - Create an issue on [GitHub](https://github.com/GDKsoftware/delphi-mcp-server/issues)
  1095. - Visit our website at [www.gdksoftware.com](https://www.gdksoftware.com)
  1096. ## Commercial Support
  1097. This library is MIT licensed and free to use. For companies that depend on it commercially we offer support and maintenance agreements with guaranteed response times, and sponsored development of features you need, such as upcoming MCP specification revisions. Contact us at [gdksoftware.com/contact-us](https://gdksoftware.com/contact-us) or open an issue to get in touch.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.