Repository navigation
Expand file tree
/
Copy pathmcp.php
More file actions
376 lines (336 loc) · 13 KB
/
Copy pathmcp.php
File metadata and controls
376 lines (336 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
<?php
/* Copyright (C) 2026 E-dem
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file mcp.php
* \ingroup dalfred
* \brief MCP Streamable HTTP endpoint (per-request, PHP-FPM friendly).
*
* One HTTP request = one JSON-RPC MCP message, handled by the official
* MCP PHP SDK (no daemon, no event loop). Sessions are persisted on disk
* between requests (Mcp-Session-Id header).
*
* Authentication: the caller provides a Dolibarr user API key via
* - "Authorization: Bearer <key>" (standard for MCP clients), or
* - "DOLAPIKEY: <key>" header (Dolibarr REST API convention), or
* - "?DOLAPIKEY=<key>" query param (fallback for clients without headers).
* The key is validated against llx_user, then forwarded to the MCP tools
* which act through the Dolibarr REST API with that user's permissions.
*
* This endpoint is OFF by default: it requires both the Dalfred module to
* be enabled AND the DALFRED_MCP_EXTERNAL_ENABLED admin toggle to be set.
*/
// Same execution context as the native REST API (htdocs/api/index.php)
if (!defined('NOLOGIN')) {
define('NOLOGIN', '1');
}
if (!defined('NOCSRFCHECK')) {
define('NOCSRFCHECK', '1');
}
if (!defined('NOTOKENRENEWAL')) {
define('NOTOKENRENEWAL', '1');
}
if (!defined('NOREQUIREMENU')) {
define('NOREQUIREMENU', '1');
}
if (!defined('NOREQUIREHTML')) {
define('NOREQUIREHTML', '1');
}
if (!defined('NOREQUIREAJAX')) {
define('NOREQUIREAJAX', '1');
}
if (!defined('NOREQUIRESOC')) {
define('NOREQUIRESOC', '1');
}
if (!defined('NOREQUIRETRAN')) {
define('NOREQUIRETRAN', '1');
}
if (!defined('NOSESSION')) {
define('NOSESSION', '1');
}
$res = 0;
if (!$res && file_exists("../main.inc.php")) {
$res = @include "../main.inc.php";
}
if (!$res && file_exists("../../main.inc.php")) {
$res = @include "../../main.inc.php";
}
if (!$res && file_exists("../../../main.inc.php")) {
$res = @include "../../../main.inc.php";
}
if (!$res) {
http_response_code(500);
die('{"error":"Main include failed"}');
}
/**
* Emit a JSON-RPC style error and exit.
*
* On 401, a WWW-Authenticate header advertises the Protected Resource
* Metadata URL so OAuth-capable MCP clients (claude.ai connectors…) can
* run the discovery + authorization flow (RFC 9728 §5.1).
*
* @param int $httpCode HTTP status code
* @param int $rpcCode JSON-RPC error code
* @param string $message Error message
* @return never
*/
function dalfred_error($httpCode, $rpcCode, $message)
{
if ($httpCode == 401) {
dol_include_once('/dalfred/lib/dalfred_mcp_bootstrap.php');
dalfred_mcp_oauth_autoload();
$prm = \DolibarrMcpOAuth\Support\UrlHelper::publicUrl('/dalfred/oauth.php').'/.well-known/oauth-protected-resource';
$endpoint = new \DolibarrMcpOAuth\HttpEndpoint($GLOBALS['db'], new \DolibarrMcpOAuth\ExposureConfig('dalfred', 'dcp_', 'DALFRED'));
header('WWW-Authenticate: '.$endpoint->wwwAuthenticateHeader($prm));
}
http_response_code($httpCode);
header('Content-Type: application/json');
print json_encode(array(
'jsonrpc' => '2.0',
'id' => null,
'error' => array('code' => $rpcCode, 'message' => $message),
));
exit;
}
if (!isModEnabled('dalfred')) {
dalfred_error(403, -32000, 'Module Dalfred not enabled');
}
if (getDolGlobalInt('DALFRED_MCP_EXTERNAL_ENABLED') !== 1) {
dalfred_error(403, -32000, 'External MCP access is disabled for this Dalfred instance');
}
// --- Authentication -------------------------------------------------------
dol_include_once('/dalfred/lib/dalfred_mcp_bootstrap.php');
if (dalfred_mcp_oauth_autoload() === null) {
dalfred_error(500, -32002, 'dolibarr-mcp-oauth library not found');
}
// Self-test, before any authentication: the admin page sends a request
// carrying both "Authorization: Bearer <dummy>" and "X-Dolibarr-Probe: 1",
// and asks one thing — did the Authorization header reach PHP? It only tells
// the caller whether their own header survived, nothing else.
if (!empty($_SERVER['HTTP_X_DOLIBARR_PROBE'])) {
header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode(array('probe' => 'authorization', 'authorization_seen' => \DolibarrMcpOAuth\HttpEndpoint::seesAuthorizationHeader($_SERVER)));
exit;
}
$mcpEndpoint = new \DolibarrMcpOAuth\HttpEndpoint($db, new \DolibarrMcpOAuth\ExposureConfig('dalfred', 'dcp_', 'DALFRED'));
$getPost = fn(string $name, $default) => GETPOST($name, 'alphanohtml') ?: $default;
$auth = $mcpEndpoint->resolveApiKey($_SERVER, $getPost);
if ($auth->apiKey === null) {
dalfred_error($auth->httpCode, -32001, $auth->error);
}
$apiKey = $auth->apiKey;
// --- Load the Dolibarr MCP server package ----------------------------------
$autoload = \DolibarrMcpOAuth\Support\PackageLocator::findAutoloader(array(
dol_buildpath('/dalfred/dolibarr-mcp-server/vendor/autoload.php', 0),
));
if (!$autoload) {
dalfred_error(500, -32002, 'Dolibarr MCP server package not found');
}
// Shared-library collisions: refuse with the culprit's name instead of dying
// on a fatal error. See lib/dalfred_runtime.php.
dol_include_once('/dalfred/lib/dalfred_runtime.php');
$runtimeDir = dalfred_runtime_package_dir($autoload);
$conflicts = dalfred_runtime_conflicts($runtimeDir, false);
dalfred_runtime_arm_fatal_handler();
if (empty($conflicts)) {
require_once $autoload;
$conflicts = dalfred_runtime_conflicts($runtimeDir, true);
}
if (!empty($conflicts)) {
$conflictMessage = dalfred_runtime_conflict_message($conflicts[0]);
dol_syslog('[DALFRED] '.$conflictMessage, LOG_ERR);
dalfred_runtime_record_error($conflictMessage, $conflicts[0]['file']);
dalfred_runtime_disarm();
dalfred_error(500, -32002, $conflictMessage);
}
/**
* Build the read-only SQL capability, or null when the caller may not use it.
*
* Returning null is not a soft failure: the MCP runtime then excludes the SQL
* tools from attribute discovery entirely, so they never appear in tools/list.
* Deny-by-default is structural rather than a runtime check to remember.
*
* Must be called only after the dolibarr-mcp-server autoloader is required —
* DolibarrMcpSql\SqlCapability implements one of that package's interfaces.
*
* @param DoliDB $db Database handler
* @param Conf $conf Dolibarr configuration
* @param string $apiKey Caller's validated API key
* @return \DolibarrMcpSql\SqlCapability|null
*/
function dalfredBuildSqlCapability($db, $conf, $apiKey)
{
dol_include_once('/dalfred/lib/dalfred_mcp_bootstrap.php');
if (dalfred_mcp_sql_autoload() === null) {
dol_syslog('[DALFRED] dolibarr-mcp-sql library not found; SQL tools stay hidden', LOG_WARNING);
return null;
}
$config = dalfred_sql_config();
$permissions = new \DolibarrMcpSql\SqlPermissions($db, $conf, $config);
// Cheapest gate first: skip loading a User object on the overwhelmingly
// common path where the feature is simply off.
if (!$permissions->isGloballyEnabled()) {
return null;
}
$userId = dalfredResolveUserIdFromApiKey($db, $apiKey);
if ($userId <= 0) {
return null;
}
$mcpUser = new User($db);
if ($mcpUser->fetch($userId) <= 0) {
return null;
}
$mcpUser->getrights();
$denial = $permissions->denialCode($mcpUser);
if ($denial !== null) {
dol_syslog('[DALFRED] SQL access refused for user '.((int) $userId).': '.$denial, LOG_INFO);
return null;
}
return new \DolibarrMcpSql\SqlCapability($db, $conf, $mcpUser, $config, 'mcp');
}
/**
* Resolve the Dolibarr user behind an API key.
*
* Keys are stored either in clear or encrypted depending on the instance, so
* both forms are matched. More than one hit is treated as no hit: an ambiguous
* key must not pick a user.
*
* @param DoliDB $db Database handler
* @param string $apiKey Caller's API key
* @return int User id, or 0 when it resolves to nothing usable
*/
function dalfredResolveUserIdFromApiKey($db, $apiKey)
{
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user";
$sql .= " WHERE api_key = '".$db->escape($apiKey)."'";
$sql .= " OR api_key = '".$db->escape(dolEncrypt($apiKey, '', '', 'dolibarr'))."'";
$resql = $db->query($sql);
if (!$resql || $db->num_rows($resql) !== 1) {
return 0;
}
$obj = $db->fetch_object($resql);
return $obj ? (int) $obj->rowid : 0;
}
// --- Handle the MCP request ------------------------------------------------
// The MCP tools act through the local Dolibarr REST API with the caller's key.
// The config is request-scoped (no putenv: FPM workers are reused across
// requests and users, process-global state must not carry credentials).
$config = new DolibarrMcp\Config\ConnectionConfig(DOL_MAIN_URL_ROOT, $apiKey);
// Persist MCP sessions between PHP-FPM requests
$sessionDir = DOL_DATA_ROOT.'/dalfred/mcp_sessions';
// --- Audit, rate limit and alerting ------------------------------------------
//
// The body is read here rather than left to the SDK because we need to know
// what is being asked BEFORE dispatching: a rate limit applied afterwards caps
// nothing. It is then handed to the transport explicitly, since php://input
// cannot be read twice.
$rawBody = file_get_contents('php://input');
$rawBody = $rawBody === false ? '' : $rawBody;
$audit = null;
$call = array('method' => 'unknown', 'tool' => null, 'arguments' => null, 'client' => null);
if (dalfred_mcp_audit_autoload() !== null) {
$audit = new \DolibarrMcpAudit\McpAudit($db, dalfred_mcp_audit_config());
$call = \DolibarrMcpAudit\McpAudit::describeRequest($rawBody);
}
// The user the agent acts as. Resolved once: the audit trail names a person,
// not a key, and the limit counts per person.
$mcpUserId = dalfredResolveUserIdFromApiKey($db, $apiKey);
$mcpLogin = '';
if ($mcpUserId > 0) {
$tmpUser = new User($db);
if ($tmpUser->fetch($mcpUserId) > 0) {
$mcpLogin = (string) $tmpUser->login;
}
}
// Only tool calls are capped. Refusing initialize or tools/list would break the
// client outright while stopping no data from leaving.
if ($audit !== null && $mcpUserId > 0 && $call['method'] === 'tools/call') {
$decision = $audit->check($mcpUserId);
if (!$decision->allowed) {
$audit->record(
$mcpUserId,
$mcpLogin,
$call['method'],
$call['tool'],
$call['arguments'],
0,
false,
'rate limit reached',
$call['client']
);
dol_syslog('[DALFRED] MCP rate limit reached for user '.$mcpLogin, LOG_WARNING);
dalfred_error(429, -32000, $decision->message());
}
}
$startedAt = microtime(true);
try {
// A null capability keeps the SQL tools out of discovery entirely.
$sqlCapability = dalfredBuildSqlCapability($db, $conf, $apiKey);
// Lets the agent ask what it is connected to instead of guessing — Dolibarr
// version, enabled modules, and whether SQL is available in this session.
dol_include_once('/dalfred/lib/dalfred.lib.php');
$environment = dalfred_mcp_environment($sqlCapability !== null);
// The runtime's dependencies are prefixed in the released package and not
// in a development checkout: name them through the helper.
$serverRequestClass = dalfred_runtime_class($runtimeDir, 'GuzzleHttp\Psr7\ServerRequest');
$utilsClass = dalfred_runtime_class($runtimeDir, 'GuzzleHttp\Psr7\Utils');
$request = $serverRequestClass::fromGlobals()
->withBody($utilsClass::streamFor($rawBody));
$response = DolibarrMcp\Bootstrap::handleHttpRequest($request, $sessionDir, $config, $sqlCapability, $environment);
if ($audit !== null && $mcpUserId > 0) {
// A failed tool answers 200 with the error inside the payload, so the
// body has to be read to tell a real success from a refusal. Rewound
// afterwards: emit() streams the same body to the client.
$payload = (string) $response->getBody();
$response->getBody()->rewind();
$failure = $response->getStatusCode() >= 400
? 'HTTP '.$response->getStatusCode()
: \DolibarrMcpAudit\McpAudit::failureReason($payload);
$audit->record(
$mcpUserId,
$mcpLogin,
$call['method'],
$call['tool'],
$call['arguments'],
(int) round((microtime(true) - $startedAt) * 1000),
$failure === null,
$failure,
$call['client']
);
}
dalfred_runtime_disarm();
DolibarrMcp\Bootstrap::emit($response);
} catch (Throwable $e) {
dalfred_runtime_disarm();
dalfred_runtime_record_error(get_class($e).': '.$e->getMessage(), $e->getFile(), $e->getLine());
if ($audit !== null && $mcpUserId > 0) {
$audit->record(
$mcpUserId,
$mcpLogin,
$call['method'],
$call['tool'],
$call['arguments'],
(int) round((microtime(true) - $startedAt) * 1000),
false,
substr($e->getMessage(), 0, 255),
$call['client']
);
}
dol_syslog('[DALFRED] ERROR '.$e->getMessage(), LOG_ERR);
dalfred_error(500, -32603, 'Internal MCP server error: '.$e->getMessage());
}
$db->close();