| 1 |
<?php |
| 2 |
/** |
| 3 |
* ErrorLogMcpObservabilityHandler — Audit logging and observability sink for MCP tool calls. |
| 4 |
* |
| 5 |
* @package WPFunnels\MCP\Observability |
| 6 |
* @since 3.13.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
namespace WPFunnels\MCP\Observability; |
| 10 |
|
| 11 |
defined( 'ABSPATH' ) || exit; |
| 12 |
|
| 13 |
/** |
| 14 |
* Class ErrorLogMcpObservabilityHandler |
| 15 |
*/ |
| 16 |
class ErrorLogMcpObservabilityHandler { |
| 17 |
|
| 18 |
/** |
| 19 |
* Log an MCP tool execution event. |
| 20 |
* |
| 21 |
* @param string $tool Name of executed tool. |
| 22 |
* @param array $input Arguments passed to tool. |
| 23 |
* @param mixed $result Tool execution result or error. |
| 24 |
* @param float $execution_ms Execution time in milliseconds. |
| 25 |
* @return void |
| 26 |
*/ |
| 27 |
public static function logToolCall( $tool, $input, $result, $execution_ms = 0.0 ) { |
| 28 |
$user_id = function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0; |
| 29 |
$is_error = is_wp_error( $result ); |
| 30 |
$destructive = ! empty( $input['confirm'] ); |
| 31 |
|
| 32 |
$log_entry = [ |
| 33 |
'timestamp' => current_time( 'mysql' ), |
| 34 |
'tool' => $tool, |
| 35 |
'user_id' => $user_id, |
| 36 |
'destructive' => $destructive, |
| 37 |
'success' => ! $is_error, |
| 38 |
'execution_ms' => round( $execution_ms, 2 ), |
| 39 |
'error' => $is_error ? $result->get_error_message() : null, |
| 40 |
]; |
| 41 |
|
| 42 |
/** |
| 43 |
* Filter or intercept MCP audit log entries. |
| 44 |
* |
| 45 |
* @param array $log_entry Structured log payload. |
| 46 |
*/ |
| 47 |
do_action( 'wpfunnels/mcp_audit_log', $log_entry ); |
| 48 |
|
| 49 |
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { |
| 50 |
error_log( |
| 51 |
sprintf( |
| 52 |
'[WPFunnels MCP] %s | User: %d | Tool: %s | Time: %.2fms | Status: %s', |
| 53 |
$log_entry['timestamp'], |
| 54 |
$user_id, |
| 55 |
$tool, |
| 56 |
$log_entry['execution_ms'], |
| 57 |
$is_error ? 'ERROR (' . $log_entry['error'] . ')' : 'SUCCESS' |
| 58 |
) |
| 59 |
); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|