dolibarr 25.0.0-alpha
mcp.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2026 Nick Fragoulis
4 * Copyright (C) 2026 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY, without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 * or see https://www.gnu.org/
19 */
20
27require_once DOL_DOCUMENT_ROOT . "/ai/class/mcptool.class.php";
28
40{
41 const CTX_ASSISTANT = 'assistant';
42
43 const CTX_MCP_SERVER = 'mcp_server';
44
46 private $db;
47
49 private $user;
50
52 private $conf;
53
57 public $loadedTools = [];
58
63 public $toolsByName = [];
64
65
70 private $toolcontext;
71
81 public function __construct($db, $user, $conf_obj = null, $toolcontext = '')
82 {
83 $this->db = $db;
84 $this->user = $user;
85
86 if ($conf_obj === null) {
87 global $conf;
88 $conf_obj = $conf;
89 }
90 $this->conf = $conf_obj;
91
92 $this->toolcontext = (!empty($toolcontext)) ? $toolcontext : self::CTX_ASSISTANT;
93 }
94
105 private function isSystemTool($toolInstance)
106 {
107 return (method_exists($toolInstance, 'isSystem') && $toolInstance->isSystem());
108 }
109
124 private function getAllowedToolsList()
125 {
126 if ($this->toolcontext === self::CTX_MCP_SERVER) {
127 $constName = 'AI_MCP_SERVER_ALLOWED_TOOLS';
128 } else {
129 $constName = 'AI_ASSISTANT_ALLOWED_TOOLS';
130 }
131
132 $raw = getDolGlobalString($constName); // Return the list (separated by coma) of all enabled tools
133
134 if ($raw === '') {
135 // Constant not yet configured — allow everything
136 return array();
137 }
138
139 if ($raw === 'NONE') {
140 // Admin explicitly disabled all tools via the preset button
141 return array('__blocked__');
142 }
143
144 return array_values(array_filter(array_map('trim', explode(',', $raw))));
145 }
146
154 public static function resolveAllowList($raw, $allDiscoveredTools)
155 {
156 if ($raw === '') {
157 // Not yet configured → implicitly all tools are allowed
158 return $allDiscoveredTools;
159 }
160 if ($raw === 'NONE') {
161 // Admin explicitly disabled everything
162 return array();
163 }
164 // Explicit list stored by a previous save
165 return array_values(array_filter(array_map('trim', explode(',', $raw))));
166 }
167
168
178 public function loadTools()
179 {
180 $this->loadNativeTools(); // Tools found into directory ai/tools/
181 $this->loadExternalTools(); // Tools provided by external module and hook addMcpTools
182 }
183
194 private function loadNativeTools()
195 {
196 $toolsDir = DOL_DOCUMENT_ROOT . '/ai/tools/';
197 if (!is_dir($toolsDir)) {
198 dol_syslog('[McpHandler] MCP tools directory not found: ' . $toolsDir, LOG_INFO);
199 return;
200 }
201
202 $files = glob($toolsDir . '*.php');
203 foreach ($files as $file) {
204 try {
205 // Validate the file path before inclusion
206 $realFilePath = realpath($file);
207 if ($realFilePath === false || strpos($realFilePath, realpath($toolsDir)) !== 0) {
208 dol_syslog('[McpHandler] Attempted to load tool outside of allowed directory: ' . $file, LOG_WARNING);
209 continue;
210 }
211
212 require_once $realFilePath;
213
214 $basename = basename($file, '.class.php');
215 $className = 'Tool' . str_replace(' ', '', ucwords(str_replace('_', ' ', $basename)));
216
217 if (!class_exists($className)) {
218 dol_syslog("[McpHandler] Tool class '{$className}' not found in file '{$file}'.", LOG_WARNING);
219 continue;
220 }
221
222 $toolInstance = new $className($this->db, $this->user, $this->conf);
223
224 if ($toolInstance instanceof McpTool) {
225 // When the API bridge is on, it replaces the other native tools (they would
226 // duplicate what the API endpoints already offer). System tools are kept
227 // because parse_intent.php needs them to drive the conversation.
228 if (!in_array($basename, ['api_bridge', 'coffeemaker', 'conversation', 'email_cleaner', 'navigation', 'reports'])
229 && !$this->isSystemTool($toolInstance)) {
230 continue;
231 }
232 // Easter egg tool family is loaded only when its hidden option is set
233 if ($basename == 'coffeemaker' && !getDolGlobalInt('AI_COFFEE_EASTER_EGG')) {
234 continue;
235 }
236 // The predefined report tools are loaded only when their option is set
237 if ($basename == 'reports' && !getDolGlobalBool('AI_ENABLE_PREDEFINED_REPORTS')) {
238 continue;
239 }
240 $this->registerTool($basename, $toolInstance);
241 } else {
242 dol_syslog("[McpHandler] Tool class '{$className}' does not extend McpTool.", LOG_ERR);
243 }
244 } catch (\Throwable $e) {
245 dol_syslog("[McpHandler] Failed to load tool from file '{$file}': " . $e->getMessage(), LOG_ERR);
246 }
247 }
248 }
258 private function loadExternalTools()
259 {
260 global $hookmanager;
261 if (!is_object($hookmanager)) {
262 require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
263 $hookmanager = new HookManager($this->db);
264 }
265
266 $hookmanager->initHooks(['aimcp']);
267
268 $parameters = ['db' => $this->db, 'user' => $this->user, 'conf' => $this->conf];
269 $action = '';
270
271 try {
272 $hookmanager->executeHooks('addMcpTools', $parameters, $this, $action);
273
274 if (!is_array($hookmanager->resArray)) {
275 return;
276 }
277
278 foreach ($hookmanager->resArray as $moduleTools) {
279 if ($moduleTools instanceof McpTool) {
280 // Tolerance: a module that set results = array($tool)
281 // instead of array(array($tool)) still works - the
282 // HookManager flattens results into resArray, so bare
283 // instances are the natural mistake to make.
284 $this->registerTool(get_class($moduleTools), $moduleTools);
285 continue;
286 }
287 if (!is_array($moduleTools)) {
288 continue;
289 }
290 foreach ($moduleTools as $toolInstance) {
291 if ($toolInstance instanceof McpTool) {
292 $this->registerTool(get_class($toolInstance), $toolInstance);
293 } else {
294 dol_syslog('[McpHandler] A module provided a tool that is not an instance of McpTool.', LOG_WARNING);
295 }
296 }
297 }
298 } catch (\Throwable $e) {
299 dol_syslog('[McpHandler] Error during \'addMcpTools\' hook execution: ' . $e->getMessage(), LOG_ERR);
300 }
301 }
302
311 private function registerTool(string $key, McpTool $toolInstance)
312 {
313 $this->loadedTools[$key] = $toolInstance;
314
315 // Populate the lookup map
316 foreach ($toolInstance->getDefinitions() as $def) {
317 if (isset($def['name'])) {
318 if (isset($this->toolsByName[$def['name']])) {
320 "[McpHandler] Tool name conflict: '{$def['name']}' is already registered by '" . get_class($this->toolsByName[$def['name']]) . "'. Skipping registration from '" . get_class($toolInstance) . "'.",
321 LOG_WARNING
322 );
323 } else {
324 $this->toolsByName[$def['name']] = $toolInstance;
325 }
326 }
327 }
328 dol_syslog('[McpHandler] Successfully registered MCP tool: ' . get_class($toolInstance), LOG_INFO);
329 }
330
339 public function getToolsSchemaUnfiltered()
340 {
341 $schema = array();
342
343 foreach ($this->loadedTools as $tool) {
344 $isSystem = $this->isSystemTool($tool);
345 $className = get_class($tool);
346
347 foreach ($tool->getDefinitions() as $def) {
348 $def['is_system'] = $isSystem;
349 $def['class_name'] = $className;
350 if (empty($def['categories'])) {
351 $def['categories'] = $tool->getCategories(); // class-level fallback; a tool may set finer per-definition categories
352 }
353 if (!empty($def['inputSchema']) && is_array($def['inputSchema'])) {
354 $def['inputSchema'] = self::normalizeInputSchema($def['inputSchema']);
355 }
356 $schema[] = $def;
357 }
358 }
359
360 return $schema;
361 }
362
375 public function getToolsSchema(): array
376 {
377 $allowed = $this->getAllowedToolsList(); // Return list of "allowed" tools for the current context $this->toolcontext (Chat or MCP)
378 $schema = [];
379
380 foreach ($this->loadedTools as $tool) {
381 $isSystem = $this->isSystemTool($tool);
382
383 foreach ($tool->getDefinitions() as $def) {
384 $name = isset($def['name']) ? $def['name'] : '';
385
386 if (!empty($def['inputSchema']) && is_array($def['inputSchema'])) {
387 $def['inputSchema'] = self::normalizeInputSchema($def['inputSchema']);
388 }
389
390 if ($isSystem) {
391 // Always include system tools but tag them so parse_intent.php
392 // can strip them from $toolsForLLM while keeping them available
393 // for the validation check (executeTool must still be able to
394 // run respond_to_user, ask_for_clarification, etc.).
395 $def['is_system'] = true;
396 if (empty($def['categories'])) {
397 $def['categories'] = $tool->getCategories(); // class-level fallback; a tool may set finer per-definition categories
398 }
399 $schema[] = $def;
400 continue;
401 }
402
403 $def['is_system'] = false;
404
405 // Same rule as getToolsSchemaForLLM(): this is what tools/list on the
406 // MCP server returns, so a caller must not be offered what it cannot run.
407 if ($this->checkToolRights($tool, $name) !== '') {
408 continue;
409 }
410
411 if (empty($allowed)) {
412 // No restriction configured — include everything
413 if (empty($def['categories'])) {
414 $def['categories'] = $tool->getCategories(); // class-level fallback; a tool may set finer per-definition categories
415 }
416 $schema[] = $def;
417 continue;
418 }
419
420 if (in_array($name, $allowed, true)) {
421 if (empty($def['categories'])) {
422 $def['categories'] = $tool->getCategories(); // class-level fallback; a tool may set finer per-definition categories
423 }
424 $schema[] = $def;
425 }
426 // Not in $allowed — silently omitted; LLM never sees this tool
427 }
428 }
429
430 return $schema;
431 }
432
448 public function getToolsSchemaForLLM()
449 {
450 $allowed = $this->getAllowedToolsList();
451 $schema = array();
452
453 foreach ($this->loadedTools as $tool) {
454 // Check isSystem() class method first (requires conversation.class.php
455 // to implement it). This is the preferred path for future extensibility.
456 if ($this->isSystemTool($tool)) {
457 continue;
458 }
459
460 foreach ($tool->getDefinitions() as $def) {
461 $name = isset($def['name']) ? $def['name'] : '';
462
463 if (!empty($def['inputSchema']) && is_array($def['inputSchema'])) {
464 $def['inputSchema'] = self::normalizeInputSchema($def['inputSchema']);
465 }
466
467 // Check is_system flag in the definition array itself.
468 // This is set directly in conversation.class.php getDefinitions()
469 // and works even if the isSystem() class method is not yet deployed.
470 if (!empty($def['is_system'])) {
471 continue;
472 }
473
474 // Do not advertise what this user cannot run.
475 if ($this->checkToolRights($tool, $name) !== '') {
476 continue;
477 }
478
479 if (empty($allowed)) {
480 // No restriction configured — include everything
481 if (empty($def['categories'])) {
482 $def['categories'] = $tool->getCategories(); // class-level fallback; a tool may set finer per-definition categories
483 }
484 $schema[] = $def;
485 continue;
486 }
487
488 if (in_array($name, $allowed, true)) {
489 if (empty($def['categories'])) {
490 $def['categories'] = $tool->getCategories(); // class-level fallback; a tool may set finer per-definition categories
491 }
492 $schema[] = $def;
493 }
494 }
495 }
496
497 return $schema;
498 }
499
509 public static function normalizeInputSchema(array $schema): array
510 {
511 return McpTool::normalizeInputSchema($schema);
512 }
513
521 private function checkToolRights($tool, $toolName)
522 {
523 if ($this->isSystemTool($tool)) {
524 return '';
525 }
526
527 $declared = method_exists($tool, 'getRequiredRights') ? $tool->getRequiredRights($toolName) : McpTool::RIGHTS_UNDECLARED;
528
529 if ($declared === McpTool::RIGHTS_ENFORCED_DOWNSTREAM) {
530 return ''; // REST API classes check DolibarrApiAccess::$user themselves
531 }
532 if ($declared === McpTool::RIGHTS_UNDECLARED) {
533 dol_syslog("[McpHandler] Tool '".$toolName."' declares no rights: denied.", LOG_WARNING);
534
535 return 'undeclared';
536 }
537 foreach ((array) $declared as $right) {
538 $right = (array) $right;
539 $module = isset($right[0]) ? $right[0] : '';
540 $perm = isset($right[1]) ? $right[1] : '';
541 $subperm = isset($right[2]) ? $right[2] : '';
542 if ($module === '' || !$this->user->hasRight($module, $perm, $subperm)) {
543 return $module.'/'.$perm.($subperm !== '' ? '/'.$subperm : '');
544 }
545 }
546
547 return '';
548 }
561 private function checkWriteConfirmation($tool, $toolName, array $args)
562 {
563 if (!method_exists($tool, 'writeConfirmationPreview')) {
564 return null;
565 }
566 $preview = (string) $tool->writeConfirmationPreview($toolName, $args);
567 if ($preview === McpTool::NO_WRITE) {
568 return null; // read tool
569 }
570
571 // A write bound to fail is refused before the user is asked to approve it.
572 if (method_exists($tool, 'writePrecheck')) {
573 $refused = (string) $tool->writePrecheck($toolName, $args);
574 if ($refused !== '') {
575 return array('error' => $refused);
576 }
577 }
578
579 require_once DOL_DOCUMENT_ROOT.'/ai/class/writeconfirmation.class.php';
580 $gate = new AiWriteConfirmation($this->db);
581
582 $state = isset($args['requestState']) ? (string) $args['requestState'] : '';
583 if ($state !== '') {
584 if ($gate->consume($this->user, $toolName, $args, $state)) {
585 return null; // confirmed: the write runs
586 }
587
588 return array('error' => $gate->error);
589 }
590
591 $issued = $gate->issue($this->user, $toolName, $args, $preview);
592 if ($issued === '') {
593 return array('error' => $gate->error);
594 }
595
596 return array(
597 'resultType' => 'input_required',
598 'inputRequests' => array(
599 array(
600 'type' => 'confirmation',
601 // The chat shows the sentence as HTML, an MCP client as text:
602 // no "&rarr;" or "&euro;" there, and accented names as written.
603 'prompt' => ($this->toolcontext === self::CTX_MCP_SERVER) ? dol_html_entity_decode($preview, ENT_QUOTES | ENT_HTML5) : $preview
604 )
605 ),
606 'requestState' => $issued
607 );
608 }
609
621 public function executeTool(string $toolName, array $args): array
622 {
623 if (!isset($this->toolsByName[$toolName])) {
624 // LLMs routinely emit near-miss tool names (create_invoice for
625 // create_customer_invoice). Recover when the real name is
626 // UNAMBIGUOUS: same action verb (segment before the first '_')
627 // and every underscore token of the requested name appears in the
628 // candidate. Exactly one match executes (logged); zero or several
629 // keep the clean error - never guess between candidates.
630 $reqTokens = explode('_', dol_strtolower($toolName));
631 $verb = $reqTokens[0];
632 $candidates = array();
633 foreach (array_keys($this->toolsByName) as $realName) {
634 if (strpos($realName, $verb.'_') !== 0 || $this->isSystemTool($this->toolsByName[$realName])) {
635 continue;
636 }
637 $realTokens = explode('_', $realName);
638 if (!array_diff($reqTokens, $realTokens)) {
639 $candidates[] = $realName;
640 }
641 }
642 if (count($candidates) === 1) {
643 dol_syslog("[McpHandler] Tool name '".$toolName."' recovered to '".$candidates[0]."'.", LOG_INFO);
644 $toolName = $candidates[0];
645 } else {
646 return ["error" => "Tool '{$toolName}' not found."];
647 }
648 }
649
650 $toolInstance = $this->toolsByName[$toolName];
651
652 // enforce tool context allow-list (system tools always pass through)
653 if (!$this->isSystemTool($toolInstance)) {
654 $allowed = $this->getAllowedToolsList();
655
656 if (!empty($allowed) && !in_array($toolName, $allowed, true)) {
658 "[McpHandler] Blocked execution of tool '$toolName' in tool context '{$this->toolcontext}' (not in allow-list).",
659 LOG_WARNING
660 );
661 return array('error' => "Tool '" . $toolName . "' is not available in this tool context.");
662 }
663 }
664
665 // execute
666 try {
667 dol_syslog('[McpHandler] Executing tool \'' . $toolName . '\' with args: ' . json_encode($args), LOG_INFO);
668 $missingRight = $this->checkToolRights($toolInstance, $toolName);
669 if ($missingRight !== '') {
670 return array('error' => ($missingRight === 'undeclared')
671 ? "Tool '".$toolName."' cannot run: it declares no required rights."
672 : "Permission denied: '".$toolName."' requires the right ".$missingRight.".");
673 }
674
675 // Writes do not execute on the first call: the caller gets a preview and
676 // a confirmation state, and comes back with it. Reads are unaffected.
677 $pending = $this->checkWriteConfirmation($toolInstance, $toolName, $args);
678 if ($pending !== null) {
679 return $pending;
680 }
681
682 $result = $toolInstance->execute($toolName, $args);
683 dol_syslog('[McpHandler] Tool \'' . $toolName . '\' executed successfully.', LOG_INFO);
684 return $result;
685 } catch (\Throwable $e) {
686 dol_syslog('[McpHandler] Error executing tool \'' . $toolName . '\': ' . $e->getMessage(), LOG_ERR);
687 return ["error" => "An internal error occurred while executing the tool '{$toolName}'. Details have been logged."];
688 }
689 }
690}
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class AiWriteConfirmation.
Class to manage hooks.
Class to handle MCP (Model Context Protocol).
Definition mcp.class.php:40
checkToolRights($tool, $toolName)
Check the rights a tool declared for the acting user.
__construct($db, $user, $conf_obj=null, $toolcontext='')
Constructor.
Definition mcp.class.php:81
isSystemTool($toolInstance)
Returns true if the given tool instance declares itself as a system tool.
checkWriteConfirmation($tool, $toolName, array $args)
Stop a write until it is confirmed, on the MCP multi-round-trip pattern.
getToolsSchemaForLLM()
Returns the schema of tools permitted in the current context, with system tools completely excluded.
getToolsSchemaUnfiltered()
Returns the full schema of every loaded tool with no allow-list filtering.
loadExternalTools()
Loads external tools registered via the 'addMcpTools' hook.
registerTool(string $key, McpTool $toolInstance)
Helper method to register a tool instance and populate lookup arrays.
getAllowedToolsList()
Returns the configured allow-list for the current context as an array of tool names.
loadTools()
Load all available MCP tools.
loadNativeTools()
Load native tools from the specific tools directory.
static normalizeInputSchema(array $schema)
Normalize a tool input schema to ensure broad compatibility with LLM function-calling APIs (e....
getToolsSchema()
Returns the schema of all tools permitted in the current context.
static resolveAllowList($raw, $allDiscoveredTools)
Resolves a raw allow-list constant value into an explicit PHP array of tool names.
executeTool(string $toolName, array $args)
Execute a specific tool by its name.
Abstract base class for all MCP (Model Context Protocol) tools.
getDefinitions()
Return the list of tools provided by this class.
const RIGHTS_UNDECLARED
Default of getRequiredRights(): the class never declared anything, deny.
static normalizeInputSchema(array $schema)
Normalize a tool input schema to ensure broad compatibility with LLM function-calling APIs (e....
const NO_WRITE
Returned by writeConfirmationPreview() when the tool writes nothing.
if(! $sortfield) if(! $sortorder) $module
Definition list.php:193
dol_html_entity_decode($a, $b, $c='UTF-8', $keepsomeentities=0)
Replace html_entity_decode functions to manage errors.
dol_strtolower($string, $encoding="UTF-8")
Convert a string to lower.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
conf($dolibarr_main_document_root, $realpathconf=null)
Load conf file (file must exists)
Definition inc.php:431
$conf db user
Active Directory does not allow anonymous connections.
Definition repair.php:166