| 1 |
<?php |
| 2 |
/** |
| 3 |
* Bridge between NotificationX abilities and MCP tools. |
| 4 |
* |
| 5 |
* The tool surface *is* the ability registry — it cannot drift. This class |
| 6 |
* turns registered abilities into `tools/list` entries and routes `tools/call` |
| 7 |
* to the matching ability, enforcing read-only scope before any write runs. |
| 8 |
* |
| 9 |
* @package NotificationX\MCP |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace NotificationX\MCP; |
| 13 |
|
| 14 |
use NotificationX\GetInstance; |
| 15 |
use NotificationX\Abilities\Registrar; |
| 16 |
|
| 17 |
if ( ! defined( 'ABSPATH' ) ) { |
| 18 |
exit; |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* @method static Tools get_instance( $args = null ) |
| 23 |
*/ |
| 24 |
class Tools { |
| 25 |
|
| 26 |
use GetInstance; |
| 27 |
|
| 28 |
/** |
| 29 |
* When true, only read abilities may be invoked (set from the credential's |
| 30 |
* scope by the server before dispatch). |
| 31 |
* |
| 32 |
* @var bool |
| 33 |
*/ |
| 34 |
protected $read_only = false; |
| 35 |
|
| 36 |
/** |
| 37 |
* Set the read-only override for the current request. |
| 38 |
* |
| 39 |
* @param bool $read_only Whether the credential is read-only. |
| 40 |
* @return void |
| 41 |
*/ |
| 42 |
public function set_read_only( $read_only ) { |
| 43 |
$this->read_only = (bool) $read_only; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Build the tools/list payload. |
| 48 |
* |
| 49 |
* @return array |
| 50 |
*/ |
| 51 |
public function list_tools() { |
| 52 |
$tools = array(); |
| 53 |
foreach ( Registrar::get_instance()->get_all() as $ability ) { |
| 54 |
$tools[] = $ability->to_tool(); |
| 55 |
} |
| 56 |
return $tools; |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Invoke a tool by its MCP name. |
| 61 |
* |
| 62 |
* @param string $name Tool name (no category prefix). |
| 63 |
* @param array $args Tool arguments. |
| 64 |
* @return array|\WP_Error Ability result or error. |
| 65 |
*/ |
| 66 |
public function invoke( $name, $args = array() ) { |
| 67 |
$ability = Registrar::get_instance()->get_by_tool_name( $name ); |
| 68 |
|
| 69 |
if ( ! $ability ) { |
| 70 |
return new \WP_Error( |
| 71 |
'nx_mcp_unknown_tool', |
| 72 |
/* translators: %s: tool name. */ |
| 73 |
sprintf( __( 'Unknown tool: %s', 'notificationx' ), $name ), |
| 74 |
array( 'status' => 404 ) |
| 75 |
); |
| 76 |
} |
| 77 |
|
| 78 |
if ( $this->read_only && $ability->is_write() ) { |
| 79 |
return new \WP_Error( |
| 80 |
'nx_mcp_read_only', |
| 81 |
__( 'This connection is read-only and cannot run write tools.', 'notificationx' ), |
| 82 |
array( 'status' => 403 ) |
| 83 |
); |
| 84 |
} |
| 85 |
|
| 86 |
return $ability->run( is_array( $args ) ? $args : array() ); |
| 87 |
} |
| 88 |
} |
| 89 |
|