27require_once DOL_DOCUMENT_ROOT .
"/ai/class/mcptool.class.php";
41 const CTX_ASSISTANT =
'assistant';
43 const CTX_MCP_SERVER =
'mcp_server';
57 public $loadedTools = [];
63 public $toolsByName = [];
81 public function __construct($db, $user, $conf_obj =
null, $toolcontext =
'')
86 if ($conf_obj ===
null) {
90 $this->
conf = $conf_obj;
92 $this->toolcontext = (!empty($toolcontext)) ? $toolcontext : self::CTX_ASSISTANT;
107 return (method_exists($toolInstance,
'isSystem') && $toolInstance->isSystem());
126 if ($this->toolcontext === self::CTX_MCP_SERVER) {
127 $constName =
'AI_MCP_SERVER_ALLOWED_TOOLS';
129 $constName =
'AI_ASSISTANT_ALLOWED_TOOLS';
139 if ($raw ===
'NONE') {
141 return array(
'__blocked__');
144 return array_values(array_filter(array_map(
'trim', explode(
',', $raw))));
158 return $allDiscoveredTools;
160 if ($raw ===
'NONE') {
165 return array_values(array_filter(array_map(
'trim', explode(
',', $raw))));
196 $toolsDir = DOL_DOCUMENT_ROOT .
'/ai/tools/';
197 if (!is_dir($toolsDir)) {
198 dol_syslog(
'[McpHandler] MCP tools directory not found: ' . $toolsDir, LOG_INFO);
202 $files = glob($toolsDir .
'*.php');
203 foreach ($files as $file) {
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);
212 require_once $realFilePath;
214 $basename = basename($file,
'.class.php');
215 $className =
'Tool' . str_replace(
' ',
'', ucwords(str_replace(
'_',
' ', $basename)));
217 if (!class_exists($className)) {
218 dol_syslog(
"[McpHandler] Tool class '{$className}' not found in file '{$file}'.", LOG_WARNING);
222 $toolInstance =
new $className($this->db, $this->
user, $this->
conf);
224 if ($toolInstance instanceof
McpTool) {
228 if (!in_array($basename, [
'api_bridge',
'coffeemaker',
'conversation',
'email_cleaner',
'navigation',
'reports'])
233 if ($basename ==
'coffeemaker' && !
getDolGlobalInt(
'AI_COFFEE_EASTER_EGG')) {
237 if ($basename ==
'reports' && !
getDolGlobalBool(
'AI_ENABLE_PREDEFINED_REPORTS')) {
242 dol_syslog(
"[McpHandler] Tool class '{$className}' does not extend McpTool.", LOG_ERR);
244 }
catch (\Throwable $e) {
245 dol_syslog(
"[McpHandler] Failed to load tool from file '{$file}': " . $e->getMessage(), LOG_ERR);
261 if (!is_object($hookmanager)) {
262 require_once DOL_DOCUMENT_ROOT .
'/core/class/hookmanager.class.php';
266 $hookmanager->initHooks([
'aimcp']);
268 $parameters = [
'db' => $this->db,
'user' => $this->user,
'conf' => $this->conf];
272 $hookmanager->executeHooks(
'addMcpTools', $parameters, $this, $action);
274 if (!is_array($hookmanager->resArray)) {
278 foreach ($hookmanager->resArray as $moduleTools) {
279 if ($moduleTools instanceof
McpTool) {
284 $this->
registerTool(get_class($moduleTools), $moduleTools);
287 if (!is_array($moduleTools)) {
290 foreach ($moduleTools as $toolInstance) {
291 if ($toolInstance instanceof
McpTool) {
292 $this->
registerTool(get_class($toolInstance), $toolInstance);
294 dol_syslog(
'[McpHandler] A module provided a tool that is not an instance of McpTool.', LOG_WARNING);
298 }
catch (\Throwable $e) {
299 dol_syslog(
'[McpHandler] Error during \'addMcpTools\' hook execution: ' . $e->getMessage(), LOG_ERR);
313 $this->loadedTools[$key] = $toolInstance;
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) .
"'.",
324 $this->toolsByName[$def[
'name']] = $toolInstance;
328 dol_syslog(
'[McpHandler] Successfully registered MCP tool: ' . get_class($toolInstance), LOG_INFO);
343 foreach ($this->loadedTools as $tool) {
345 $className = get_class($tool);
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();
353 if (!empty($def[
'inputSchema']) && is_array($def[
'inputSchema'])) {
380 foreach ($this->loadedTools as $tool) {
383 foreach ($tool->getDefinitions() as $def) {
384 $name = isset($def[
'name']) ? $def[
'name'] :
'';
386 if (!empty($def[
'inputSchema']) && is_array($def[
'inputSchema'])) {
395 $def[
'is_system'] =
true;
396 if (empty($def[
'categories'])) {
397 $def[
'categories'] = $tool->getCategories();
403 $def[
'is_system'] =
false;
411 if (empty($allowed)) {
413 if (empty($def[
'categories'])) {
414 $def[
'categories'] = $tool->getCategories();
420 if (in_array($name, $allowed,
true)) {
421 if (empty($def[
'categories'])) {
422 $def[
'categories'] = $tool->getCategories();
453 foreach ($this->loadedTools as $tool) {
460 foreach ($tool->getDefinitions() as $def) {
461 $name = isset($def[
'name']) ? $def[
'name'] :
'';
463 if (!empty($def[
'inputSchema']) && is_array($def[
'inputSchema'])) {
470 if (!empty($def[
'is_system'])) {
479 if (empty($allowed)) {
481 if (empty($def[
'categories'])) {
482 $def[
'categories'] = $tool->getCategories();
488 if (in_array($name, $allowed,
true)) {
489 if (empty($def[
'categories'])) {
490 $def[
'categories'] = $tool->getCategories();
529 if ($declared === McpTool::RIGHTS_ENFORCED_DOWNSTREAM) {
533 dol_syslog(
"[McpHandler] Tool '".$toolName.
"' declares no rights: denied.", LOG_WARNING);
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] :
'';
543 return $module.
'/'.$perm.($subperm !==
'' ?
'/'.$subperm :
'');
563 if (!method_exists($tool,
'writeConfirmationPreview')) {
566 $preview = (string) $tool->writeConfirmationPreview($toolName, $args);
572 if (method_exists($tool,
'writePrecheck')) {
573 $refused = (string) $tool->writePrecheck($toolName, $args);
574 if ($refused !==
'') {
575 return array(
'error' => $refused);
579 require_once DOL_DOCUMENT_ROOT.
'/ai/class/writeconfirmation.class.php';
582 $state = isset($args[
'requestState']) ? (string) $args[
'requestState'] :
'';
584 if ($gate->consume($this->user, $toolName, $args, $state)) {
588 return array(
'error' => $gate->error);
591 $issued = $gate->issue($this->
user, $toolName, $args, $preview);
592 if ($issued ===
'') {
593 return array(
'error' => $gate->error);
597 'resultType' =>
'input_required',
598 'inputRequests' => array(
600 'type' =>
'confirmation',
603 'prompt' => ($this->toolcontext === self::CTX_MCP_SERVER) ?
dol_html_entity_decode($preview, ENT_QUOTES | ENT_HTML5) : $preview
606 'requestState' => $issued
623 if (!isset($this->toolsByName[$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])) {
637 $realTokens = explode(
'_', $realName);
638 if (!array_diff($reqTokens, $realTokens)) {
639 $candidates[] = $realName;
642 if (count($candidates) === 1) {
643 dol_syslog(
"[McpHandler] Tool name '".$toolName.
"' recovered to '".$candidates[0].
"'.", LOG_INFO);
644 $toolName = $candidates[0];
646 return [
"error" =>
"Tool '{$toolName}' not found."];
650 $toolInstance = $this->toolsByName[$toolName];
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).",
661 return array(
'error' =>
"Tool '" . $toolName .
"' is not available in this tool context.");
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.".");
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) {
682 $result = $toolInstance->execute($toolName, $args);
683 dol_syslog('[
McpHandler] Tool \
'' . $toolName .
'\' executed successfully.
', LOG_INFO);
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."];
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 handle MCP (Model Context Protocol).
checkToolRights($tool, $toolName)
Check the rights a tool declared for the acting user.
__construct($db, $user, $conf_obj=null, $toolcontext='')
Constructor.
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.
if(! $sortfield) if(! $sortorder) $module
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)
$conf db user
Active Directory does not allow anonymous connections.