dolibarr/htdocs/ai/server
Pichinov-Jose 1aeec05d80
Fix: MCP server propagates authenticated service user to tools (#38294)
The MCP server (htdocs/ai/server/mcp_server.php) loads a service user
from AI_MCP_USER_ID but does not expose it as the PHP global $user.
Several tool classes call 'global $user' to identify the caller --
they therefore see no authenticated user in HTTP MCP context (no PHP
web session exists) and return 'User not authenticated' even though
authentication via X-API-Key/Bearer has already succeeded.

This breaks roughly 40% of the MCP tools shipped by the module when
called from external clients (Claude Desktop Custom Connectors,
Claude Code CLI, MCP Inspector, custom scripts).

Two complementary fixes applied:

1. mcp_server.php: after successfully loading the service user,
   assign it to $GLOBALS['user'] and the local $user variable. This
   acts as a safety net for any tool (current or third-party) that
   relies on the legacy 'global $user' pattern.

2. Three tool classes harmonize their constructor signatures with
   the McpHandler contract -- new $className($db, $user, $conf):
   - ToolCrudObjects (htdocs/ai/tools/crud_objects.class.php)
   - ToolInvoices (htdocs/ai/tools/invoices.class.php)
   - ToolReports (htdocs/ai/tools/reports.class.php)

   These now accept $user via constructor (matching the pattern
   already used in ToolThirdParty, ToolCategories, ToolProducts)
   and store it as $this->user. Methods that previously called
   'global $user' (execute, validateInvoice, payInvoice) now use
   the injected $this->user, with a fallback to the global for
   web-session contexts.

Tested with:
- create_other_document (proposal, supplier_invoice): works
- search_invoice, validate_invoice, pay_invoice: works
- get_sales_report, get_purchase_report: works
- AI Assistant web UI: unchanged, no regression
2026-07-13 06:57:42 +02:00
..
mcp_server.php Fix: MCP server propagates authenticated service user to tools (#38294) 2026-07-13 06:57:42 +02:00