Commit inicial powerservice
This commit is contained in:
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 2 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, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
{
|
||||
"name": "wordpress/mcp-adapter",
|
||||
"description": "Adapter for Abilities API, letting WordPress abilities to be used as MCP tools, resources or prompts",
|
||||
"license": "GPL-2.0-or-later",
|
||||
"type": "wordpress-plugin",
|
||||
"keywords": [
|
||||
"wordpress",
|
||||
"mcp",
|
||||
"api",
|
||||
"adapter",
|
||||
"integration",
|
||||
"model-context-protocol",
|
||||
"abilities-api",
|
||||
"ai"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "WordPress AI Team",
|
||||
"homepage": "https://make.wordpress.org/ai/"
|
||||
}
|
||||
],
|
||||
"homepage": "https://github.com/wordpress/mcp-adapter",
|
||||
"support": {
|
||||
"issues": "https://github.com/wordpress/mcp-adapter/issues",
|
||||
"source": "https://github.com/wordpress/mcp-adapter"
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"prefer-stable": true,
|
||||
"config": {
|
||||
"platform": {
|
||||
"php": "7.4"
|
||||
},
|
||||
"sort-packages": true,
|
||||
"optimize-autoloader": true,
|
||||
"preferred-install": "dist",
|
||||
"allow-plugins": {
|
||||
"automattic/jetpack-autoloader": true,
|
||||
"composer/installers": true,
|
||||
"dealerdirect/phpcodesniffer-composer-installer": true,
|
||||
"phpstan/extension-installer": true
|
||||
}
|
||||
},
|
||||
"repositories": [
|
||||
{
|
||||
"type": "composer",
|
||||
"url": "https://wpackagist.org",
|
||||
"only": [
|
||||
"wpackagist-plugin/*",
|
||||
"wpackagist-theme/*"
|
||||
]
|
||||
}
|
||||
],
|
||||
"extra": {
|
||||
"installer-paths": {
|
||||
"vendor/{$vendor}/{$name}/": [
|
||||
"wpackagist-plugin/plugin-check"
|
||||
]
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"WP\\MCP\\": "includes/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"WP\\MCP\\Tests\\": [
|
||||
"tests/"
|
||||
]
|
||||
}
|
||||
},
|
||||
"require": {
|
||||
"php": "^7.4 || ^8.0",
|
||||
"wordpress/php-mcp-schema": "^0.1.0",
|
||||
"ext-json": "*"
|
||||
},
|
||||
"require-dev": {
|
||||
"automattic/vipwpcs": "^3.0",
|
||||
"php-stubs/wordpress-stubs": "^6.9",
|
||||
"php-stubs/wp-cli-stubs": "^2.12",
|
||||
"phpcompatibility/php-compatibility": "10.x-dev as 9.99.99",
|
||||
"phpcompatibility/phpcompatibility-wp": "^2.1",
|
||||
"phpstan/extension-installer": "^1.3",
|
||||
"phpstan/php-8-stubs": "^0.4.24",
|
||||
"phpstan/phpstan": "^2.1.22",
|
||||
"phpstan/phpstan-deprecation-rules": "^2.0.3",
|
||||
"phpunit/phpunit": "^9.6",
|
||||
"slevomat/coding-standard": "^8.0",
|
||||
"szepeviktor/phpstan-wordpress": "^2.0",
|
||||
"wp-phpunit/wp-phpunit": "^6.5",
|
||||
"wpackagist-plugin/plugin-check": "^1.6",
|
||||
"yoast/phpunit-polyfills": "^4.0"
|
||||
},
|
||||
"scripts": {
|
||||
"lint:php": "phpcs",
|
||||
"lint:php:fix": "phpcbf",
|
||||
"lint:php:stan": "vendor/bin/phpstan analyse --memory-limit=1G",
|
||||
"test": "phpunit --strict-coverage"
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
/**
|
||||
* Ability for discovering available WordPress abilities.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Abilities;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Discover Abilities - Lists all available WordPress abilities in the system.
|
||||
*
|
||||
* This ability provides discovery functionality for the MCP protocol.
|
||||
* It discovers all registered WordPress abilities in the system.
|
||||
*
|
||||
* SECURITY CONSIDERATIONS:
|
||||
* - This ability exposes information about all registered abilities in the system
|
||||
* - Only abilities with mcp.public=true metadata will be returned
|
||||
* - Requires proper WordPress capability checks for secure operation
|
||||
*
|
||||
* @see https://developer.wordpress.org/apis/security/ for detailed security guidance
|
||||
*/
|
||||
final class DiscoverAbilitiesAbility {
|
||||
use McpAbilityHelperTrait;
|
||||
|
||||
/**
|
||||
* Register the ability.
|
||||
*/
|
||||
public static function register(): void {
|
||||
wp_register_ability(
|
||||
'mcp-adapter/discover-abilities',
|
||||
array(
|
||||
'label' => 'Discover Abilities',
|
||||
'description' => 'Discover all available WordPress abilities in the system. Returns a list of all registered abilities with their basic information.',
|
||||
'category' => 'mcp-adapter',
|
||||
'output_schema' => array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'abilities' => array(
|
||||
'type' => 'array',
|
||||
'items' => array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'name' => array( 'type' => 'string' ),
|
||||
'label' => array( 'type' => 'string' ),
|
||||
'description' => array( 'type' => 'string' ),
|
||||
),
|
||||
'required' => array( 'name', 'label', 'description' ),
|
||||
),
|
||||
),
|
||||
),
|
||||
'required' => array( 'abilities' ),
|
||||
),
|
||||
'permission_callback' => array( self::class, 'check_permission' ),
|
||||
'execute_callback' => array( self::class, 'execute' ),
|
||||
'meta' => array(
|
||||
'annotations' => array(
|
||||
'readonly' => true,
|
||||
'destructive' => false,
|
||||
'idempotent' => true,
|
||||
),
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the discover abilities functionality.
|
||||
*
|
||||
* Note: Permission checks are handled by the WP_Ability::execute() framework method
|
||||
* before this callback is invoked.
|
||||
*
|
||||
* @see \WP_Ability::execute()
|
||||
*
|
||||
* @param array $input Input parameters (unused for this ability).
|
||||
*
|
||||
* @return array Array containing public MCP abilities.
|
||||
*/
|
||||
public static function execute( $input = array() ): array {
|
||||
// Get all abilities and filter for publicly exposed ones
|
||||
$abilities = wp_get_abilities();
|
||||
|
||||
$ability_list = array();
|
||||
foreach ( $abilities as $ability ) {
|
||||
$ability_name = $ability->get_name();
|
||||
|
||||
// Check if ability is publicly exposed via MCP
|
||||
if ( ! self::is_ability_mcp_public( $ability ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Only discover abilities with type='tool' (default type)
|
||||
if ( self::get_ability_mcp_type( $ability ) !== 'tool' ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ability_list[] = array(
|
||||
'name' => $ability_name,
|
||||
'label' => $ability->get_label(),
|
||||
'description' => $ability->get_description(),
|
||||
);
|
||||
}
|
||||
|
||||
return array(
|
||||
'abilities' => $ability_list,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check permissions for discovering abilities.
|
||||
*
|
||||
* Validates user capabilities and caller identity.
|
||||
*
|
||||
* @param array $input Input parameters (unused for this ability).
|
||||
*
|
||||
* @return bool|\WP_Error True if the user has permission to discover abilities.
|
||||
*/
|
||||
public static function check_permission( $input = array() ) {
|
||||
// Verify caller identity - ensure user is authenticated
|
||||
if ( ! is_user_logged_in() ) {
|
||||
return new WP_Error( 'authentication_required', 'User must be authenticated to access this ability' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the capability required to discover available abilities.
|
||||
*
|
||||
* This capability is checked before listing all registered WordPress abilities
|
||||
* through the mcp-adapter-discover-abilities tool.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param string $capability The required capability. Default 'read'.
|
||||
*/
|
||||
$required_capability = apply_filters( 'mcp_adapter_discover_abilities_capability', 'read' );
|
||||
// phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Capability is determined dynamically via filter
|
||||
if ( ! current_user_can( $required_capability ) ) {
|
||||
return new WP_Error(
|
||||
'insufficient_capability',
|
||||
sprintf( 'User lacks required capability: %s', $required_capability )
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
<?php
|
||||
/**
|
||||
* Ability for executing WordPress abilities.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Abilities;
|
||||
|
||||
use WP\MCP\Domain\Utils\AbilityArgumentNormalizer;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Execute Ability - Executes a WordPress ability with provided parameters.
|
||||
*
|
||||
* This ability provides the primary execution layer for running any registered
|
||||
* WordPress ability through the MCP protocol.
|
||||
*
|
||||
* SECURITY CONSIDERATIONS:
|
||||
* - This ability has openWorldHint=true, allowing execution of any registered ability
|
||||
* - Only abilities with mcp.public=true metadata can be executed via default MCP server.
|
||||
* - Requires proper WordPress capability checks for secure operation
|
||||
* - Caller identity verification is enforced through WordPress authentication
|
||||
*
|
||||
* @see https://developer.wordpress.org/apis/security/ for detailed security guidance
|
||||
*/
|
||||
final class ExecuteAbilityAbility {
|
||||
use McpAbilityHelperTrait;
|
||||
|
||||
/**
|
||||
* Register the ability.
|
||||
*/
|
||||
public static function register(): void {
|
||||
wp_register_ability(
|
||||
'mcp-adapter/execute-ability',
|
||||
array(
|
||||
'label' => 'Execute Ability',
|
||||
'description' => 'Execute a WordPress ability with the provided parameters. This is the primary execution layer that can run any registered ability.',
|
||||
'category' => 'mcp-adapter',
|
||||
'input_schema' => array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'ability_name' => array(
|
||||
'type' => 'string',
|
||||
'description' => 'The full name of the ability to execute',
|
||||
),
|
||||
'parameters' => array(
|
||||
'type' => 'object',
|
||||
'description' => 'Parameters to pass to the ability',
|
||||
),
|
||||
),
|
||||
'required' => array( 'ability_name', 'parameters' ),
|
||||
),
|
||||
'output_schema' => array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'success' => array( 'type' => 'boolean' ),
|
||||
'data' => array(
|
||||
'type' => array(
|
||||
'object',
|
||||
'array',
|
||||
'string',
|
||||
'number',
|
||||
'integer',
|
||||
'boolean',
|
||||
'null',
|
||||
),
|
||||
'description' => 'The result data from the ability execution',
|
||||
),
|
||||
'error' => array(
|
||||
'type' => 'string',
|
||||
'description' => 'Error message if execution failed',
|
||||
),
|
||||
),
|
||||
'required' => array( 'success' ),
|
||||
),
|
||||
'permission_callback' => array( self::class, 'check_permission' ),
|
||||
'execute_callback' => array( self::class, 'execute' ),
|
||||
'meta' => array(
|
||||
'annotations' => array(
|
||||
'readonly' => false,
|
||||
'destructive' => true,
|
||||
'idempotent' => false,
|
||||
),
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the ability execution functionality.
|
||||
*
|
||||
* Note: Permission checks are handled by the WP_Ability::execute() framework method
|
||||
* before this callback is invoked. This ensures all ability executions are properly
|
||||
* authorized by the framework.
|
||||
*
|
||||
* @see \WP_Ability::execute()
|
||||
*
|
||||
* @param array $input Input parameters containing ability_name and parameters.
|
||||
*
|
||||
* @return array Array containing execution results.
|
||||
*/
|
||||
public static function execute( $input = array() ): array {
|
||||
$ability_name = $input['ability_name'] ?? '';
|
||||
// Note: Use null coalescing instead of empty() to preserve empty arrays/objects ({} → [])
|
||||
$parameters = $input['parameters'] ?? null;
|
||||
|
||||
if ( empty( $ability_name ) ) {
|
||||
return array(
|
||||
'success' => false,
|
||||
'error' => 'Ability name is required',
|
||||
);
|
||||
}
|
||||
|
||||
$ability = wp_get_ability( $ability_name );
|
||||
|
||||
if ( ! $ability ) {
|
||||
return array(
|
||||
'success' => false,
|
||||
'error' => "Ability '{$ability_name}' not found",
|
||||
);
|
||||
}
|
||||
|
||||
// Normalize parameters for ability's schema requirements
|
||||
// Empty {} from MCP is treated as null for abilities without input schema
|
||||
$parameters = AbilityArgumentNormalizer::normalize( $ability, $parameters );
|
||||
|
||||
try {
|
||||
// Execute the ability
|
||||
$result = $ability->execute( $parameters );
|
||||
|
||||
// Check if the result is a WP_Error
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return array(
|
||||
'success' => false,
|
||||
'error' => $result->get_error_message(),
|
||||
);
|
||||
}
|
||||
|
||||
return array(
|
||||
'success' => true,
|
||||
'data' => $result,
|
||||
);
|
||||
} catch ( \Throwable $e ) {
|
||||
return array(
|
||||
'success' => false,
|
||||
'error' => $e->getMessage(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check permissions for executing abilities.
|
||||
*
|
||||
* Validates user capabilities, caller identity, and MCP exposure restrictions.
|
||||
*
|
||||
* @param array $input Input parameters containing ability_name and parameters.
|
||||
*
|
||||
* @return bool|\WP_Error True if the user has permission to execute the specified ability.
|
||||
*/
|
||||
public static function check_permission( $input = array() ) {
|
||||
$ability_name = $input['ability_name'] ?? '';
|
||||
|
||||
if ( empty( $ability_name ) ) {
|
||||
return new WP_Error( 'missing_ability_name', 'Ability name is required' );
|
||||
}
|
||||
|
||||
// Validate user authentication and capabilities
|
||||
$user_check = self::validate_user_access();
|
||||
if ( is_wp_error( $user_check ) ) {
|
||||
return $user_check;
|
||||
}
|
||||
|
||||
// Check MCP exposure restrictions
|
||||
$exposure_check = self::check_ability_mcp_exposure( $ability_name );
|
||||
if ( is_wp_error( $exposure_check ) ) {
|
||||
return $exposure_check;
|
||||
}
|
||||
|
||||
// Get the target ability
|
||||
$ability = wp_get_ability( $ability_name );
|
||||
if ( ! $ability ) {
|
||||
return new WP_Error( 'ability_not_found', "Ability '{$ability_name}' not found" );
|
||||
}
|
||||
|
||||
// Normalize parameters for ability's schema requirements
|
||||
// Empty {} from MCP is treated as null for abilities without input schema
|
||||
$parameters = $input['parameters'] ?? null;
|
||||
$parameters = AbilityArgumentNormalizer::normalize( $ability, $parameters );
|
||||
$permission_result = $ability->check_permissions( $parameters );
|
||||
|
||||
// Return WP_Error as-is, or convert other values to boolean
|
||||
if ( is_wp_error( $permission_result ) ) {
|
||||
return $permission_result;
|
||||
}
|
||||
|
||||
return (bool) $permission_result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate user authentication and basic capabilities for execute ability.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
private static function validate_user_access() {
|
||||
// Verify caller identity - ensure the user is authenticated
|
||||
if ( ! is_user_logged_in() ) {
|
||||
return new WP_Error( 'authentication_required', 'User must be authenticated to access this ability' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the capability required to execute abilities.
|
||||
*
|
||||
* This is intentionally set to 'read' as the minimum baseline capability.
|
||||
* Each ability defines its own permission_callback that enforces the actual
|
||||
* capability requirements for that specific operation. This filter serves
|
||||
* only as a gate to prevent completely unauthenticated or capability-less
|
||||
* users from reaching the ability execution layer.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param string $capability The required capability. Default 'read'.
|
||||
*/
|
||||
$required_capability = apply_filters( 'mcp_adapter_execute_ability_capability', 'read' );
|
||||
// phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Capability is determined dynamically via filter
|
||||
if ( ! current_user_can( $required_capability ) ) {
|
||||
return new WP_Error(
|
||||
'insufficient_capability',
|
||||
sprintf( 'User lacks required capability: %s', $required_capability )
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
/**
|
||||
* Ability for getting detailed information about WordPress abilities.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Abilities;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Get Ability Info - Get detailed information about a specific WordPress ability.
|
||||
*
|
||||
* This ability provides detailed information about any registered WordPress ability,
|
||||
* including its input/output schemas, description, and usage examples.
|
||||
*
|
||||
* SECURITY CONSIDERATIONS:
|
||||
* - This ability exposes detailed schemas and metadata about abilities
|
||||
* - Only abilities with mcp.public=true metadata can be queried via default MCP server.
|
||||
* - Requires proper WordPress capability checks for secure operation
|
||||
*
|
||||
* @see https://developer.wordpress.org/apis/security/ for detailed security guidance
|
||||
*/
|
||||
final class GetAbilityInfoAbility {
|
||||
use McpAbilityHelperTrait;
|
||||
|
||||
/**
|
||||
* Register the ability.
|
||||
*/
|
||||
public static function register(): void {
|
||||
wp_register_ability(
|
||||
'mcp-adapter/get-ability-info',
|
||||
array(
|
||||
'label' => 'Get Ability Info',
|
||||
'description' => 'Get detailed information about a specific WordPress ability including its input/output schema, description, and usage examples.',
|
||||
'category' => 'mcp-adapter',
|
||||
'input_schema' => array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'ability_name' => array(
|
||||
'type' => 'string',
|
||||
'description' => 'The full name of the ability to get information about',
|
||||
),
|
||||
),
|
||||
'required' => array( 'ability_name' ),
|
||||
),
|
||||
'output_schema' => array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
'name' => array( 'type' => 'string' ),
|
||||
'label' => array( 'type' => 'string' ),
|
||||
'description' => array( 'type' => 'string' ),
|
||||
'input_schema' => array(
|
||||
'type' => 'object',
|
||||
'description' => 'JSON Schema for the ability input parameters',
|
||||
),
|
||||
'output_schema' => array(
|
||||
'type' => 'object',
|
||||
'description' => 'JSON Schema for the ability output structure',
|
||||
),
|
||||
'meta' => array(
|
||||
'type' => 'object',
|
||||
'description' => 'Additional metadata about the ability',
|
||||
),
|
||||
),
|
||||
'required' => array( 'name', 'label', 'description', 'input_schema' ),
|
||||
),
|
||||
'permission_callback' => array( self::class, 'check_permission' ),
|
||||
'execute_callback' => array( self::class, 'execute' ),
|
||||
'meta' => array(
|
||||
'annotations' => array(
|
||||
'readonly' => true,
|
||||
'destructive' => false,
|
||||
'idempotent' => true,
|
||||
),
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the get ability info functionality.
|
||||
*
|
||||
* Note: Permission checks are handled by the WP_Ability::execute() framework method
|
||||
* before this callback is invoked (see WP_Ability::execute() line 605).
|
||||
*
|
||||
* @param array $input Input parameters containing ability_name.
|
||||
*
|
||||
* @return array Array containing detailed ability information.
|
||||
*/
|
||||
public static function execute( $input = array() ): array {
|
||||
$ability_name = $input['ability_name'] ?? '';
|
||||
|
||||
if ( empty( $ability_name ) ) {
|
||||
return array(
|
||||
'error' => 'Ability name is required',
|
||||
);
|
||||
}
|
||||
|
||||
$ability = wp_get_ability( $ability_name );
|
||||
|
||||
if ( ! $ability ) {
|
||||
return array(
|
||||
'error' => "Ability '{$ability_name}' not found",
|
||||
);
|
||||
}
|
||||
|
||||
$ability_info = array(
|
||||
'name' => $ability->get_name(),
|
||||
'label' => $ability->get_label(),
|
||||
'description' => $ability->get_description(),
|
||||
'input_schema' => $ability->get_input_schema(),
|
||||
);
|
||||
|
||||
// Add output schema if available
|
||||
$output_schema = $ability->get_output_schema();
|
||||
if ( ! empty( $output_schema ) ) {
|
||||
$ability_info['output_schema'] = $output_schema;
|
||||
}
|
||||
|
||||
// Add meta information if available
|
||||
$meta = $ability->get_meta();
|
||||
if ( ! empty( $meta ) ) {
|
||||
$ability_info['meta'] = $meta;
|
||||
}
|
||||
|
||||
return $ability_info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check permissions for getting ability info.
|
||||
*
|
||||
* Validates user capabilities, caller identity, and MCP exposure restrictions.
|
||||
*
|
||||
* @param array $input Input parameters containing ability_name.
|
||||
*
|
||||
* @return bool|\WP_Error True if the user has permission to get ability info.
|
||||
*/
|
||||
public static function check_permission( $input = array() ) {
|
||||
$ability_name = $input['ability_name'] ?? '';
|
||||
|
||||
if ( empty( $ability_name ) ) {
|
||||
return new WP_Error( 'missing_ability_name', 'Ability name is required' );
|
||||
}
|
||||
|
||||
// Validate user authentication and capabilities
|
||||
$user_check = self::validate_user_access();
|
||||
if ( is_wp_error( $user_check ) ) {
|
||||
return $user_check;
|
||||
}
|
||||
|
||||
// Check MCP exposure restrictions
|
||||
return self::check_ability_mcp_exposure( $ability_name );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate user authentication and basic capabilities for get ability info.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
private static function validate_user_access() {
|
||||
// Verify caller identity - ensure user is authenticated
|
||||
if ( ! is_user_logged_in() ) {
|
||||
return new WP_Error( 'authentication_required', 'User must be authenticated to access this ability' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the capability required to get ability information.
|
||||
*
|
||||
* This capability is checked before returning detailed information about
|
||||
* a specific WordPress ability through the mcp-adapter-get-ability-info tool.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param string $capability The required capability. Default 'read'.
|
||||
*/
|
||||
$required_capability = apply_filters( 'mcp_adapter_get_ability_info_capability', 'read' );
|
||||
// phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Capability is determined dynamically via filter
|
||||
if ( ! current_user_can( $required_capability ) ) {
|
||||
return new WP_Error(
|
||||
'insufficient_capability',
|
||||
sprintf( 'User lacks required capability: %s', $required_capability )
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
/**
|
||||
* Helper trait for WordPress abilities providing MCP-related utilities.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Abilities;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Trait McpAbilityHelperTrait
|
||||
*
|
||||
* Provides helper methods for MCP abilities including MCP exposure checking and metadata handling.
|
||||
*/
|
||||
trait McpAbilityHelperTrait {
|
||||
|
||||
/**
|
||||
* Checks if ability is publicly exposed via MCP.
|
||||
*
|
||||
* Validates against the ability's mcp.public metadata flag.
|
||||
* Only abilities with mcp.public=true are accessible via default MCP server.
|
||||
*
|
||||
* @param string $ability_name The ability name to check.
|
||||
*
|
||||
* @return bool|\WP_Error True if publicly exposed, WP_Error if not.
|
||||
*/
|
||||
protected static function check_ability_mcp_exposure( string $ability_name ) {
|
||||
$ability = wp_get_ability( $ability_name );
|
||||
|
||||
if ( ! $ability ) {
|
||||
return new WP_Error( 'ability_not_found', "Ability '{$ability_name}' not found" );
|
||||
}
|
||||
|
||||
$meta = $ability->get_meta();
|
||||
$is_public_mcp = $meta['mcp']['public'] ?? false;
|
||||
|
||||
if ( ! $is_public_mcp ) {
|
||||
return new WP_Error(
|
||||
'ability_not_public_mcp',
|
||||
sprintf( 'Ability "%s" is not exposed via MCP (mcp.public!=true)', $ability_name )
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if ability is publicly exposed via MCP (simple boolean version).
|
||||
*
|
||||
* This is a simplified version that returns only boolean values,
|
||||
* useful for filtering operations where WP_Error handling isn't needed.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability object to check.
|
||||
*
|
||||
* @return bool True if publicly exposed, false otherwise.
|
||||
*/
|
||||
protected static function is_ability_mcp_public( \WP_Ability $ability ): bool {
|
||||
$meta = $ability->get_meta();
|
||||
|
||||
return (bool) ( $meta['mcp']['public'] ?? false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the MCP type of an ability.
|
||||
*
|
||||
* Returns the type specified in meta.mcp.type, defaulting to 'tool' if not specified.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability object to check.
|
||||
*
|
||||
* @return string The MCP type ('tool', 'resource', or 'prompt'). Defaults to 'tool'.
|
||||
*/
|
||||
protected static function get_ability_mcp_type( \WP_Ability $ability ): string {
|
||||
$meta = $ability->get_meta();
|
||||
$type = $meta['mcp']['type'] ?? 'tool';
|
||||
|
||||
// Validate type is one of the allowed values
|
||||
if ( ! in_array( $type, array( 'tool', 'resource', 'prompt' ), true ) ) {
|
||||
return 'tool';
|
||||
}
|
||||
|
||||
return $type;
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
/**
|
||||
* PSR-4 Autoloader for PHP classes inside plugin.
|
||||
*
|
||||
* Ensures that autoloaders are present, and logs an Admin notice if not.
|
||||
*
|
||||
* Can be bypassed by defining the WP_MCP_AUTOLOAD constant to false.
|
||||
*
|
||||
* @package WP\MCP
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP;
|
||||
|
||||
/**
|
||||
* Class - Autoloader
|
||||
*/
|
||||
final class Autoloader {
|
||||
/**
|
||||
* Whether the autoloader has been loaded.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static bool $is_loaded = false;
|
||||
|
||||
/**
|
||||
* Attempt to autoload the Composer dependencies.
|
||||
*/
|
||||
public static function autoload(): bool {
|
||||
// If we're not *supposed* to autoload anything, then return true.
|
||||
if ( defined( 'WP_MCP_AUTOLOAD' ) && false === WP_MCP_AUTOLOAD ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ( self::$is_loaded ) {
|
||||
return self::$is_loaded;
|
||||
}
|
||||
|
||||
$autoloader = WP_MCP_DIR . '/vendor/autoload.php';
|
||||
self::$is_loaded = self::require_autoloader( $autoloader );
|
||||
|
||||
return self::$is_loaded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to load the autoloader file, if it exists.
|
||||
*
|
||||
* @param string $autoloader_file The path to the autoloader file.
|
||||
*/
|
||||
private static function require_autoloader( string $autoloader_file ): bool {
|
||||
if ( ! is_readable( $autoloader_file ) ) {
|
||||
self::missing_autoloader_notice();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) require_once $autoloader_file; // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- Autoloader is a Composer file.
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a notice if the autoloader is missing.
|
||||
*/
|
||||
private static function missing_autoloader_notice(): void {
|
||||
|
||||
$hooks = array(
|
||||
'admin_notices',
|
||||
'network_admin_notices',
|
||||
);
|
||||
|
||||
foreach ( $hooks as $hook ) {
|
||||
add_action(
|
||||
$hook,
|
||||
static function () {
|
||||
$error_message = __( 'MCP Adapter: The Composer autoloader was not found. If you installed the plugin from the GitHub source code, make sure to run `composer install`.', 'mcp-adapter' );
|
||||
|
||||
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
|
||||
error_log( esc_html( $error_message ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- This is a development notice.
|
||||
}
|
||||
?>
|
||||
<div class="error notice">
|
||||
<p>
|
||||
<?php echo esc_html( $error_message ); ?>
|
||||
</p>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
/**
|
||||
* WP-CLI Command for MCP STDIO Transport
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Cli;
|
||||
|
||||
use WP\MCP\Core\McpAdapter;
|
||||
use function WP_CLI\Utils\format_items;
|
||||
|
||||
/**
|
||||
* Manage MCP servers via WP-CLI.
|
||||
*
|
||||
* Provides commands to serve MCP servers over STDIO transport for
|
||||
* communication with MCP clients via subprocess.
|
||||
*/
|
||||
class McpCommand extends \WP_CLI_Command { // phpcs:ignore
|
||||
|
||||
/**
|
||||
* Serve an MCP server via STDIO transport.
|
||||
*
|
||||
* This command starts an MCP server that communicates via standard input/output
|
||||
* using the JSON-RPC 2.0 protocol. It's designed to be launched as a subprocess
|
||||
* by MCP clients.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--server=<server-id>]
|
||||
* : The ID of the MCP server to serve. If not specified, uses the first available server.
|
||||
*
|
||||
* [--user=<id|login|email>]
|
||||
* : Run as a specific WordPress user for permission checks.
|
||||
* : Without this, runs as unauthenticated (limited capabilities).
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # Serve the default MCP server as admin user
|
||||
* wp mcp serve --user=admin
|
||||
*
|
||||
* # Serve a specific server as user with ID 1
|
||||
* wp mcp serve --server=my-mcp-server --user=1
|
||||
*
|
||||
* # Serve without authentication (limited capabilities)
|
||||
* wp mcp serve --server=public-server
|
||||
*
|
||||
* @when after_wp_load
|
||||
* @synopsis [--server=<server-id>] [--user=<id|login|email>]
|
||||
*/
|
||||
public function serve( array $args, array $assoc_args ): void {
|
||||
|
||||
// Get the MCP adapter instance
|
||||
$adapter = McpAdapter::instance();
|
||||
|
||||
// Get all registered servers
|
||||
$servers = $adapter->get_servers();
|
||||
|
||||
if ( empty( $servers ) ) {
|
||||
\WP_CLI::error( 'No MCP servers are registered. Please register at least one server first.' );
|
||||
}
|
||||
|
||||
// Determine which server to use
|
||||
$server_id = $assoc_args['server'] ?? null;
|
||||
$server = null;
|
||||
|
||||
if ( $server_id ) {
|
||||
$server = $adapter->get_server( $server_id );
|
||||
if ( ! $server ) {
|
||||
\WP_CLI::error( sprintf( 'Server with ID "%s" not found.', $server_id ) );
|
||||
}
|
||||
} else {
|
||||
// Use the first available server
|
||||
$server = array_values( $servers )[0];
|
||||
$server_id = $server->get_server_id();
|
||||
\WP_CLI::line( sprintf( 'Using server: %s', $server_id ) );
|
||||
}
|
||||
|
||||
// Set user context if specified
|
||||
if ( isset( $assoc_args['user'] ) ) {
|
||||
$user = $this->get_user( $assoc_args['user'] );
|
||||
if ( ! $user ) {
|
||||
\WP_CLI::error( sprintf( 'User "%s" not found.', $assoc_args['user'] ) );
|
||||
}
|
||||
|
||||
wp_set_current_user( $user->ID );
|
||||
\WP_CLI::debug( sprintf( 'Running as user: %s (ID: %d)', $user->user_login, $user->ID ) );
|
||||
} else {
|
||||
\WP_CLI::debug( 'Running without authentication. Some capabilities may be limited.' );
|
||||
}
|
||||
|
||||
// Create and start STDIO server bridge
|
||||
try {
|
||||
\WP_CLI::debug( sprintf( 'Starting STDIO bridge for server: %s', $server_id ) );
|
||||
|
||||
// Create STDIO server bridge
|
||||
$stdio_bridge = new StdioServerBridge( $server );
|
||||
|
||||
// Start serving (this blocks until terminated)
|
||||
$stdio_bridge->serve();
|
||||
} catch ( \RuntimeException $e ) {
|
||||
\WP_CLI::error( $e->getMessage() );
|
||||
} catch ( \Throwable $e ) {
|
||||
\WP_CLI::error( 'Failed to start STDIO bridge: ' . $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user by ID, login, or email.
|
||||
*
|
||||
* @param string $user User identifier (ID, login, or email).
|
||||
*
|
||||
* @return \WP_User|false User object or false if not found.
|
||||
*/
|
||||
private function get_user( string $user ) {
|
||||
// Try as ID first
|
||||
if ( is_numeric( $user ) ) {
|
||||
return get_user_by( 'id', (int) $user );
|
||||
}
|
||||
|
||||
// Try as login
|
||||
$user_obj = get_user_by( 'login', $user );
|
||||
if ( $user_obj ) {
|
||||
return $user_obj;
|
||||
}
|
||||
|
||||
// Try as email
|
||||
return get_user_by( 'email', $user );
|
||||
}
|
||||
|
||||
/**
|
||||
* List all registered MCP servers.
|
||||
*
|
||||
* ## OPTIONS
|
||||
*
|
||||
* [--format=<format>]
|
||||
* : Render output in a particular format.
|
||||
* ---
|
||||
* default: table
|
||||
* options:
|
||||
* - table
|
||||
* - csv
|
||||
* - json
|
||||
* - yaml
|
||||
* ---
|
||||
*
|
||||
* ## EXAMPLES
|
||||
*
|
||||
* # List all MCP servers
|
||||
* wp mcp list
|
||||
*
|
||||
* # List servers in JSON format
|
||||
* wp mcp list --format=json
|
||||
*
|
||||
* @when after_wp_load
|
||||
* @synopsis [--format=<format>]
|
||||
*/
|
||||
public function list( array $args, array $assoc_args ): void {
|
||||
$adapter = McpAdapter::instance();
|
||||
|
||||
$servers = $adapter->get_servers();
|
||||
|
||||
if ( empty( $servers ) ) {
|
||||
\WP_CLI::line( 'No MCP servers registered.' );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$items = array();
|
||||
foreach ( $servers as $server ) {
|
||||
$items[] = array(
|
||||
'ID' => $server->get_server_id(),
|
||||
'Name' => $server->get_server_name(),
|
||||
'Version' => $server->get_server_version(),
|
||||
'Tools' => count( $server->get_tools() ),
|
||||
'Resources' => count( $server->get_resources() ),
|
||||
'Prompts' => count( $server->get_prompts() ),
|
||||
'Description' => $server->get_server_description(),
|
||||
);
|
||||
}
|
||||
|
||||
$format = $assoc_args['format'] ?? 'table';
|
||||
format_items( $format, $items, array( 'ID', 'Name', 'Version', 'Tools', 'Resources', 'Prompts' ) );
|
||||
}
|
||||
}
|
||||
Vendored
+349
@@ -0,0 +1,349 @@
|
||||
<?php
|
||||
/**
|
||||
* STDIO Server Bridge for MCP Adapter
|
||||
*
|
||||
* This service acts as a bridge between the STDIO protocol and MCP servers,
|
||||
* allowing any registered server to be exposed via command-line interface.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Cli;
|
||||
|
||||
use WP\MCP\Core\McpServer;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\McpErrorFactory;
|
||||
use WP\MCP\Transport\Infrastructure\JsonRpcResponseBuilder;
|
||||
use WP\MCP\Transport\Infrastructure\RequestRouter;
|
||||
|
||||
/**
|
||||
* STDIO Server Bridge - Exposes MCP servers via STDIO protocol
|
||||
*
|
||||
* This service handles JSON-RPC communication over stdin/stdout and delegates
|
||||
* requests to the appropriate MCP server. Unlike transport implementations,
|
||||
* this is a presentation layer service that can work with any server.
|
||||
*/
|
||||
class StdioServerBridge {
|
||||
|
||||
/**
|
||||
* The MCP server to expose via STDIO.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
private McpServer $server;
|
||||
|
||||
/**
|
||||
* Request router for handling MCP requests.
|
||||
*
|
||||
* @var \WP\MCP\Transport\Infrastructure\RequestRouter
|
||||
*/
|
||||
private RequestRouter $request_router;
|
||||
|
||||
/**
|
||||
* Whether the bridge is currently running.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private bool $is_running = false;
|
||||
|
||||
/**
|
||||
* Initialize the STDIO server bridge.
|
||||
*
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server to expose.
|
||||
*/
|
||||
public function __construct( McpServer $server ) {
|
||||
$this->server = $server;
|
||||
|
||||
// Create request router using server's infrastructure
|
||||
$this->request_router = $this->create_request_router();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a request router for the server.
|
||||
*
|
||||
* @return \WP\MCP\Transport\Infrastructure\RequestRouter
|
||||
*/
|
||||
private function create_request_router(): RequestRouter {
|
||||
// Create transport context using server's infrastructure
|
||||
$context = $this->server->create_transport_context();
|
||||
|
||||
return $context->request_router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the STDIO server bridge.
|
||||
*
|
||||
* This method reads JSON-RPC messages from stdin and writes responses to stdout.
|
||||
* It runs in a loop until terminated or until it receives a shutdown signal.
|
||||
*
|
||||
* @throws \RuntimeException If STDIO transport is disabled.
|
||||
*/
|
||||
public function serve(): void {
|
||||
/**
|
||||
* Filters whether the STDIO transport is enabled.
|
||||
*
|
||||
* Return false to disable STDIO transport entirely. This prevents
|
||||
* the WP-CLI `mcp-adapter serve` command from functioning.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param bool $enabled Whether STDIO transport is enabled. Default true.
|
||||
*/
|
||||
$enable_serve = apply_filters( 'mcp_adapter_enable_stdio_transport', true );
|
||||
|
||||
if ( ! $enable_serve ) {
|
||||
throw new \RuntimeException(
|
||||
'The STDIO transport is disabled. Enable it by setting the "mcp_adapter_enable_stdio_transport" filter to true.'
|
||||
);
|
||||
}
|
||||
|
||||
$this->is_running = true;
|
||||
|
||||
// Log to stderr to keep stdout clean for MCP messages
|
||||
$this->log_to_stderr( sprintf( 'MCP STDIO Bridge started for server: %s', $this->server->get_server_id() ) );
|
||||
|
||||
// Main server loop
|
||||
while ( $this->is_running ) {
|
||||
try {
|
||||
// Read a line from stdin (blocking)
|
||||
$input = fgets( STDIN );
|
||||
|
||||
if ( false === $input ) {
|
||||
// EOF or error reading from stdin
|
||||
break;
|
||||
}
|
||||
|
||||
// Trim newline delimiter
|
||||
$input = rtrim( $input, "\r\n" );
|
||||
|
||||
if ( empty( $input ) ) {
|
||||
// Empty line, continue reading
|
||||
continue;
|
||||
}
|
||||
|
||||
// Process the request and get response
|
||||
$response = $this->handle_request( $input );
|
||||
|
||||
// Write response to stdout with newline delimiter
|
||||
if ( ! empty( $response ) ) {
|
||||
// Use fwrite() for precise binary-safe JSON-RPC protocol communication.
|
||||
// WP_CLI output functions would add formatting/prefixes that break MCP protocol.
|
||||
// MCP requires exact control over stdout for machine-to-machine communication.
|
||||
fwrite( STDOUT, $response . "\n" ); // phpcs:ignore
|
||||
fflush( STDOUT );
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
// Log errors to stderr
|
||||
$this->log_to_stderr( 'Error processing request: ' . $e->getMessage() );
|
||||
|
||||
$error_response = $this->encode_response(
|
||||
JsonRpcResponseBuilder::create_error_response(
|
||||
null,
|
||||
array(
|
||||
'code' => McpErrorFactory::INTERNAL_ERROR,
|
||||
'message' => 'Internal error',
|
||||
'data' => array(
|
||||
'details' => $e->getMessage(),
|
||||
),
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
fwrite( STDOUT, $error_response . "\n" ); // phpcs:ignore
|
||||
fflush( STDOUT );
|
||||
}
|
||||
}
|
||||
|
||||
$this->log_to_stderr( 'MCP STDIO Bridge stopped' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a message to stderr.
|
||||
*
|
||||
* @param string $message The message to log.
|
||||
*/
|
||||
private function log_to_stderr( string $message ): void {
|
||||
fwrite( STDERR, "[MCP STDIO Bridge] $message\n" ); // phpcs:ignore
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a JSON-RPC request string and return a JSON-RPC response string.
|
||||
*
|
||||
* @param string $json_input The JSON-RPC request string.
|
||||
*
|
||||
* @return string The JSON-RPC response string (empty for notifications).
|
||||
*/
|
||||
private function handle_request( string $json_input ): string {
|
||||
try {
|
||||
// Parse JSON-RPC request
|
||||
$request = json_decode( $json_input, true );
|
||||
|
||||
if ( json_last_error() !== JSON_ERROR_NONE ) {
|
||||
return $this->create_error_response(
|
||||
null,
|
||||
McpErrorFactory::PARSE_ERROR,
|
||||
'Parse error',
|
||||
'Invalid JSON was received by the server.'
|
||||
);
|
||||
}
|
||||
|
||||
// Validate JSON-RPC structure
|
||||
if ( ! is_array( $request ) ) {
|
||||
return $this->create_error_response(
|
||||
null,
|
||||
McpErrorFactory::INVALID_REQUEST,
|
||||
'Invalid Request',
|
||||
'The JSON sent is not a valid Request object.'
|
||||
);
|
||||
}
|
||||
|
||||
// Check for JSON-RPC version
|
||||
if ( ! isset( $request['jsonrpc'] ) || '2.0' !== $request['jsonrpc'] ) {
|
||||
return $this->create_error_response(
|
||||
$request['id'] ?? null,
|
||||
McpErrorFactory::INVALID_REQUEST,
|
||||
'Invalid Request',
|
||||
'The JSON-RPC version must be 2.0.'
|
||||
);
|
||||
}
|
||||
|
||||
// Extract request components
|
||||
$method = $request['method'] ?? null;
|
||||
$params = $request['params'] ?? array();
|
||||
$id = $request['id'] ?? null;
|
||||
|
||||
if ( ! is_string( $method ) ) {
|
||||
return $this->create_error_response(
|
||||
$id,
|
||||
McpErrorFactory::INVALID_REQUEST,
|
||||
'Invalid Request',
|
||||
'Method must be a string.'
|
||||
);
|
||||
}
|
||||
|
||||
// Convert params to array if it's an object
|
||||
if ( is_object( $params ) ) {
|
||||
$params = (array) $params;
|
||||
}
|
||||
|
||||
if ( ! is_array( $params ) ) {
|
||||
$params = array();
|
||||
}
|
||||
|
||||
// Route the request to the appropriate handler
|
||||
$result = $this->request_router->route_request(
|
||||
$method,
|
||||
$params,
|
||||
$id,
|
||||
'stdio'
|
||||
);
|
||||
|
||||
// If this is a notification (no id), don't send a response
|
||||
if ( null === $id ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Format the response
|
||||
return $this->format_response( $result, $id );
|
||||
} catch ( \Throwable $e ) {
|
||||
// Handle unexpected errors
|
||||
return $this->create_error_response(
|
||||
null,
|
||||
McpErrorFactory::INTERNAL_ERROR,
|
||||
'Internal error',
|
||||
$e->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a JSON-RPC error response.
|
||||
*
|
||||
* @param mixed $id The request ID (can be null).
|
||||
* @param int $code The error code.
|
||||
* @param string $message The error message.
|
||||
* @param string $data Optional error data.
|
||||
*
|
||||
* @return string The JSON error response string.
|
||||
*/
|
||||
private function create_error_response( $id, int $code, string $message, string $data = '' ): string {
|
||||
$error = array(
|
||||
'code' => $code,
|
||||
'message' => $message,
|
||||
);
|
||||
|
||||
if ( '' !== $data ) {
|
||||
$error['data'] = $data;
|
||||
}
|
||||
|
||||
return $this->encode_response( JsonRpcResponseBuilder::create_error_response( $id, $error ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a JSON-RPC response to a string.
|
||||
*
|
||||
* @param array $response JSON-RPC response structure.
|
||||
*
|
||||
* @return string JSON-encoded response string.
|
||||
*/
|
||||
private function encode_response( array $response ): string {
|
||||
$json = wp_json_encode( $response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
|
||||
|
||||
if ( false === $json ) {
|
||||
// Fallback when JSON encoding fails - use constant for consistency.
|
||||
return sprintf(
|
||||
'{"jsonrpc":"2.0","error":{"code":%d,"message":"Internal error"},"id":null}',
|
||||
McpErrorFactory::INTERNAL_ERROR
|
||||
);
|
||||
}
|
||||
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a handler result as a JSON-RPC response.
|
||||
*
|
||||
* @param array $result The handler result.
|
||||
* @param mixed $id The request ID.
|
||||
*
|
||||
* @return string The JSON-RPC response string.
|
||||
*/
|
||||
private function format_response( array $result, $id ): string {
|
||||
// Check if result contains an error
|
||||
if ( isset( $result['error'] ) ) {
|
||||
$error = $result['error'];
|
||||
|
||||
// Ensure error has required fields
|
||||
$error_payload = array(
|
||||
'code' => $error['code'] ?? McpErrorFactory::INTERNAL_ERROR,
|
||||
'message' => $error['message'] ?? 'Internal error',
|
||||
);
|
||||
|
||||
// Add data field if present
|
||||
if ( isset( $error['data'] ) ) {
|
||||
$error_payload['data'] = $error['data'];
|
||||
}
|
||||
|
||||
return $this->encode_response( JsonRpcResponseBuilder::create_error_response( $id, $error_payload ) );
|
||||
}
|
||||
|
||||
return $this->encode_response( JsonRpcResponseBuilder::create_success_response( $id, $result ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the STDIO server bridge.
|
||||
*/
|
||||
public function stop(): void {
|
||||
$this->is_running = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the server this bridge is exposing.
|
||||
*
|
||||
* @return \WP\MCP\Core\McpServer
|
||||
*/
|
||||
public function get_server(): McpServer {
|
||||
return $this->server;
|
||||
}
|
||||
}
|
||||
Vendored
+351
@@ -0,0 +1,351 @@
|
||||
<?php
|
||||
/**
|
||||
* WordPress MCP Registry - Main class for managing multiple MCP servers.
|
||||
*
|
||||
* @package WP\MCP\Core
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Core;
|
||||
|
||||
use WP\MCP\Abilities\DiscoverAbilitiesAbility;
|
||||
use WP\MCP\Abilities\ExecuteAbilityAbility;
|
||||
use WP\MCP\Abilities\GetAbilityInfoAbility;
|
||||
use WP\MCP\Cli\McpCommand;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\NullMcpErrorHandler;
|
||||
use WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\NullMcpObservabilityHandler;
|
||||
use WP\MCP\Servers\DefaultServerFactory;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* WordPress MCP Registry - Main class for managing multiple MCP servers.
|
||||
*/
|
||||
final class McpAdapter {
|
||||
|
||||
public const VERSION = '0.5.0';
|
||||
|
||||
/**
|
||||
* Registry instance
|
||||
*
|
||||
* @var \WP\MCP\Core\McpAdapter
|
||||
*/
|
||||
private static self $instance;
|
||||
/**
|
||||
* Track if the adapter has been initialized to prevent duplicate initialization
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private static bool $initialized = false;
|
||||
/**
|
||||
* Registered servers
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer[]
|
||||
*/
|
||||
private array $servers = array();
|
||||
|
||||
/**
|
||||
* Get the registry instance
|
||||
*
|
||||
* @return \WP\MCP\Core\McpAdapter
|
||||
*/
|
||||
public static function instance(): self {
|
||||
if ( ! isset( self::$instance ) ) {
|
||||
self::$instance = new self();
|
||||
|
||||
// In WP-CLI context, initialize immediately so commands have access to servers
|
||||
if ( defined( 'WP_CLI' ) && constant( 'WP_CLI' ) ) {
|
||||
add_action( 'init', array( self::$instance, 'init' ), 20 );
|
||||
} else {
|
||||
// Initialize for REST API requests with reasonable priority
|
||||
add_action( 'rest_api_init', array( self::$instance, 'init' ), 15 );
|
||||
}
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the registry
|
||||
*
|
||||
* @internal For use by instance initialization only.
|
||||
*/
|
||||
public function init(): void {
|
||||
if ( self::$initialized ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->maybe_create_default_server();
|
||||
|
||||
/**
|
||||
* Fires after the MCP Adapter has been initialized.
|
||||
*
|
||||
* Use this action to register custom MCP servers. The adapter instance
|
||||
* provides methods to create and configure additional servers beyond
|
||||
* the default server.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param \WP\MCP\Core\McpAdapter $adapter The MCP Adapter singleton instance.
|
||||
*/
|
||||
do_action( 'mcp_adapter_init', $this );
|
||||
$this->register_wp_cli_commands();
|
||||
self::$initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Conditionally create the default server based on filter.
|
||||
*
|
||||
* @internal For use by adapter initialization only.
|
||||
*/
|
||||
private function maybe_create_default_server(): void {
|
||||
/**
|
||||
* Filters whether the default MCP server should be created.
|
||||
*
|
||||
* Return false to prevent the default server from being created.
|
||||
* This is useful when you want to define custom servers only.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param bool $create_default Whether to create the default server. Default true.
|
||||
*/
|
||||
if ( ! apply_filters( 'mcp_adapter_create_default_server', true ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Register category before abilities
|
||||
add_action( 'wp_abilities_api_categories_init', array( $this, 'register_default_category' ) );
|
||||
add_action( 'wp_abilities_api_init', array( $this, 'register_default_abilities' ) );
|
||||
|
||||
add_action( 'mcp_adapter_init', array( DefaultServerFactory::class, 'create' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register WP-CLI commands if WP-CLI is available
|
||||
*
|
||||
* @internal For use by adapter initialization only.
|
||||
*/
|
||||
private function register_wp_cli_commands(): void {
|
||||
// Only register if WP-CLI is available
|
||||
if ( ! defined( 'WP_CLI' ) || ! constant( 'WP_CLI' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( ! class_exists( '\WP_CLI' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
\WP_CLI::add_command(
|
||||
'mcp-adapter',
|
||||
McpCommand::class,
|
||||
array(
|
||||
'shortdesc' => 'Manage MCP servers via WP-CLI.',
|
||||
'longdesc' => 'Commands for managing and serving MCP servers, including STDIO transport.',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and register a new MCP server.
|
||||
*
|
||||
* @param string $server_id Unique identifier for the server.
|
||||
* @param string $server_route_namespace Server route namespace.
|
||||
* @param string $server_route Server route.
|
||||
* @param string $server_name Server name.
|
||||
* @param string $server_description Server description.
|
||||
* @param string $server_version Server version.
|
||||
* @param array<class-string<\WP\MCP\Transport\Contracts\McpTransportInterface>> $mcp_transports Array of MCP transport class names to initialize.
|
||||
* @param class-string<\WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface>|null $error_handler The error handler class name. If null, NullMcpErrorHandler will be used.
|
||||
* @param class-string<\WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface>|null $observability_handler The observability handler class name. If null, NullMcpObservabilityHandler will be used.
|
||||
* @param list<string> $tools Ability names to register as tools.
|
||||
* @param list<string> $resources Resources to register.
|
||||
* @param list<string> $prompts Prompts to register.
|
||||
* @param callable|null $transport_permission_callback Optional custom permission callback for transport-level authentication. If null, defaults to is_user_logged_in().
|
||||
*
|
||||
* @return \WP\MCP\Core\McpAdapter|\WP_Error McpAdapter instance on success, WP_Error on failure.
|
||||
*/
|
||||
public function create_server( string $server_id, string $server_route_namespace, string $server_route, string $server_name, string $server_description, string $server_version, array $mcp_transports, ?string $error_handler, ?string $observability_handler = null, array $tools = array(), array $resources = array(), array $prompts = array(), ?callable $transport_permission_callback = null ) {
|
||||
// Use NullMcpErrorHandler if no error handler is provided.
|
||||
if ( ! $error_handler ) {
|
||||
$error_handler = NullMcpErrorHandler::class;
|
||||
}
|
||||
|
||||
// Validate error handler class exists and implements McpErrorHandlerInterface.
|
||||
if ( ! class_exists( $error_handler ) ) {
|
||||
return new WP_Error(
|
||||
'invalid_error_handler',
|
||||
sprintf(
|
||||
/* translators: %s: error handler class name */
|
||||
esc_html__( 'Error handler class "%s" does not exist.', 'mcp-adapter' ),
|
||||
esc_html( $error_handler )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! in_array( McpErrorHandlerInterface::class, class_implements( $error_handler ) ?: array(), true ) ) {
|
||||
return new WP_Error(
|
||||
'invalid_error_handler',
|
||||
sprintf(
|
||||
/* translators: %s: error handler class name */
|
||||
esc_html__( 'Error handler class "%s" must implement the McpErrorHandlerInterface.', 'mcp-adapter' ),
|
||||
esc_html( $error_handler )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Use NullMcpObservabilityHandler if no observability handler is provided.
|
||||
if ( ! $observability_handler ) {
|
||||
$observability_handler = NullMcpObservabilityHandler::class;
|
||||
}
|
||||
|
||||
// Validate observability handler class exists and implements McpObservabilityHandlerInterface.
|
||||
if ( ! class_exists( $observability_handler ) ) {
|
||||
return new WP_Error(
|
||||
'invalid_observability_handler',
|
||||
sprintf(
|
||||
/* translators: %s: observability handler class name */
|
||||
esc_html__( 'Observability handler class "%s" does not exist.', 'mcp-adapter' ),
|
||||
esc_html( $observability_handler )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! in_array( McpObservabilityHandlerInterface::class, class_implements( $observability_handler ) ?: array(), true ) ) {
|
||||
return new WP_Error(
|
||||
'invalid_observability_handler',
|
||||
sprintf(
|
||||
/* translators: %s: observability handler class name */
|
||||
esc_html__( 'Observability handler class "%s" must implement the McpObservabilityHandlerInterface interface.', 'mcp-adapter' ),
|
||||
esc_html( $observability_handler )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( ! doing_action( 'mcp_adapter_init' ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
esc_html__( 'MCP Servers must be created during the "mcp_adapter_init" action. Hook into "mcp_adapter_init" to register your server.', 'mcp-adapter' ),
|
||||
'0.1.0'
|
||||
);
|
||||
|
||||
return new WP_Error(
|
||||
'invalid_timing',
|
||||
esc_html__( 'MCP Server creation must be done during mcp_adapter_init action.', 'mcp-adapter' )
|
||||
);
|
||||
}
|
||||
|
||||
if ( isset( $this->servers[ $server_id ] ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
sprintf(
|
||||
// translators: %s: server ID
|
||||
esc_html__( 'Server with ID "%s" already exists. Each server must have a unique ID.', 'mcp-adapter' ),
|
||||
esc_html( $server_id )
|
||||
),
|
||||
'0.1.0'
|
||||
);
|
||||
|
||||
return new WP_Error(
|
||||
'duplicate_server_id',
|
||||
// translators: %s: server ID.
|
||||
sprintf( esc_html__( 'Server with ID "%s" already exists.', 'mcp-adapter' ), esc_html( $server_id ) )
|
||||
);
|
||||
}
|
||||
|
||||
// Create server with tools, resources, and prompts - let server handle all registration logic.
|
||||
try {
|
||||
$server = new McpServer(
|
||||
$server_id,
|
||||
$server_route_namespace,
|
||||
$server_route,
|
||||
$server_name,
|
||||
$server_description,
|
||||
$server_version,
|
||||
$mcp_transports,
|
||||
$error_handler,
|
||||
$observability_handler,
|
||||
$tools,
|
||||
$resources,
|
||||
$prompts,
|
||||
$transport_permission_callback
|
||||
);
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'server_creation_failed',
|
||||
sprintf(
|
||||
/* translators: 1: server ID, 2: error message */
|
||||
esc_html__( 'Failed to create server "%1$s": %2$s', 'mcp-adapter' ),
|
||||
esc_html( $server_id ),
|
||||
esc_html( $e->getMessage() )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Track server creation.
|
||||
$server->get_observability_handler()->record_event(
|
||||
'mcp.server.created',
|
||||
array(
|
||||
'status' => 'success',
|
||||
'server_id' => $server_id,
|
||||
'transport_count' => count( $mcp_transports ),
|
||||
'tools_count' => count( $tools ),
|
||||
'resources_count' => count( $resources ),
|
||||
'prompts_count' => count( $prompts ),
|
||||
)
|
||||
);
|
||||
|
||||
// Add server to registry.
|
||||
$this->servers[ $server_id ] = $server;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a server by ID.
|
||||
*
|
||||
* @param string $server_id Server ID.
|
||||
*
|
||||
* @return \WP\MCP\Core\McpServer|null
|
||||
*/
|
||||
public function get_server( string $server_id ): ?McpServer {
|
||||
return $this->servers[ $server_id ] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered servers
|
||||
*
|
||||
* @return \WP\MCP\Core\McpServer[]
|
||||
*/
|
||||
public function get_servers(): array {
|
||||
return $this->servers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the default MCP category.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_default_category(): void {
|
||||
wp_register_ability_category(
|
||||
'mcp-adapter',
|
||||
array(
|
||||
'label' => 'MCP Adapter',
|
||||
'description' => 'Abilities for the MCP Adapter',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the default MCP abilities.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_default_abilities(): void {
|
||||
// Register the three core MCP abilities
|
||||
DiscoverAbilitiesAbility::register();
|
||||
GetAbilityInfoAbility::register();
|
||||
ExecuteAbilityAbility::register();
|
||||
}
|
||||
}
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MCP Component Registry for managing tools, resources, and prompts.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Core;
|
||||
|
||||
use WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface;
|
||||
use WP\MCP\Domain\Prompts\McpPrompt;
|
||||
use WP\MCP\Domain\Resources\McpResource;
|
||||
use WP\MCP\Domain\Tools\McpTool;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\FailureReason;
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt as PromptDto;
|
||||
use WP\McpSchema\Server\Resources\DTO\Resource as ResourceDto;
|
||||
use WP\McpSchema\Server\Tools\DTO\Tool as ToolDto;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Registry for managing MCP server components (tools, resources, prompts).
|
||||
*/
|
||||
class McpComponentRegistry {
|
||||
|
||||
/**
|
||||
* MCP tools keyed by tool name.
|
||||
*
|
||||
* @var array<string, \WP\MCP\Domain\Tools\McpTool>
|
||||
*/
|
||||
private array $mcp_tools = array();
|
||||
|
||||
/**
|
||||
* MCP resources keyed by resource URI.
|
||||
*
|
||||
* @var array<string, \WP\MCP\Domain\Resources\McpResource>
|
||||
*/
|
||||
private array $mcp_resources = array();
|
||||
|
||||
/**
|
||||
* MCP prompts keyed by prompt name.
|
||||
*
|
||||
* @var array<string, \WP\MCP\Domain\Prompts\McpPrompt>
|
||||
*/
|
||||
private array $mcp_prompts = array();
|
||||
|
||||
/**
|
||||
* MCP Server instance.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
private McpServer $mcp_server;
|
||||
|
||||
/**
|
||||
* Error handler instance.
|
||||
*
|
||||
* @var \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface
|
||||
*/
|
||||
private McpErrorHandlerInterface $error_handler;
|
||||
|
||||
/**
|
||||
* Observability handler instance.
|
||||
*
|
||||
* @var \WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface
|
||||
*/
|
||||
private McpObservabilityHandlerInterface $observability_handler;
|
||||
|
||||
/**
|
||||
* Whether to record component registration.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private bool $should_record_component_registration;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP\MCP\Core\McpServer $mcp_server MCP server instance.
|
||||
* @param \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface $error_handler Error handler instance.
|
||||
* @param \WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface $observability_handler Observability handler instance.
|
||||
*/
|
||||
public function __construct(
|
||||
McpServer $mcp_server,
|
||||
McpErrorHandlerInterface $error_handler,
|
||||
McpObservabilityHandlerInterface $observability_handler
|
||||
) {
|
||||
$this->mcp_server = $mcp_server;
|
||||
$this->error_handler = $error_handler;
|
||||
$this->observability_handler = $observability_handler;
|
||||
|
||||
/**
|
||||
* Filters whether component registration events should be recorded for observability.
|
||||
*
|
||||
* Default is false to avoid polluting observability logs during startup.
|
||||
* Enable this filter to track tool, resource, and prompt registrations
|
||||
* for debugging or monitoring purposes.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param bool $should_record Whether to record component registration events. Default false.
|
||||
* @param string $server_id The server ID for which components are being registered.
|
||||
* @param \WP\MCP\Core\McpServer $server The McpServer instance owning the registry.
|
||||
*/
|
||||
$this->should_record_component_registration = apply_filters(
|
||||
'mcp_adapter_observability_record_component_registration',
|
||||
false,
|
||||
$this->mcp_server->get_server_id(),
|
||||
$this->mcp_server
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register tools to the server.
|
||||
*
|
||||
* @param list<string|\WP\MCP\Domain\Tools\McpTool> $tools Array of ability names (strings) or McpTool instances.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_tools( array $tools ): void {
|
||||
foreach ( $tools as $tool_item ) {
|
||||
$this->register_single_tool( $tool_item );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a single tool to the server.
|
||||
*
|
||||
* @param string|\WP\MCP\Domain\Tools\McpTool $tool_item The tool to register.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_single_tool( $tool_item ): void {
|
||||
// Case 0: McpTool instance.
|
||||
if ( $tool_item instanceof McpTool ) {
|
||||
$this->add_mcp_tool( $tool_item );
|
||||
|
||||
/** @var \WP\McpSchema\Server\Tools\DTO\Tool $tool_dto */
|
||||
$tool_dto = $tool_item->get_protocol_dto();
|
||||
$this->track_registration( 'tool', $tool_dto->getName(), 'success' );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 1: String - treat as ability name.
|
||||
if ( is_string( $tool_item ) ) {
|
||||
$this->register_ability_tool( $tool_item );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->error_handler->log(
|
||||
sprintf(
|
||||
'Invalid tool registration item: expected McpTool instance or string ability name, got %s.',
|
||||
is_object( $tool_item ) ? get_class( $tool_item ) : gettype( $tool_item )
|
||||
),
|
||||
array( 'McpComponentRegistry::register_single_tool' ),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an McpTool directly.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Tools\McpTool $mcp_tool McpTool instance.
|
||||
*
|
||||
* @return void
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
private function add_mcp_tool( McpTool $mcp_tool ): void {
|
||||
/** @var \WP\McpSchema\Server\Tools\DTO\Tool $tool_dto */
|
||||
$tool_dto = $mcp_tool->get_protocol_dto();
|
||||
$tool_name = $tool_dto->getName();
|
||||
|
||||
if ( isset( $this->mcp_tools[ $tool_name ] ) ) {
|
||||
$this->error_handler->log(
|
||||
"Tool with name '{$tool_name}' already registered, skipping duplicate.",
|
||||
array( 'McpComponentRegistry::add_mcp_tool' ),
|
||||
'warning'
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->mcp_tools[ $tool_name ] = $mcp_tool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a component registration event.
|
||||
*
|
||||
* @param string $type Component type.
|
||||
* @param string $name Component name.
|
||||
* @param string $status Registration status ('success' or 'failed').
|
||||
* @param array<string, mixed> $extra Extra event data.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function track_registration( string $type, string $name, string $status, array $extra = array() ): void {
|
||||
if ( ! $this->should_record_component_registration ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$event_data = array_merge(
|
||||
array(
|
||||
'status' => $status,
|
||||
'component_type' => $type,
|
||||
'component_name' => $name,
|
||||
'server_id' => $this->mcp_server->get_server_id(),
|
||||
),
|
||||
$extra
|
||||
);
|
||||
|
||||
$this->observability_handler->record_event( 'mcp.component.registration', $event_data );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a tool from an ability name.
|
||||
*
|
||||
* @param string $ability_name Ability name.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_ability_tool( string $ability_name ): void {
|
||||
$ability = \wp_get_ability( $ability_name );
|
||||
|
||||
if ( ! $ability ) {
|
||||
$this->error_handler->log( "WordPress ability '{$ability_name}' does not exist.", array( "RegisterAbilityAsMcpTool::{$ability_name}" ) );
|
||||
$this->track_registration( 'ability_tool', $ability_name, 'failed', array( 'failure_reason' => FailureReason::ABILITY_NOT_FOUND ) );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$mcp_tool = McpTool::fromAbility( $ability );
|
||||
|
||||
if ( is_wp_error( $mcp_tool ) ) {
|
||||
$this->error_handler->log( $mcp_tool->get_error_message(), array( "McpTool::fromAbility::{$ability_name}" ) );
|
||||
$this->track_registration(
|
||||
'ability_tool',
|
||||
$ability_name,
|
||||
'failed',
|
||||
array( 'error_code' => $mcp_tool->get_error_code() )
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add_mcp_tool( $mcp_tool );
|
||||
$this->track_registration( 'ability_tool', $ability_name, 'success' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register resources to the server.
|
||||
*
|
||||
* @param list<string|\WP\MCP\Domain\Resources\McpResource> $resources Array of ability names or McpResource instances.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_resources( array $resources ): void {
|
||||
foreach ( $resources as $resource_item ) {
|
||||
$this->register_single_resource( $resource_item );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a single resource to the server.
|
||||
*
|
||||
* @param string|\WP\MCP\Domain\Resources\McpResource $resource_item The resource to register.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_single_resource( $resource_item ): void {
|
||||
// Case 0: McpResource instance.
|
||||
if ( $resource_item instanceof McpResource ) {
|
||||
$this->add_mcp_resource( $resource_item );
|
||||
|
||||
/** @var \WP\McpSchema\Server\Resources\DTO\Resource $resource_dto */
|
||||
$resource_dto = $resource_item->get_protocol_dto();
|
||||
$this->track_registration( 'resource', $resource_dto->getUri(), 'success' );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 1: String - treat as ability name.
|
||||
if ( is_string( $resource_item ) ) {
|
||||
$this->register_ability_resource( $resource_item );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 2: Invalid type.
|
||||
$this->error_handler->log(
|
||||
sprintf(
|
||||
'Invalid resource registration item: expected McpResource instance or string ability name, got %s.',
|
||||
is_object( $resource_item ) ? get_class( $resource_item ) : gettype( $resource_item )
|
||||
),
|
||||
array( 'McpComponentRegistry::register_single_resource' ),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an McpResource directly.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Resources\McpResource $mcp_resource McpResource instance.
|
||||
*
|
||||
* @return bool True if the resource was added, false if it was a duplicate.
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
private function add_mcp_resource( McpResource $mcp_resource ): bool {
|
||||
/** @var \WP\McpSchema\Server\Resources\DTO\Resource $resource_dto */
|
||||
$resource_dto = $mcp_resource->get_protocol_dto();
|
||||
$uri = $resource_dto->getUri();
|
||||
|
||||
if ( isset( $this->mcp_resources[ $uri ] ) ) {
|
||||
$this->error_handler->log(
|
||||
"Resource with URI '{$uri}' already registered, skipping duplicate.",
|
||||
array( 'McpComponentRegistry::add_mcp_resource' ),
|
||||
'warning'
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->mcp_resources[ $uri ] = $mcp_resource;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an ability-backed resource by ability name.
|
||||
*
|
||||
* @param string $ability_name Ability name.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_ability_resource( string $ability_name ): void {
|
||||
$ability = \wp_get_ability( $ability_name );
|
||||
|
||||
if ( ! $ability ) {
|
||||
$this->error_handler->log( "WordPress ability '{$ability_name}' does not exist.", array( "RegisterAbilityAsMcpResource::{$ability_name}" ) );
|
||||
|
||||
$this->track_registration( 'resource', $ability_name, 'failed', array( 'failure_reason' => FailureReason::ABILITY_NOT_FOUND ) );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$mcp_resource = McpResource::fromAbility( $ability, $this->error_handler );
|
||||
|
||||
// Check if resource creation returned an error.
|
||||
if ( is_wp_error( $mcp_resource ) ) {
|
||||
$this->error_handler->log( $mcp_resource->get_error_message(), array( "McpResource::fromAbility::{$ability_name}" ) );
|
||||
|
||||
$this->track_registration(
|
||||
'resource',
|
||||
$ability_name,
|
||||
'failed',
|
||||
array( 'error_code' => $mcp_resource->get_error_code() )
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$added = $this->add_mcp_resource( $mcp_resource );
|
||||
|
||||
if ( $added ) {
|
||||
$this->track_registration( 'resource', $ability_name, 'success' );
|
||||
} else {
|
||||
/** @var \WP\McpSchema\Server\Resources\DTO\Resource $resource_dto */
|
||||
$resource_dto = $mcp_resource->get_protocol_dto();
|
||||
$this->track_registration(
|
||||
'resource',
|
||||
$ability_name,
|
||||
'failed',
|
||||
array(
|
||||
'failure_reason' => FailureReason::DUPLICATE_URI,
|
||||
'duplicate_uri' => $resource_dto->getUri(),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register prompts to the server.
|
||||
*
|
||||
* Accepts multiple formats:
|
||||
* - McpPrompt instances
|
||||
* - Class name string implementing McpPromptBuilderInterface (instantiated automatically)
|
||||
* - Ability name string (converted via RegisterAbilityAsMcpPrompt)
|
||||
* - McpPromptBuilderInterface instance (fluent API or custom builders)
|
||||
* - Array configuration (converted via McpPrompt::fromArray())
|
||||
*
|
||||
* @param list<string|\WP\MCP\Domain\Prompts\McpPrompt|\WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface> $prompts Array of prompts to register.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_prompts( array $prompts ): void {
|
||||
foreach ( $prompts as $prompt_item ) {
|
||||
$this->register_single_prompt( $prompt_item );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a single prompt to the server.
|
||||
*
|
||||
* @param string|\WP\MCP\Domain\Prompts\McpPrompt|\WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface $prompt_item The prompt to register.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_single_prompt( $prompt_item ): void {
|
||||
// Case 0: McpPrompt instance.
|
||||
if ( $prompt_item instanceof McpPrompt ) {
|
||||
$this->add_mcp_prompt( $prompt_item );
|
||||
|
||||
/** @var \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt_dto */
|
||||
$prompt_dto = $prompt_item->get_protocol_dto();
|
||||
$this->track_registration( 'prompt', $prompt_dto->getName(), 'success' );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 1: McpPromptBuilderInterface instance (fluent API or custom builder).
|
||||
if ( $prompt_item instanceof McpPromptBuilderInterface ) {
|
||||
$this->register_builder_instance( $prompt_item );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 2: String - either a class name or ability name.
|
||||
if ( is_string( $prompt_item ) ) {
|
||||
// Check if it's a class that implements McpPromptBuilderInterface.
|
||||
if ( class_exists( $prompt_item ) && in_array( McpPromptBuilderInterface::class, class_implements( $prompt_item ) ?: array(), true ) ) {
|
||||
$this->register_builder_class( $prompt_item );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Treat as ability name.
|
||||
$this->register_ability_prompt( $prompt_item );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 3: Invalid type.
|
||||
$this->error_handler->log(
|
||||
sprintf(
|
||||
'Invalid prompt registration item: expected McpPrompt, McpPromptBuilderInterface, or string, got %s.',
|
||||
is_object( $prompt_item ) ? get_class( $prompt_item ) : gettype( $prompt_item )
|
||||
),
|
||||
array( 'McpComponentRegistry::register_single_prompt' ),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an McpPrompt to the registry.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Prompts\McpPrompt $mcp_prompt McpPrompt instance.
|
||||
*
|
||||
* @return void
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
private function add_mcp_prompt( McpPrompt $mcp_prompt ): void {
|
||||
/** @var \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt */
|
||||
$prompt = $mcp_prompt->get_protocol_dto();
|
||||
$prompt_name = $prompt->getName();
|
||||
|
||||
if ( isset( $this->mcp_prompts[ $prompt_name ] ) ) {
|
||||
$this->error_handler->log(
|
||||
"Prompt with name '{$prompt_name}' already registered, skipping duplicate.",
|
||||
array( 'McpComponentRegistry::add_mcp_prompt' ),
|
||||
'warning'
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->mcp_prompts[ $prompt_name ] = $mcp_prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a McpPromptBuilderInterface instance.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface $builder The builder instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_builder_instance( McpPromptBuilderInterface $builder ): void {
|
||||
$prompt_name = $builder->get_name();
|
||||
|
||||
$mcp_prompt = McpPrompt::fromBuilder( $builder );
|
||||
if ( $mcp_prompt instanceof WP_Error ) {
|
||||
$this->error_handler->log( $mcp_prompt->get_error_message(), array( "McpPrompt::fromBuilder::{$prompt_name}" ) );
|
||||
|
||||
$this->track_registration(
|
||||
'prompt',
|
||||
$prompt_name,
|
||||
'failed',
|
||||
array( 'error_code' => $mcp_prompt->get_error_code() )
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add_mcp_prompt( $mcp_prompt );
|
||||
|
||||
$this->track_registration( 'prompt', $prompt_name, 'success' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a prompt from a builder class name.
|
||||
*
|
||||
* @param string $class_name The fully-qualified class name.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_builder_class( string $class_name ): void {
|
||||
try {
|
||||
/** @var \WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface $builder */
|
||||
$builder = new $class_name();
|
||||
$this->register_builder_instance( $builder );
|
||||
} catch ( \Throwable $e ) {
|
||||
$this->error_handler->log( "Failed to build prompt from class '{$class_name}': {$e->getMessage()}", array( "McpPromptBuilder::{$class_name}" ) );
|
||||
|
||||
$this->track_registration( 'prompt', $class_name, 'failed', array( 'failure_reason' => FailureReason::BUILDER_EXCEPTION ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a prompt from an ability name.
|
||||
*
|
||||
* @param string $ability_name The ability name.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function register_ability_prompt( string $ability_name ): void {
|
||||
$ability = \wp_get_ability( $ability_name );
|
||||
|
||||
if ( ! $ability ) {
|
||||
$this->error_handler->log( "WordPress ability '{$ability_name}' does not exist.", array( "RegisterAbilityAsMcpPrompt::{$ability_name}" ) );
|
||||
|
||||
$this->track_registration( 'prompt', $ability_name, 'failed', array( 'failure_reason' => FailureReason::ABILITY_NOT_FOUND ) );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$mcp_prompt = McpPrompt::fromAbility( $ability );
|
||||
|
||||
if ( is_wp_error( $mcp_prompt ) ) {
|
||||
$this->error_handler->log( $mcp_prompt->get_error_message(), array( "McpPrompt::fromAbility::{$ability_name}" ) );
|
||||
|
||||
$this->track_registration(
|
||||
'prompt',
|
||||
$ability_name,
|
||||
'failed',
|
||||
array( 'error_code' => $mcp_prompt->get_error_code() )
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->add_mcp_prompt( $mcp_prompt );
|
||||
|
||||
$this->track_registration( 'prompt', $ability_name, 'success' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all tools registered to the server.
|
||||
*
|
||||
* @return array<string, \WP\McpSchema\Server\Tools\DTO\Tool>
|
||||
*/
|
||||
public function get_tools(): array {
|
||||
return array_map(
|
||||
static fn( McpTool $mcp_tool ): ToolDto => $mcp_tool->get_protocol_dto(),
|
||||
$this->mcp_tools
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all resources registered to the server.
|
||||
*
|
||||
* @return array<string, \WP\McpSchema\Server\Resources\DTO\Resource>
|
||||
*/
|
||||
public function get_resources(): array {
|
||||
return array_map(
|
||||
static fn( McpResource $mcp_resource ): ResourceDto => $mcp_resource->get_protocol_dto(),
|
||||
$this->mcp_resources
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all prompts registered to the server.
|
||||
*
|
||||
* @return array<string, \WP\McpSchema\Server\Prompts\DTO\Prompt>
|
||||
*/
|
||||
public function get_prompts(): array {
|
||||
return array_map(
|
||||
static fn( McpPrompt $mcp_prompt ): PromptDto => $mcp_prompt->get_protocol_dto(),
|
||||
$this->mcp_prompts
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific McpTool by tool name.
|
||||
*
|
||||
* @param string $tool_name Tool name.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Tools\McpTool|null
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
public function get_mcp_tool( string $tool_name ): ?McpTool {
|
||||
return $this->mcp_tools[ $tool_name ] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific McpResource by URI.
|
||||
*
|
||||
* @param string $resource_uri Resource URI.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Resources\McpResource|null
|
||||
* @internal
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
public function get_mcp_resource( string $resource_uri ): ?McpResource {
|
||||
return $this->mcp_resources[ $resource_uri ] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an McpPrompt by prompt name.
|
||||
*
|
||||
* @param string $prompt_name Prompt name.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Prompts\McpPrompt|null
|
||||
* @internal
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
public function get_mcp_prompt( string $prompt_name ): ?McpPrompt {
|
||||
return $this->mcp_prompts[ $prompt_name ] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a prompt builder instance by prompt name (builder-based prompts).
|
||||
*
|
||||
* @param string $prompt_name Prompt name.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface|null
|
||||
*/
|
||||
public function get_prompt_builder( string $prompt_name ): ?McpPromptBuilderInterface {
|
||||
$mcp_prompt = $this->mcp_prompts[ $prompt_name ] ?? null;
|
||||
|
||||
return $mcp_prompt ? $mcp_prompt->get_builder() : null;
|
||||
}
|
||||
}
|
||||
Vendored
+448
@@ -0,0 +1,448 @@
|
||||
<?php
|
||||
/**
|
||||
* WordPress MCP Server class for managing server-specific tools, resources, and prompts.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Core;
|
||||
|
||||
use WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface;
|
||||
use WP\MCP\Domain\Prompts\McpPrompt;
|
||||
use WP\MCP\Domain\Resources\McpResource;
|
||||
use WP\MCP\Domain\Tools\McpTool;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\NullMcpErrorHandler;
|
||||
use WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\NullMcpObservabilityHandler;
|
||||
use WP\MCP\Transport\Infrastructure\McpTransportContext;
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt as PromptDto;
|
||||
|
||||
/**
|
||||
* WordPress MCP Server - Represents a single MCP server with its tools, resources, and prompts.
|
||||
*/
|
||||
class McpServer {
|
||||
/**
|
||||
* Error handler instance.
|
||||
*
|
||||
* @var \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface
|
||||
*/
|
||||
public McpErrorHandlerInterface $error_handler;
|
||||
|
||||
/**
|
||||
* Observability handler instance.
|
||||
*
|
||||
* @var \WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface
|
||||
*/
|
||||
public McpObservabilityHandlerInterface $observability_handler;
|
||||
|
||||
/**
|
||||
* Server ID.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $server_id;
|
||||
|
||||
/**
|
||||
* Server URL.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $server_route_namespace;
|
||||
|
||||
/**
|
||||
* Server route.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $server_route;
|
||||
|
||||
/**
|
||||
* Server name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $server_name;
|
||||
|
||||
/**
|
||||
* Server description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $server_description;
|
||||
|
||||
/**
|
||||
* Server version.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private string $server_version;
|
||||
|
||||
/**
|
||||
* Component registry for managing tools, resources, and prompts.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpComponentRegistry
|
||||
*/
|
||||
private McpComponentRegistry $component_registry;
|
||||
|
||||
/**
|
||||
* Transport factory for initializing transports.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpTransportFactory
|
||||
*/
|
||||
private McpTransportFactory $transport_factory;
|
||||
|
||||
/**
|
||||
* Whether MCP validation is enabled.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private bool $mcp_validation_enabled;
|
||||
|
||||
/**
|
||||
* Transport permission callback.
|
||||
*
|
||||
* @var callable|null
|
||||
*/
|
||||
private $transport_permission_callback;
|
||||
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string $server_id Unique identifier for the server.
|
||||
* @param string $server_route_namespace Server route namespace.
|
||||
* @param string $server_route Server route.
|
||||
* @param string $server_name Human-readable server name.
|
||||
* @param string $server_description Server description.
|
||||
* @param string $server_version Server version.
|
||||
* @param array<class-string<\WP\MCP\Transport\Contracts\McpTransportInterface>> $mcp_transports Array of MCP transport class names to initialize (e.g., [McpRestTransport::class]).
|
||||
* @param class-string<\WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface>|null $error_handler Error handler class to use (e.g., NullMcpErrorHandler::class). Must implement McpErrorHandlerInterface. If null, NullMcpErrorHandler will be used.
|
||||
* @param class-string<\WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface>|null $observability_handler Observability handler class to use (e.g., NullMcpObservabilityHandler::class). Must implement McpObservabilityHandlerInterface. If null, NullMcpObservabilityHandler will be used.
|
||||
* @param list<string> $tools Optional ability names to register as tools during construction.
|
||||
* @param list<string> $resources Optional resources to register during construction.
|
||||
* @param list<string> $prompts Optional prompts to register during construction.
|
||||
* @param callable|null $transport_permission_callback Optional custom permission callback for transport-level authentication. If null, defaults to is_user_logged_in().
|
||||
*
|
||||
* @throws \Exception Thrown if the MCP transport class does not extend AbstractMcpTransport.
|
||||
*/
|
||||
public function __construct(
|
||||
string $server_id,
|
||||
string $server_route_namespace,
|
||||
string $server_route,
|
||||
string $server_name,
|
||||
string $server_description,
|
||||
string $server_version,
|
||||
array $mcp_transports,
|
||||
?string $error_handler,
|
||||
?string $observability_handler,
|
||||
array $tools = array(),
|
||||
array $resources = array(),
|
||||
array $prompts = array(),
|
||||
?callable $transport_permission_callback = null
|
||||
) {
|
||||
// Store server configuration
|
||||
$this->server_id = $server_id;
|
||||
$this->server_route_namespace = $server_route_namespace;
|
||||
$this->server_route = $server_route;
|
||||
$this->server_name = $server_name;
|
||||
$this->server_description = $server_description;
|
||||
$this->server_version = $server_version;
|
||||
$this->transport_permission_callback = $transport_permission_callback;
|
||||
|
||||
/**
|
||||
* Filters whether MCP protocol validation is enabled for a server.
|
||||
*
|
||||
* Validation is disabled by default for performance, as the Abilities API
|
||||
* also validates all abilities. Enable this filter for stricter MCP protocol
|
||||
* compliance checking during development or debugging.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param bool $enabled Whether validation is enabled. Default false.
|
||||
* @param string $server_id The server ID being configured.
|
||||
* @param \WP\MCP\Core\McpServer $server The McpServer instance being constructed.
|
||||
*/
|
||||
$this->mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false, $this->server_id, $this );
|
||||
|
||||
// Setup handlers and components
|
||||
$this->setup_handlers( $error_handler, $observability_handler );
|
||||
$this->setup_components( $tools, $resources, $prompts, $mcp_transports );
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup error and observability handlers.
|
||||
*
|
||||
* @param string|null $error_handler Error handler class name.
|
||||
* @param string|null $observability_handler Observability handler class name.
|
||||
*/
|
||||
private function setup_handlers( ?string $error_handler, ?string $observability_handler ): void {
|
||||
// Instantiate error handler
|
||||
if ( $error_handler && class_exists( $error_handler ) ) {
|
||||
/** @var \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface $handler */
|
||||
$handler = new $error_handler();
|
||||
$this->error_handler = $handler;
|
||||
} else {
|
||||
$this->error_handler = new NullMcpErrorHandler();
|
||||
}
|
||||
|
||||
// Instantiate observability handler
|
||||
if ( $observability_handler && class_exists( $observability_handler ) ) {
|
||||
/** @var \WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface $handler */
|
||||
$handler = new $observability_handler();
|
||||
$this->observability_handler = $handler;
|
||||
} else {
|
||||
$this->observability_handler = new NullMcpObservabilityHandler();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup component registry and transport factory.
|
||||
*
|
||||
* @param list<string> $tools Tools to register.
|
||||
* @param list<string> $resources Resources to register.
|
||||
* @param list<string> $prompts Prompts to register.
|
||||
* @param array<class-string<\WP\MCP\Transport\Contracts\McpTransportInterface>> $mcp_transports Transport classes to initialize.
|
||||
*
|
||||
* @throws \Exception
|
||||
*/
|
||||
private function setup_components( array $tools, array $resources, array $prompts, array $mcp_transports ): void {
|
||||
// Initialize component registry
|
||||
$this->component_registry = new McpComponentRegistry(
|
||||
$this,
|
||||
$this->error_handler,
|
||||
$this->observability_handler
|
||||
);
|
||||
|
||||
// Initialize transport factory
|
||||
$this->transport_factory = new McpTransportFactory( $this );
|
||||
|
||||
// Register tools, resources, and prompts
|
||||
$this->register_mcp_components( $tools, $resources, $prompts );
|
||||
|
||||
// Initialize transports
|
||||
$this->transport_factory->initialize_transports( $mcp_transports );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register initial tools, resources, and prompts.
|
||||
*
|
||||
* @param list<string> $tools Tools to register.
|
||||
* @param list<string> $resources Resources to register.
|
||||
* @param list<string> $prompts Prompts to register.
|
||||
*/
|
||||
private function register_mcp_components( array $tools, array $resources, array $prompts ): void {
|
||||
// Register tools if provided
|
||||
if ( ! empty( $tools ) ) {
|
||||
$this->component_registry->register_tools( $tools );
|
||||
}
|
||||
|
||||
// Register resources if provided
|
||||
if ( ! empty( $resources ) ) {
|
||||
$this->component_registry->register_resources( $resources );
|
||||
}
|
||||
|
||||
// Register prompts if provided
|
||||
if ( empty( $prompts ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->component_registry->register_prompts( $prompts );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server ID.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_server_id(): string {
|
||||
return $this->server_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server route namespace.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_server_route_namespace(): string {
|
||||
return $this->server_route_namespace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server route.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_server_route(): string {
|
||||
return $this->server_route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the server name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_server_name(): string {
|
||||
return $this->server_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server description.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_server_description(): string {
|
||||
return $this->server_description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server version.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_server_version(): string {
|
||||
return $this->server_version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the transport permission callback.
|
||||
*
|
||||
* @return callable|null
|
||||
*/
|
||||
public function get_transport_permission_callback(): ?callable {
|
||||
return $this->transport_permission_callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the observability handler instance.
|
||||
*
|
||||
* @return \WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface
|
||||
*/
|
||||
public function get_observability_handler(): McpObservabilityHandlerInterface {
|
||||
return $this->observability_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error handler instance.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @return \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface
|
||||
*/
|
||||
public function get_error_handler(): McpErrorHandlerInterface {
|
||||
return $this->error_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all tools registered to this server.
|
||||
*
|
||||
* @return array<string, \WP\McpSchema\Server\Tools\DTO\Tool>
|
||||
*/
|
||||
public function get_tools(): array {
|
||||
return $this->component_registry->get_tools();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all resources registered to this server.
|
||||
*
|
||||
* @return array<string, \WP\McpSchema\Server\Resources\DTO\Resource>
|
||||
*/
|
||||
public function get_resources(): array {
|
||||
return $this->component_registry->get_resources();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all prompts registered to this server.
|
||||
*
|
||||
* @return array<string, \WP\McpSchema\Server\Prompts\DTO\Prompt>
|
||||
*/
|
||||
public function get_prompts(): array {
|
||||
return $this->component_registry->get_prompts();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific McpTool by name.
|
||||
*
|
||||
* @param string $tool_name Tool name.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Tools\McpTool|null
|
||||
* @internal
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
public function get_mcp_tool( string $tool_name ): ?McpTool {
|
||||
return $this->component_registry->get_mcp_tool( $tool_name );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific McpResource by URI.
|
||||
*
|
||||
* @param string $resource_uri Resource URI.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Resources\McpResource|null
|
||||
* @internal
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
public function get_mcp_resource( string $resource_uri ): ?McpResource {
|
||||
return $this->component_registry->get_mcp_resource( $resource_uri );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific prompt by name.
|
||||
*
|
||||
* @param string $prompt_name Prompt name.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\Prompt|null
|
||||
*/
|
||||
public function get_prompt( string $prompt_name ): ?PromptDto {
|
||||
$mcp_prompt = $this->component_registry->get_mcp_prompt( $prompt_name );
|
||||
|
||||
return $mcp_prompt ? $mcp_prompt->get_protocol_dto() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an McpPrompt by name.
|
||||
*
|
||||
* @param string $prompt_name Prompt name.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Prompts\McpPrompt|null
|
||||
* @internal
|
||||
* @since 0.3.0
|
||||
*
|
||||
*/
|
||||
public function get_mcp_prompt( string $prompt_name ): ?McpPrompt {
|
||||
return $this->component_registry->get_mcp_prompt( $prompt_name );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a prompt builder instance by prompt name (builder-based prompts).
|
||||
*
|
||||
* @param string $prompt_name Prompt name.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface|null
|
||||
*/
|
||||
public function get_prompt_builder( string $prompt_name ): ?McpPromptBuilderInterface {
|
||||
return $this->component_registry->get_prompt_builder( $prompt_name );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create transport context with all required dependencies.
|
||||
*
|
||||
* @return \WP\MCP\Transport\Infrastructure\McpTransportContext
|
||||
*/
|
||||
public function create_transport_context(): McpTransportContext {
|
||||
return $this->transport_factory->create_transport_context();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if MCP validation is enabled.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function is_mcp_validation_enabled(): bool {
|
||||
return $this->mcp_validation_enabled;
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Transport Factory for initializing MCP transports.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Core;
|
||||
|
||||
use WP\MCP\Handlers\Initialize\InitializeHandler;
|
||||
use WP\MCP\Handlers\Prompts\PromptsHandler;
|
||||
use WP\MCP\Handlers\Resources\ResourcesHandler;
|
||||
use WP\MCP\Handlers\System\SystemHandler;
|
||||
use WP\MCP\Handlers\Tools\ToolsHandler;
|
||||
use WP\MCP\Transport\Contracts\McpTransportInterface;
|
||||
use WP\MCP\Transport\Infrastructure\McpTransportContext;
|
||||
|
||||
/**
|
||||
* Factory for creating and initializing MCP transports.
|
||||
*/
|
||||
class McpTransportFactory {
|
||||
/**
|
||||
* MCP Server instance.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
private McpServer $mcp_server;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP\MCP\Core\McpServer $mcp_server MCP server instance.
|
||||
*/
|
||||
public function __construct( McpServer $mcp_server ) {
|
||||
$this->mcp_server = $mcp_server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize MCP transports for the server.
|
||||
*
|
||||
* @param array<class-string<\WP\MCP\Transport\Contracts\McpTransportInterface>> $mcp_transports Array of MCP transport class names to initialize.
|
||||
*/
|
||||
public function initialize_transports( array $mcp_transports ): void {
|
||||
foreach ( $mcp_transports as $mcp_transport ) {
|
||||
// Check if the class exists
|
||||
if ( ! class_exists( $mcp_transport ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
sprintf(
|
||||
/* translators: %s: Transport class name */
|
||||
esc_html__( 'Transport class "%s" does not exist. Make sure the class is properly autoloaded or included.', 'mcp-adapter' ),
|
||||
esc_html( $mcp_transport )
|
||||
),
|
||||
'0.1.0'
|
||||
);
|
||||
// Log error and continue processing other transports
|
||||
$this->mcp_server->get_error_handler()->log(
|
||||
sprintf( 'Transport class "%s" does not exist.', $mcp_transport ),
|
||||
array( 'McpTransportFactory::initialize_transports' )
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for interface implementation
|
||||
if ( ! in_array( McpTransportInterface::class, class_implements( $mcp_transport ) ?: array(), true ) ) {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
sprintf(
|
||||
/* translators: %s: Transport class name */
|
||||
esc_html__( 'Transport class "%s" must implement McpTransportInterface. Check your transport implementation.', 'mcp-adapter' ),
|
||||
esc_html( $mcp_transport )
|
||||
),
|
||||
'0.1.0'
|
||||
);
|
||||
// Log error and continue processing other transports
|
||||
$this->mcp_server->get_error_handler()->log(
|
||||
sprintf( 'MCP transport class "%s" must implement the McpTransportInterface.', $mcp_transport ),
|
||||
array( 'McpTransportFactory::initialize_transports' )
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Interface-based instantiation with dependency injection
|
||||
$context = $this->create_transport_context();
|
||||
new $mcp_transport( $context );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the transport context with all required dependencies.
|
||||
*
|
||||
* @return \WP\MCP\Transport\Infrastructure\McpTransportContext
|
||||
*/
|
||||
public function create_transport_context(): McpTransportContext {
|
||||
// Create handlers
|
||||
$initialize_handler = new InitializeHandler( $this->mcp_server );
|
||||
$tools_handler = new ToolsHandler( $this->mcp_server );
|
||||
$resources_handler = new ResourcesHandler( $this->mcp_server );
|
||||
$prompts_handler = new PromptsHandler( $this->mcp_server );
|
||||
$system_handler = new SystemHandler();
|
||||
|
||||
// Create the context - the router will be created automatically
|
||||
return new McpTransportContext(
|
||||
array(
|
||||
'mcp_server' => $this->mcp_server,
|
||||
'initialize_handler' => $initialize_handler,
|
||||
'tools_handler' => $tools_handler,
|
||||
'resources_handler' => $resources_handler,
|
||||
'prompts_handler' => $prompts_handler,
|
||||
'system_handler' => $system_handler,
|
||||
'observability_handler' => $this->mcp_server->get_observability_handler(),
|
||||
'error_handler' => $this->mcp_server->get_error_handler(),
|
||||
'transport_permission_callback' => $this->mcp_server->get_transport_permission_callback(),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP protocol version negotiation.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Core;
|
||||
|
||||
/**
|
||||
* Negotiates the MCP protocol version between client and server.
|
||||
*
|
||||
* If the client requests a supported version, the server echoes it back.
|
||||
* Otherwise the server falls back to the latest supported version.
|
||||
*
|
||||
* This is a Core layer class — no WordPress function calls.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
final class McpVersionNegotiator {
|
||||
|
||||
/**
|
||||
* Protocol versions supported by this server, ordered newest-first.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
// phpcs:ignore SlevomatCodingStandard.Classes.DisallowMultiConstantDefinition -- False positive: sniff mistakes array() commas for multi-const commas (only handles short syntax).
|
||||
public const SUPPORTED_PROTOCOL_VERSIONS = array(
|
||||
'2025-11-25',
|
||||
'2025-06-18',
|
||||
'2024-11-05',
|
||||
);
|
||||
|
||||
/**
|
||||
* Negotiate the protocol version to use for a session.
|
||||
*
|
||||
* If the client-requested version is in the supported list it is echoed
|
||||
* back verbatim. Otherwise the latest supported version is returned.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $client_version The protocol version requested by the client.
|
||||
*
|
||||
* @return string The negotiated protocol version.
|
||||
*/
|
||||
public static function negotiate( string $client_version ): string {
|
||||
if ( in_array( $client_version, self::SUPPORTED_PROTOCOL_VERSIONS, true ) ) {
|
||||
return $client_version;
|
||||
}
|
||||
|
||||
return self::SUPPORTED_PROTOCOL_VERSIONS[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a given version string is supported.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $version The protocol version to check.
|
||||
*
|
||||
* @return bool True when the version is in the supported list, false otherwise.
|
||||
*/
|
||||
public static function is_supported( string $version ): bool {
|
||||
return in_array( $version, self::SUPPORTED_PROTOCOL_VERSIONS, true );
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
/**
|
||||
* Contract for MCP component classes (tools, resources, prompts).
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Contracts;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
|
||||
/**
|
||||
* Interface McpComponentInterface.
|
||||
*
|
||||
* Classes implementing this interface encapsulate:
|
||||
* - a clean protocol DTO (Tool/Resource/Prompt) that is safe to expose to MCP clients, and
|
||||
* - MCP Adapter internal metadata and execution wiring (ability-backed OR direct-callable).
|
||||
*
|
||||
* This keeps protocol DTOs free of internal adapter fields, while still
|
||||
* providing a uniform execution and permission-check surface for handlers.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
interface McpComponentInterface {
|
||||
|
||||
/**
|
||||
* Get the clean protocol DTO for MCP responses.
|
||||
*
|
||||
* This DTO is used only for protocol serialization and MUST NOT include
|
||||
* internal adapter metadata or execution wiring.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\AbstractDataTransferObject Protocol-only DTO.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public function get_protocol_dto(): AbstractDataTransferObject;
|
||||
|
||||
/**
|
||||
* Execute the component using the configured strategy.
|
||||
*
|
||||
* Implementations MUST execute via either:
|
||||
* - an attached WordPress ability, or
|
||||
* - a direct callable handler (for non-ability registrations).
|
||||
*
|
||||
* @param mixed $arguments Component arguments (typically an associative array).
|
||||
*
|
||||
* @return mixed Execution result.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public function execute( $arguments );
|
||||
|
||||
/**
|
||||
* Check whether execution is permitted for the current request.
|
||||
*
|
||||
* Implementations MUST check permissions via either:
|
||||
* - the attached WordPress ability, or
|
||||
* - a direct permission callback (for non-ability registrations).
|
||||
*
|
||||
* @param mixed $arguments Component arguments (typically an associative array).
|
||||
*
|
||||
* @return bool|\WP_Error True when permitted, false or WP_Error otherwise.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public function check_permission( $arguments );
|
||||
|
||||
/**
|
||||
* Get MCP Adapter internal metadata for this component.
|
||||
*
|
||||
* This metadata MUST NOT be stored on protocol DTOs and MUST NOT be exposed to MCP clients.
|
||||
*
|
||||
* @return array<string, mixed> Internal metadata.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public function get_adapter_meta(): array;
|
||||
|
||||
/**
|
||||
* Get observability context tags for logging/metrics.
|
||||
*
|
||||
* This replaces legacy approaches that derived observability tags from DTO `_meta`.
|
||||
*
|
||||
* @return array<string, mixed> Observability tags (component_type, source, etc.).
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public function get_observability_context(): array;
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
/**
|
||||
* Interface for MCP Prompt Builders.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Prompts\Contracts;
|
||||
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt;
|
||||
|
||||
/**
|
||||
* Interface for building MCP prompts.
|
||||
*
|
||||
* Classes implementing this interface can be passed directly to McpServer::register_prompts()
|
||||
* instead of requiring WordPress abilities.
|
||||
*/
|
||||
interface McpPromptBuilderInterface {
|
||||
|
||||
/**
|
||||
* Build and return the Prompt DTO instance.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\Prompt The built prompt DTO.
|
||||
*/
|
||||
public function build(): Prompt;
|
||||
|
||||
/**
|
||||
* Get the unique name for this prompt.
|
||||
*
|
||||
* @return string The prompt name.
|
||||
*/
|
||||
public function get_name(): string;
|
||||
|
||||
/**
|
||||
* Get the prompt title.
|
||||
*
|
||||
* @return string|null The prompt title.
|
||||
*/
|
||||
public function get_title(): ?string;
|
||||
|
||||
/**
|
||||
* Get the prompt description.
|
||||
*
|
||||
* @return string|null The prompt description.
|
||||
*/
|
||||
public function get_description(): ?string;
|
||||
|
||||
/**
|
||||
* Get the prompt arguments.
|
||||
*
|
||||
* @return array The prompt arguments.
|
||||
*/
|
||||
public function get_arguments(): array;
|
||||
|
||||
/**
|
||||
* Handle the prompt execution when called.
|
||||
*
|
||||
* @param array $arguments The arguments passed to the prompt.
|
||||
*
|
||||
* @return array The prompt response.
|
||||
*/
|
||||
public function handle( array $arguments ): array;
|
||||
|
||||
/**
|
||||
* Check if the current user has permission to execute this prompt.
|
||||
*
|
||||
* @param array $arguments The arguments passed to the prompt.
|
||||
*
|
||||
* @return bool True if execution is allowed, false otherwise.
|
||||
*/
|
||||
public function has_permission( array $arguments ): bool;
|
||||
}
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MCP Prompt component.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Prompts;
|
||||
|
||||
use WP\MCP\Domain\Contracts\McpComponentInterface;
|
||||
use WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface;
|
||||
use WP\MCP\Domain\Utils\AbilityArgumentNormalizer;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\MCP\Infrastructure\Observability\FailureReason;
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt as PromptDto;
|
||||
use WP\McpSchema\Server\Prompts\DTO\PromptArgument;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Prompt component providing unified execution and permission checks.
|
||||
*
|
||||
* This class supports multiple ways to register prompts:
|
||||
*
|
||||
* 1. Array configuration:
|
||||
* ```php
|
||||
* $prompt = McpPrompt::fromArray([
|
||||
* 'name' => 'code-review',
|
||||
* 'title' => 'Code Review',
|
||||
* 'description' => 'Generate a comprehensive code review',
|
||||
* 'arguments' => [
|
||||
* ['name' => 'code', 'description' => 'The code to review', 'required' => true],
|
||||
* ],
|
||||
* 'handler' => fn($args) => ['messages' => [...]],
|
||||
* 'permission' => fn() => true,
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* 2. From WordPress Ability (ability-backed):
|
||||
* ```php
|
||||
* $prompt = McpPrompt::fromAbility($ability);
|
||||
* ```
|
||||
*
|
||||
* 3. From prompt builder (builder-backed compatibility):
|
||||
* ```php
|
||||
* $prompt = McpPrompt::fromBuilder($builder);
|
||||
* ```
|
||||
*
|
||||
* McpPrompt wraps a protocol-only PromptDto for MCP serialization. Internal
|
||||
* adapter metadata and execution wiring live on this class and are never
|
||||
* exposed to MCP clients. Use get_protocol_dto() for protocol responses.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
final class McpPrompt implements McpComponentInterface {
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// Runtime Properties
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Clean Prompt DTO (protocol-only).
|
||||
*
|
||||
* @var \WP\McpSchema\Server\Prompts\DTO\Prompt
|
||||
*/
|
||||
private PromptDto $prompt;
|
||||
|
||||
/**
|
||||
* Ability used for execution/permission checks (ability-backed prompts).
|
||||
*
|
||||
* @var \WP_Ability|null
|
||||
*/
|
||||
private ?\WP_Ability $ability = null;
|
||||
|
||||
/**
|
||||
* Builder instance (builder-backed prompts).
|
||||
*
|
||||
* @var \WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface|null
|
||||
*/
|
||||
private ?McpPromptBuilderInterface $builder = null;
|
||||
|
||||
/**
|
||||
* Direct execution handler (callable-backed prompts).
|
||||
*
|
||||
* @var callable|null
|
||||
*/
|
||||
private $handler = null;
|
||||
|
||||
/**
|
||||
* Direct permission callback (callable-backed prompts).
|
||||
*
|
||||
* @var callable|null
|
||||
*/
|
||||
private $permission_callback = null;
|
||||
|
||||
/**
|
||||
* Internal adapter metadata (never exposed to clients).
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $adapter_meta = array();
|
||||
|
||||
/**
|
||||
* Observability context tags for logging/metrics.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $observability_context = array();
|
||||
|
||||
// =========================================================================
|
||||
// Constructor
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Private constructor - use factory methods.
|
||||
*
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The Prompt DTO.
|
||||
*/
|
||||
private function __construct( PromptDto $prompt ) {
|
||||
$this->prompt = $prompt;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Factory Methods
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Create a prompt definition from an array configuration.
|
||||
*
|
||||
* @param array $config The prompt configuration array.
|
||||
*
|
||||
* @return self|\WP_Error
|
||||
*/
|
||||
public static function fromArray( array $config ) {
|
||||
if ( empty( $config['name'] ) ) {
|
||||
return new WP_Error( 'mcp_prompt_missing_name', 'Prompt configuration must include a "name" field.' );
|
||||
}
|
||||
|
||||
if ( ! isset( $config['handler'] ) || ! is_callable( $config['handler'] ) ) {
|
||||
return new WP_Error( 'mcp_prompt_missing_handler', 'Prompt configuration must include a callable "handler" field.' );
|
||||
}
|
||||
|
||||
// Validate and prepare icons if set.
|
||||
$valid_icons = null;
|
||||
if ( isset( $config['icons'] ) && is_array( $config['icons'] ) && ! empty( $config['icons'] ) ) {
|
||||
$icons_result = McpValidator::validate_icons_array( $config['icons'] );
|
||||
if ( ! empty( $icons_result['valid'] ) ) {
|
||||
$valid_icons = $icons_result['valid'];
|
||||
}
|
||||
}
|
||||
|
||||
$prompt_data = array(
|
||||
'name' => $config['name'],
|
||||
'description' => $config['description'] ?? null,
|
||||
);
|
||||
|
||||
if ( isset( $config['title'] ) ) {
|
||||
$prompt_data['title'] = $config['title'];
|
||||
}
|
||||
|
||||
if ( isset( $config['meta'] ) && is_array( $config['meta'] ) && ! empty( $config['meta'] ) ) {
|
||||
$prompt_data['_meta'] = $config['meta'];
|
||||
}
|
||||
|
||||
if ( null !== $valid_icons ) {
|
||||
$prompt_data['icons'] = $valid_icons;
|
||||
}
|
||||
|
||||
// Create the Prompt DTO - wrap in try-catch since PromptArgument::fromArray() and PromptDto::fromArray() can throw.
|
||||
try {
|
||||
// Process arguments inside try-catch since PromptArgument::fromArray() can throw.
|
||||
if ( isset( $config['arguments'] ) && is_array( $config['arguments'] ) && ! empty( $config['arguments'] ) ) {
|
||||
$prompt_data['arguments'] = array_map(
|
||||
static function ( array $arg ): PromptArgument {
|
||||
return PromptArgument::fromArray(
|
||||
array(
|
||||
'name' => $arg['name'],
|
||||
'title' => $arg['title'] ?? null,
|
||||
'description' => $arg['description'] ?? null,
|
||||
'required' => $arg['required'] ?? null,
|
||||
)
|
||||
);
|
||||
},
|
||||
$config['arguments']
|
||||
);
|
||||
}
|
||||
|
||||
$prompt = PromptDto::fromArray( $prompt_data );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'mcp_prompt_dto_creation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: error message */
|
||||
__( 'Failed to create Prompt DTO: %s', 'mcp-adapter' ),
|
||||
$e->getMessage()
|
||||
),
|
||||
array( 'exception' => $e )
|
||||
);
|
||||
}
|
||||
|
||||
// Optional deep validation if enabled.
|
||||
$mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false );
|
||||
if ( $mcp_validation_enabled ) {
|
||||
$validation_result = McpPromptValidator::validate_prompt_dto( $prompt );
|
||||
if ( is_wp_error( $validation_result ) ) {
|
||||
return $validation_result;
|
||||
}
|
||||
}
|
||||
|
||||
$instance = new self( $prompt );
|
||||
$instance->handler = $config['handler'];
|
||||
|
||||
if ( isset( $config['permission'] ) && is_callable( $config['permission'] ) ) {
|
||||
$instance->permission_callback = $config['permission'];
|
||||
}
|
||||
|
||||
$instance->observability_context = array(
|
||||
'component_type' => 'prompt',
|
||||
'prompt_name' => $config['name'],
|
||||
'source' => 'array',
|
||||
);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ability-backed MCP prompt.
|
||||
*
|
||||
* @param \WP_Ability $ability WordPress ability.
|
||||
*
|
||||
* @return self|\WP_Error
|
||||
*/
|
||||
public static function fromAbility( \WP_Ability $ability ) {
|
||||
$prompt_data = RegisterAbilityAsMcpPrompt::build( $ability );
|
||||
if ( $prompt_data instanceof WP_Error ) {
|
||||
return $prompt_data;
|
||||
}
|
||||
|
||||
$instance = new self( $prompt_data['prompt'] );
|
||||
$instance->adapter_meta = $prompt_data['adapter_meta'];
|
||||
$instance->ability = $ability;
|
||||
|
||||
$instance->observability_context = array(
|
||||
'component_type' => 'prompt',
|
||||
'prompt_name' => $prompt_data['prompt']->getName(),
|
||||
'ability_name' => $ability->get_name(),
|
||||
'source' => 'ability',
|
||||
);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a builder-backed MCP prompt.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface $builder Builder instance.
|
||||
*
|
||||
* @return self|\WP_Error
|
||||
*/
|
||||
public static function fromBuilder( McpPromptBuilderInterface $builder ) {
|
||||
try {
|
||||
$prompt = $builder->build();
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_prompt_builder_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
|
||||
// Optional deep validation if enabled.
|
||||
$mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false );
|
||||
if ( $mcp_validation_enabled ) {
|
||||
$validation_result = McpPromptValidator::validate_prompt_dto( $prompt );
|
||||
if ( is_wp_error( $validation_result ) ) {
|
||||
return $validation_result;
|
||||
}
|
||||
}
|
||||
|
||||
$instance = new self( $prompt );
|
||||
$instance->builder = $builder;
|
||||
|
||||
$instance->adapter_meta = array(
|
||||
'source' => 'builder',
|
||||
'builder_class' => get_class( $builder ),
|
||||
);
|
||||
|
||||
$instance->observability_context = array(
|
||||
'component_type' => 'prompt',
|
||||
'prompt_name' => $prompt->getName(),
|
||||
'source' => 'builder',
|
||||
);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// McpComponentInterface Implementation
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get the clean protocol DTO for MCP responses.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\Prompt
|
||||
*/
|
||||
public function get_protocol_dto(): PromptDto {
|
||||
return $this->prompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the prompt.
|
||||
*
|
||||
* @param mixed $arguments Prompt arguments.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function execute( $arguments ) {
|
||||
$args = $this->unwrap_input_if_needed( $arguments );
|
||||
$args = is_array( $args ) ? $args : array();
|
||||
|
||||
if ( null !== $this->ability ) {
|
||||
$args = AbilityArgumentNormalizer::normalize( $this->ability, $args );
|
||||
|
||||
try {
|
||||
$result = $this->ability->execute( $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_execution_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
} elseif ( null !== $this->builder ) {
|
||||
try {
|
||||
$result = $this->builder->handle( $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_execution_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
} elseif ( null !== $this->handler ) {
|
||||
try {
|
||||
$result = call_user_func( $this->handler, $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_execution_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
} else {
|
||||
return new WP_Error( 'mcp_prompt_no_handler', 'No prompt execution strategy configured.' );
|
||||
}
|
||||
|
||||
if ( $result instanceof WP_Error ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
if ( ! is_array( $result ) ) {
|
||||
$result = array( 'result' => $result );
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwrap prompt input arguments when the input schema was transformed (flattened → object wrapper).
|
||||
*
|
||||
* @param mixed $arguments Raw prompt arguments.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
private function unwrap_input_if_needed( $arguments ) {
|
||||
$is_transformed = true === ( $this->adapter_meta['input_schema_transformed'] ?? false );
|
||||
|
||||
if ( ! $is_transformed ) {
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$wrapper = $this->adapter_meta['input_schema_wrapper'] ?? 'input';
|
||||
$wrapper = is_string( $wrapper ) && '' !== trim( $wrapper ) ? $wrapper : 'input';
|
||||
|
||||
return is_array( $arguments ) ? ( $arguments[ $wrapper ] ?? null ) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the current request has permission to execute this prompt.
|
||||
*
|
||||
* @param mixed $arguments Prompt arguments.
|
||||
*
|
||||
* @return bool|\WP_Error
|
||||
*/
|
||||
public function check_permission( $arguments ) {
|
||||
$args = $this->unwrap_input_if_needed( $arguments );
|
||||
$args = is_array( $args ) ? $args : array();
|
||||
|
||||
if ( null !== $this->ability ) {
|
||||
$args = AbilityArgumentNormalizer::normalize( $this->ability, $args );
|
||||
|
||||
try {
|
||||
return $this->ability->check_permissions( $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_permission_check_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ( null !== $this->builder ) {
|
||||
try {
|
||||
return $this->builder->has_permission( $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_permission_check_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ( null !== $this->permission_callback ) {
|
||||
try {
|
||||
$result = call_user_func( $this->permission_callback, $args );
|
||||
|
||||
return $result instanceof WP_Error ? $result : (bool) $result;
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_permission_check_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new WP_Error(
|
||||
'mcp_permission_denied',
|
||||
'Access denied.',
|
||||
array( 'failure_reason' => FailureReason::NO_PERMISSION_STRATEGY )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get internal adapter metadata for this prompt.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function get_adapter_meta(): array {
|
||||
return $this->adapter_meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get observability context tags for logging/metrics.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function get_observability_context(): array {
|
||||
return $this->observability_context;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Private Helper Methods
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get the underlying builder instance, when builder-backed.
|
||||
*
|
||||
* @return \WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface|null
|
||||
*/
|
||||
public function get_builder(): ?McpPromptBuilderInterface {
|
||||
return $this->builder;
|
||||
}
|
||||
}
|
||||
+341
@@ -0,0 +1,341 @@
|
||||
<?php
|
||||
/**
|
||||
* Abstract base class for building MCP prompts.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Prompts;
|
||||
|
||||
use WP\MCP\Domain\Prompts\Contracts\McpPromptBuilderInterface;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt as PromptDto;
|
||||
use WP\McpSchema\Server\Prompts\DTO\PromptArgument;
|
||||
|
||||
/**
|
||||
* Abstract base class for building MCP prompts.
|
||||
*
|
||||
* @deprecated 0.5.0 Use {@see \WP\MCP\Domain\Prompts\McpPrompt} instead for creating prompts.
|
||||
*
|
||||
* The fluent API or array configuration provided by McpPrompt is simpler
|
||||
* and more flexible than subclassing this abstract class:
|
||||
*
|
||||
* ```php
|
||||
* // Fluent API (preferred)
|
||||
* $prompt = McpPrompt::create('my-prompt')
|
||||
* ->title('My Prompt')
|
||||
* ->argument('input', 'Input text', true)
|
||||
* ->handler(function(array $args): array {
|
||||
* return ['messages' => [...]];
|
||||
* });
|
||||
*
|
||||
* // Array configuration (WordPress-style)
|
||||
* $prompt = McpPrompt::fromArray([
|
||||
* 'name' => 'my-prompt',
|
||||
* 'title' => 'My Prompt',
|
||||
* 'arguments' => [['name' => 'input', 'description' => 'Input text', 'required' => true]],
|
||||
* 'handler' => function(array $args): array { return [...]; },
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* This class remains functional for backward compatibility but will be
|
||||
* removed in a future major version.
|
||||
*
|
||||
* @see McpPrompt For the preferred prompt creation API.
|
||||
*/
|
||||
abstract class McpPromptBuilder implements McpPromptBuilderInterface {
|
||||
|
||||
/**
|
||||
* The prompt name (unique identifier).
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $name = '';
|
||||
|
||||
/**
|
||||
* The prompt title (human-readable display name).
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title = null;
|
||||
|
||||
/**
|
||||
* The prompt description.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description = null;
|
||||
|
||||
/**
|
||||
* The prompt arguments.
|
||||
*
|
||||
* @var list<array{name: string, title?: string, description?: string, required?: bool}>
|
||||
*/
|
||||
protected array $arguments = array();
|
||||
|
||||
/**
|
||||
* The prompt icons for UI display.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var list<array{src: string, mimeType?: string, sizes?: array<string>, theme?: string}>|null
|
||||
*/
|
||||
protected ?array $icons = null;
|
||||
|
||||
/**
|
||||
* Additional metadata passed through to MCP clients.
|
||||
*
|
||||
* Use this to attach purpose-specific metadata that MCP clients can consume.
|
||||
* Keys are passed through unchanged.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected array $meta = array();
|
||||
|
||||
/**
|
||||
* Constructor - automatically configures the prompt.
|
||||
*
|
||||
* Configuration happens exactly once during construction, ensuring
|
||||
* idempotent behavior. Subclasses should NOT override this constructor;
|
||||
* instead, implement the configure() method.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
final public function __construct() {
|
||||
$this->configure();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the prompt properties.
|
||||
*
|
||||
* Subclasses must implement this method to set the name, title,
|
||||
* description, and arguments for the prompt. This method is called
|
||||
* exactly once during construction.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
abstract protected function configure(): void;
|
||||
|
||||
/**
|
||||
* Build and return the Prompt DTO instance.
|
||||
*
|
||||
* This method converts the configured state into an MCP Prompt DTO.
|
||||
* Safe to call multiple times - always returns a fresh DTO based on
|
||||
* the current (immutable after construction) state.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\Prompt The built prompt DTO.
|
||||
*/
|
||||
public function build(): PromptDto {
|
||||
$argument_dtos = null;
|
||||
if ( ! empty( $this->arguments ) ) {
|
||||
$argument_dtos = array_map(
|
||||
static function ( array $arg ): PromptArgument {
|
||||
return PromptArgument::fromArray(
|
||||
array(
|
||||
'name' => $arg['name'],
|
||||
'title' => $arg['title'] ?? null,
|
||||
'description' => $arg['description'] ?? null,
|
||||
'required' => $arg['required'] ?? null,
|
||||
)
|
||||
);
|
||||
},
|
||||
$this->arguments
|
||||
);
|
||||
}
|
||||
|
||||
// Validate and prepare icons if set.
|
||||
$valid_icons = null;
|
||||
if ( ! empty( $this->icons ) ) {
|
||||
$icons_result = McpValidator::validate_icons_array( $this->icons );
|
||||
if ( ! empty( $icons_result['valid'] ) ) {
|
||||
$valid_icons = $icons_result['valid'];
|
||||
}
|
||||
}
|
||||
|
||||
$prompt_data = array(
|
||||
'name' => $this->name,
|
||||
'title' => $this->title,
|
||||
'description' => $this->description,
|
||||
'arguments' => $argument_dtos,
|
||||
);
|
||||
|
||||
if ( ! empty( $this->meta ) ) {
|
||||
$prompt_data['_meta'] = $this->meta;
|
||||
}
|
||||
|
||||
// Only include icons if valid ones exist.
|
||||
if ( null !== $valid_icons ) {
|
||||
$prompt_data['icons'] = $valid_icons;
|
||||
}
|
||||
|
||||
return PromptDto::fromArray( $prompt_data );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the unique name for this prompt.
|
||||
*
|
||||
* @return string The prompt name.
|
||||
*/
|
||||
public function get_name(): string {
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the prompt title.
|
||||
*
|
||||
* @return string|null The prompt title.
|
||||
*/
|
||||
public function get_title(): ?string {
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the prompt description.
|
||||
*
|
||||
* @return string|null The prompt description.
|
||||
*/
|
||||
public function get_description(): ?string {
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the prompt arguments.
|
||||
*
|
||||
* @return list<array{name: string, title?: string, description?: string, required?: bool}> The prompt arguments.
|
||||
*/
|
||||
public function get_arguments(): array {
|
||||
return $this->arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the prompt icons.
|
||||
*
|
||||
* @return list<array{src: string, mimeType?: string, sizes?: array<string>, theme?: string}> The prompt icons.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public function get_icons(): array {
|
||||
return $this->icons ?? array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the prompt icons for UI display.
|
||||
*
|
||||
* Icons are validated during build() using McpValidator::validate_icons_array().
|
||||
* Invalid icons are filtered out with warnings (graceful degradation).
|
||||
*
|
||||
* Per MCP 2025-11-25:
|
||||
* - MUST support: image/png, image/jpeg, image/jpg
|
||||
* - SHOULD support: image/svg+xml, image/webp
|
||||
*
|
||||
* @param list<array{src: string, mimeType?: string, sizes?: array<string>, theme?: string}> $icons Array of icon definitions.
|
||||
*
|
||||
* @return self
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
protected function set_icons( array $icons ): self {
|
||||
$this->icons = $icons;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the additional metadata.
|
||||
*
|
||||
* @return array<string, mixed> The additional metadata.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public function get_meta(): array {
|
||||
return $this->meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set additional metadata.
|
||||
*
|
||||
* This metadata is passed through to MCP clients unchanged.
|
||||
*
|
||||
* @param array<string, mixed> $meta Additional metadata key-value pairs.
|
||||
*
|
||||
* @return self
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
protected function set_meta( array $meta ): self {
|
||||
$this->meta = $meta;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the prompt execution when called.
|
||||
*
|
||||
* Subclasses must implement this method to handle the prompt logic.
|
||||
*
|
||||
* @param array<string, mixed> $arguments The arguments passed to the prompt.
|
||||
*
|
||||
* @return array<string, mixed> The prompt response.
|
||||
*/
|
||||
abstract public function handle( array $arguments ): array;
|
||||
|
||||
/**
|
||||
* Check if the current user has permission to execute this prompt.
|
||||
*
|
||||
* Default implementation allows all executions. Override this method
|
||||
* to implement custom permission logic.
|
||||
*
|
||||
* @param array<string, mixed> $arguments The arguments passed to the prompt.
|
||||
*
|
||||
* @return bool True if execution is allowed, false otherwise.
|
||||
*/
|
||||
public function has_permission( array $arguments ): bool {
|
||||
// Default: allow all executions
|
||||
// Override this method to implement custom permission logic
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to add an argument to the prompt.
|
||||
*
|
||||
* @param string $name The argument name.
|
||||
* @param string|null $description Optional argument description.
|
||||
* @param bool $required Whether the argument is required.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
protected function add_argument( string $name, ?string $description = null, bool $required = false ): self {
|
||||
$this->arguments[] = $this->create_argument( $name, $description, $required );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to create an argument definition.
|
||||
*
|
||||
* @param string $name The argument name.
|
||||
* @param string|null $description Optional argument description.
|
||||
* @param bool $required Whether the argument is required.
|
||||
*
|
||||
* @return array{name: string, description?: string, required?: true} The argument definition.
|
||||
*/
|
||||
protected function create_argument( string $name, ?string $description = null, bool $required = false ): array {
|
||||
$argument = array(
|
||||
'name' => $name,
|
||||
);
|
||||
|
||||
if ( null !== $description ) {
|
||||
$argument['description'] = $description;
|
||||
}
|
||||
|
||||
if ( $required ) {
|
||||
$argument['required'] = true;
|
||||
}
|
||||
|
||||
return $argument;
|
||||
}
|
||||
}
|
||||
+520
@@ -0,0 +1,520 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Prompt Validator class for validating MCP prompts according to the specification.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Prompts;
|
||||
|
||||
use WP\MCP\Domain\Resources\McpResourceValidator;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt as PromptDto;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Validates MCP prompts against the Model Context Protocol specification.
|
||||
*
|
||||
* Provides minimal, resource-efficient validation to ensure prompts conform
|
||||
* to the MCP schema requirements without heavy processing overhead.
|
||||
*
|
||||
* @link https://modelcontextprotocol.io/specification/2025-11-25/server/prompts
|
||||
*/
|
||||
class McpPromptValidator {
|
||||
|
||||
/**
|
||||
* Validate an MCP prompt data array against the MCP schema.
|
||||
*
|
||||
* @param array $prompt_data The prompt data to validate.
|
||||
* @param string $context Optional context for error messages.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
public static function validate_prompt_data( array $prompt_data, string $context = '' ) {
|
||||
$validation_errors = self::get_validation_errors( $prompt_data );
|
||||
|
||||
if ( ! empty( $validation_errors ) ) {
|
||||
$error_message = $context ? "[{$context}] " : '';
|
||||
$error_message .= sprintf(
|
||||
/* translators: %s: comma-separated list of validation errors */
|
||||
__( 'Prompt validation failed: %s', 'mcp-adapter' ),
|
||||
implode( ', ', $validation_errors )
|
||||
);
|
||||
return new WP_Error( 'mcp_prompt_validation_failed', esc_html( $error_message ) );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a Prompt DTO against the MCP schema.
|
||||
*
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The prompt DTO to validate.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error otherwise.
|
||||
*/
|
||||
public static function validate_prompt_dto( PromptDto $prompt ) {
|
||||
$errors = array();
|
||||
|
||||
// Validate name.
|
||||
if ( ! McpValidator::validate_name( $prompt->getName() ) ) {
|
||||
$errors[] = __( 'Prompt name must be 1-128 characters and contain only [A-Za-z0-9_.-]', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate icons if present.
|
||||
$icons = $prompt->getIcons();
|
||||
if ( ! empty( $icons ) ) {
|
||||
$icons_array = array_map( static fn( $icon ) => $icon->toArray(), $icons );
|
||||
$icons_result = McpValidator::validate_icons_array( $icons_array );
|
||||
$icons_errors = self::format_icon_validation_errors( $icons_result );
|
||||
$errors = array_merge( $errors, $icons_errors );
|
||||
}
|
||||
|
||||
// Validate annotations if present (shared annotations).
|
||||
// Currently Prompt DTO doesn't have annotations field in spec, but if it did, we'd validate here.
|
||||
// BaseMetadata has title and name, handled separately.
|
||||
|
||||
if ( ! empty( $errors ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_prompt_validation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: list of validation errors */
|
||||
__( 'Prompt validation failed: %s', 'mcp-adapter' ),
|
||||
implode( '; ', $errors )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an McpPrompt instance against the MCP schema.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Prompts\McpPrompt $prompt The prompt instance to validate.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
public static function validate_prompt_instance( McpPrompt $prompt ) {
|
||||
return self::validate_prompt_dto( $prompt->get_protocol_dto() );
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get validation error details for debugging purposes.
|
||||
* This is the core validation method - all other validation methods use this.
|
||||
*
|
||||
* @param array $prompt_data The prompt data to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
public static function get_validation_errors( array $prompt_data ): array {
|
||||
$errors = array();
|
||||
|
||||
// Check required fields
|
||||
if ( empty( $prompt_data['name'] ) || ! is_string( $prompt_data['name'] ) || ! McpValidator::validate_name( $prompt_data['name'] ) ) {
|
||||
$errors[] = __( 'Prompt name is required and must be 1-128 characters and contain only [A-Za-z0-9_.-]', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Check optional fields if present
|
||||
if ( isset( $prompt_data['title'] ) && ! is_string( $prompt_data['title'] ) ) {
|
||||
$errors[] = __( 'Prompt title must be a string if provided', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
if ( isset( $prompt_data['description'] ) && ! is_string( $prompt_data['description'] ) ) {
|
||||
$errors[] = __( 'Prompt description must be a string if provided', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate arguments (optional field)
|
||||
if ( isset( $prompt_data['arguments'] ) ) {
|
||||
$arguments_errors = self::get_arguments_validation_errors( $prompt_data['arguments'] );
|
||||
if ( ! empty( $arguments_errors ) ) {
|
||||
$errors = array_merge( $errors, $arguments_errors );
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get detailed validation errors for prompt arguments.
|
||||
*
|
||||
* @param array|mixed $arguments The arguments to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
private static function get_arguments_validation_errors( $arguments ): array {
|
||||
$errors = array();
|
||||
|
||||
// Arguments must be an array
|
||||
if ( ! is_array( $arguments ) ) {
|
||||
return array( __( 'Prompt arguments must be an array if provided', 'mcp-adapter' ) );
|
||||
}
|
||||
|
||||
// Validate each argument
|
||||
foreach ( $arguments as $index => $argument ) {
|
||||
if ( ! is_array( $argument ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: argument index */
|
||||
__( 'Prompt argument at index %d must be an object', 'mcp-adapter' ),
|
||||
$index
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check required name field
|
||||
if ( empty( $argument['name'] ) || ! is_string( $argument['name'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: argument index */
|
||||
__( 'Prompt argument at index %d must have a non-empty name string', 'mcp-adapter' ),
|
||||
$index
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate argument name format (uses standard 128-char limit per MCP spec).
|
||||
if ( ! McpValidator::validate_name( $argument['name'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: argument name */
|
||||
__( 'Prompt argument \'%s\' name must only contain letters, numbers, hyphens (-), underscores (_), and dots (.), and be 128 characters or less', 'mcp-adapter' ),
|
||||
$argument['name']
|
||||
);
|
||||
}
|
||||
|
||||
// Check optional description field
|
||||
if ( isset( $argument['description'] ) && ! is_string( $argument['description'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: argument name */
|
||||
__( 'Prompt argument \'%s\' description must be a string if provided', 'mcp-adapter' ),
|
||||
$argument['name']
|
||||
);
|
||||
}
|
||||
|
||||
// Check optional required field
|
||||
if ( ! isset( $argument['required'] ) || is_bool( $argument['required'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: argument name */
|
||||
__( 'Prompt argument \'%s\' required field must be a boolean if provided', 'mcp-adapter' ),
|
||||
$argument['name']
|
||||
);
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate prompt messages array (used when getting a prompt with messages).
|
||||
*
|
||||
* @param array $messages The messages to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
public static function validate_prompt_messages( array $messages ): array {
|
||||
$errors = array();
|
||||
|
||||
foreach ( $messages as $index => $message ) {
|
||||
if ( ! is_array( $message ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message at index %d must be an object', 'mcp-adapter' ),
|
||||
$index
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check the required role field
|
||||
if ( empty( $message['role'] ) || ! is_string( $message['role'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message at index %d must have a role field', 'mcp-adapter' ),
|
||||
$index
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate role value
|
||||
if ( ! in_array( $message['role'], array( 'user', 'assistant' ), true ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message at index %d role must be either \'user\' or \'assistant\'', 'mcp-adapter' ),
|
||||
$index
|
||||
);
|
||||
}
|
||||
|
||||
// Check the required content field
|
||||
if ( empty( $message['content'] ) || ! is_array( $message['content'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message at index %d must have a content object', 'mcp-adapter' ),
|
||||
$index
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate content
|
||||
$content_errors = self::get_content_validation_errors( $message['content'], $index );
|
||||
if ( empty( $content_errors ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$errors = array_merge( $errors, $content_errors );
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format icon validation errors from the validation result.
|
||||
*
|
||||
* @param array{valid: array, errors: array} $icons_result The result from validate_icons_array.
|
||||
*
|
||||
* @return array Array of formatted error messages.
|
||||
*/
|
||||
private static function format_icon_validation_errors( array $icons_result ): array {
|
||||
$errors = array();
|
||||
|
||||
if ( ! empty( $icons_result['errors'] ) ) {
|
||||
foreach ( $icons_result['errors'] as $error_group ) {
|
||||
foreach ( $error_group['errors'] as $error ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: 1: icon index, 2: error message */
|
||||
__( 'Icon at index %1$d: %2$s', 'mcp-adapter' ),
|
||||
$error_group['index'],
|
||||
$error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors for message content.
|
||||
*
|
||||
* @param array $content The content to validate.
|
||||
* @param int $message_index The message index for error reporting.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
private static function get_content_validation_errors( array $content, int $message_index ): array {
|
||||
$errors = array();
|
||||
|
||||
// Check the required type field
|
||||
if ( empty( $content['type'] ) || ! is_string( $content['type'] ) ) {
|
||||
return array(
|
||||
sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d content must have a type field', 'mcp-adapter' ),
|
||||
$message_index
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
$type = $content['type'];
|
||||
|
||||
switch ( $type ) {
|
||||
case 'text':
|
||||
if ( ! isset( $content['text'] ) || ! is_string( $content['text'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d text content must have a text field', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'image':
|
||||
if ( empty( $content['data'] ) || ! is_string( $content['data'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d image content must have a data field with base64-encoded image', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} elseif ( ! McpValidator::validate_base64( $content['data'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d image content data must be valid base64', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
|
||||
if ( empty( $content['mimeType'] ) || ! is_string( $content['mimeType'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d image content must have a mimeType field', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} elseif ( ! McpValidator::validate_image_mime_type( $content['mimeType'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d image content must have a valid image MIME type', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'audio':
|
||||
if ( empty( $content['data'] ) || ! is_string( $content['data'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d audio content must have a data field with base64-encoded audio', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} elseif ( ! McpValidator::validate_base64( $content['data'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d audio content data must be valid base64', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
|
||||
if ( empty( $content['mimeType'] ) || ! is_string( $content['mimeType'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d audio content must have a mimeType field', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} elseif ( ! McpValidator::validate_audio_mime_type( $content['mimeType'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d audio content must have a valid audio MIME type', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'resource_link':
|
||||
// ResourceLink is a metadata-only reference (same shape as Resource + type discriminator).
|
||||
if ( empty( $content['name'] ) || ! is_string( $content['name'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content must have a name field', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
|
||||
if ( empty( $content['uri'] ) || ! is_string( $content['uri'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content must have a uri field', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} elseif ( ! McpValidator::validate_resource_uri( $content['uri'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content uri must be a valid URI format', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
|
||||
if ( isset( $content['mimeType'] ) ) {
|
||||
if ( ! is_string( $content['mimeType'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content mimeType must be a string if provided', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} elseif ( ! McpValidator::validate_mime_type( $content['mimeType'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content mimeType must be a valid MIME type format', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ( isset( $content['size'] ) && ! is_int( $content['size'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content size must be an integer if provided', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
|
||||
if ( isset( $content['title'] ) && ! is_string( $content['title'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content title must be a string if provided', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
|
||||
if ( isset( $content['description'] ) && ! is_string( $content['description'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content description must be a string if provided', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
}
|
||||
|
||||
if ( isset( $content['icons'] ) ) {
|
||||
if ( ! is_array( $content['icons'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource_link content icons must be an array if provided', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} else {
|
||||
$icons_result = McpValidator::validate_icons_array( $content['icons'], false );
|
||||
$errors = array_merge( $errors, self::format_icon_validation_errors( $icons_result ) );
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'resource':
|
||||
if ( empty( $content['resource'] ) || ! is_array( $content['resource'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d resource content must have a resource object', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} else {
|
||||
// Validate embedded resource using the resource validator for strict MCP compliance.
|
||||
$resource_errors = McpResourceValidator::get_validation_errors( $content['resource'] );
|
||||
foreach ( $resource_errors as $resource_error ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %1$d: message index, %2$s: resource error */
|
||||
__( 'Message %1$d embedded resource: %2$s', 'mcp-adapter' ),
|
||||
$message_index,
|
||||
$resource_error
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
$errors[] = sprintf(
|
||||
/* translators: %1$d: message index, %2$s: content type */
|
||||
__( 'Message %1$d content type \'%2$s\' is not supported. Must be \'text\', \'image\', \'audio\', \'resource\', or \'resource_link\'', 'mcp-adapter' ),
|
||||
$message_index,
|
||||
$type
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
// Check optional annotations
|
||||
if ( isset( $content['annotations'] ) ) {
|
||||
if ( ! is_array( $content['annotations'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: message index */
|
||||
__( 'Message %d content annotations must be an array if provided', 'mcp-adapter' ),
|
||||
$message_index
|
||||
);
|
||||
} else {
|
||||
$annotation_errors = McpValidator::get_annotation_validation_errors( $content['annotations'] );
|
||||
if ( ! empty( $annotation_errors ) ) {
|
||||
$errors = array_merge( $errors, $annotation_errors );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
}
|
||||
+529
@@ -0,0 +1,529 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* RegisterAbilityAsMcpPrompt class for converting WordPress abilities to MCP prompts.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Prompts;
|
||||
|
||||
use WP\MCP\Domain\Utils\McpNameSanitizer;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\MCP\Domain\Utils\SchemaTransformer;
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt as PromptDto;
|
||||
use WP\McpSchema\Server\Prompts\DTO\PromptArgument;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Converts WordPress abilities to MCP prompts according to the specification.
|
||||
*
|
||||
* This class extracts prompt data from ability properties and converts the JSON Schema
|
||||
* input_schema to MCP prompt arguments format.
|
||||
*
|
||||
* Schema Handling:
|
||||
* - Object schemas with properties: Each property becomes a PromptArgument
|
||||
* - Flattened schemas (type: string, number, etc.): Wrapped as single argument named "input"
|
||||
* - Empty/null schemas: No arguments
|
||||
* - Complex schemas (oneOf/anyOf): Treated as no arguments (documented limitation)
|
||||
*
|
||||
* Example ability registration:
|
||||
* wp_register_ability(
|
||||
* 'prompts/code-review',
|
||||
* array(
|
||||
* 'label' => 'Code Review Prompt',
|
||||
* 'description' => 'Generate code review prompt',
|
||||
* 'input_schema' => array(
|
||||
* 'type' => 'object',
|
||||
* 'properties' => array(
|
||||
* 'code' => array('type' => 'string', 'description' => 'Code to review'),
|
||||
* ),
|
||||
* 'required' => array('code'),
|
||||
* ),
|
||||
* 'meta' => array(
|
||||
* 'mcp' => array('public' => true, 'type' => 'prompt'),
|
||||
* 'annotations' => array(...)
|
||||
* )
|
||||
* )
|
||||
* );
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
class RegisterAbilityAsMcpPrompt {
|
||||
|
||||
/**
|
||||
* The WordPress ability instance.
|
||||
*
|
||||
* @var \WP_Ability
|
||||
*/
|
||||
private \WP_Ability $ability;
|
||||
|
||||
/**
|
||||
* Tracks whether input_schema was transformed from flattened to object format.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private bool $schema_was_transformed = false;
|
||||
|
||||
/**
|
||||
* The wrapper property name used when transforming flattened schemas.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
private ?string $schema_wrapper_property = null;
|
||||
|
||||
/**
|
||||
* Tracks the source of prompt arguments.
|
||||
*
|
||||
* Possible values:
|
||||
* - 'explicit': Arguments came from ability.meta.mcp.arguments
|
||||
* - 'schema': Arguments were auto-converted from ability.input_schema
|
||||
* - null: No arguments present
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
private ?string $arguments_source = null;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
*/
|
||||
private function __construct( \WP_Ability $ability ) {
|
||||
$this->ability = $ability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a new instance of the class.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\Prompt|\WP_Error Returns Prompt DTO or WP_Error if validation fails.
|
||||
*/
|
||||
public static function make( \WP_Ability $ability ) {
|
||||
$prompt = new self( $ability );
|
||||
|
||||
return $prompt->get_prompt();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the MCP prompt instance.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\Prompt|\WP_Error Prompt DTO or WP_Error if validation fails.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function get_prompt() {
|
||||
$built = $this->build_prompt_data();
|
||||
|
||||
// Propagate WP_Error from argument validation.
|
||||
if ( is_wp_error( $built ) ) {
|
||||
return $built;
|
||||
}
|
||||
|
||||
try {
|
||||
return PromptDto::fromArray( $built['prompt_data'] );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error( 'mcp_prompt_schema_invalid', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Prompt DTO data and adapter metadata.
|
||||
*
|
||||
* @return array{prompt_data: array<string, mixed>, adapter_meta: array<string, mixed>}|\WP_Error
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function build_prompt_data() {
|
||||
$data = $this->get_data();
|
||||
|
||||
// Propagate WP_Error from argument validation.
|
||||
if ( is_wp_error( $data ) ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
// Get ability meta for icons and user _meta extraction.
|
||||
$ability_meta = $this->ability->get_meta();
|
||||
$mcp_meta = $ability_meta['mcp'] ?? array();
|
||||
|
||||
// Map icons from ability.meta.mcp.icons if present.
|
||||
// Uses same pattern as tools/resources for consistency.
|
||||
if ( ! empty( $mcp_meta['icons'] ) && is_array( $mcp_meta['icons'] ) ) {
|
||||
$icons_result = McpValidator::validate_icons_array( $mcp_meta['icons'] );
|
||||
if ( ! empty( $icons_result['valid'] ) ) {
|
||||
$data['icons'] = $icons_result['valid'];
|
||||
}
|
||||
}
|
||||
|
||||
// Build adapter metadata, tracking transformation when it occurred.
|
||||
$adapter_meta = array(
|
||||
'ability' => $this->ability->get_name(),
|
||||
);
|
||||
|
||||
// Track arguments source when arguments are present.
|
||||
if ( null !== $this->arguments_source ) {
|
||||
$adapter_meta['arguments_source'] = $this->arguments_source;
|
||||
}
|
||||
|
||||
// Record transformation metadata when schema was wrapped (matches tool behavior).
|
||||
// Only relevant when arguments_source is 'schema'.
|
||||
if ( $this->schema_was_transformed && 'schema' === $this->arguments_source ) {
|
||||
$adapter_meta['input_schema_transformed'] = true;
|
||||
$adapter_meta['input_schema_wrapper'] = $this->schema_wrapper_property;
|
||||
}
|
||||
|
||||
// Preserve user-provided _meta from ability.meta.mcp._meta.
|
||||
$prompt_meta = array();
|
||||
if ( ! empty( $mcp_meta['_meta'] ) && is_array( $mcp_meta['_meta'] ) ) {
|
||||
$prompt_meta = $mcp_meta['_meta'];
|
||||
}
|
||||
if ( ! empty( $prompt_meta ) ) {
|
||||
$data['_meta'] = $prompt_meta;
|
||||
}
|
||||
|
||||
return array(
|
||||
'prompt_data' => $data,
|
||||
'adapter_meta' => $adapter_meta,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the MCP prompt data array.
|
||||
*
|
||||
* Per MCP 2025-11-25 specification, Prompt objects do NOT support annotations at the
|
||||
* template level. Annotations are only supported on content blocks inside prompt messages
|
||||
* (messages[].content.annotations).
|
||||
*
|
||||
* Arguments Resolution:
|
||||
* 1. If `ability.meta.mcp.arguments` is defined and non-empty, use it directly (explicit override)
|
||||
* 2. Otherwise, auto-convert from `ability.input_schema`
|
||||
*
|
||||
* This follows the `mcp.*` override pattern used elsewhere (mcp.uri, mcp.icons, mcp.annotations).
|
||||
*
|
||||
* @return array<string,mixed>|\WP_Error Prompt data array, or WP_Error if explicit arguments are invalid.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function get_data() {
|
||||
$prompt_name = $this->resolve_prompt_name();
|
||||
if ( is_wp_error( $prompt_name ) ) {
|
||||
return $prompt_name;
|
||||
}
|
||||
|
||||
$prompt_data = array(
|
||||
'name' => $prompt_name,
|
||||
);
|
||||
|
||||
// Add optional title from ability label.
|
||||
$label = trim( $this->ability->get_label() );
|
||||
if ( ! empty( $label ) ) {
|
||||
$prompt_data['title'] = $label;
|
||||
}
|
||||
|
||||
// Add optional description.
|
||||
$description = trim( $this->ability->get_description() );
|
||||
if ( ! empty( $description ) ) {
|
||||
$prompt_data['description'] = $description;
|
||||
}
|
||||
|
||||
// Check for explicit mcp.arguments override first.
|
||||
$explicit_arguments = $this->get_explicit_arguments();
|
||||
if ( is_array( $explicit_arguments ) && ! empty( $explicit_arguments ) ) {
|
||||
$arguments = $this->convert_explicit_arguments( $explicit_arguments );
|
||||
if ( is_wp_error( $arguments ) ) {
|
||||
return $arguments;
|
||||
}
|
||||
if ( ! empty( $arguments ) ) {
|
||||
$prompt_data['arguments'] = $arguments;
|
||||
$this->arguments_source = 'explicit';
|
||||
}
|
||||
|
||||
return $prompt_data;
|
||||
}
|
||||
|
||||
// Fall back to auto-converting from input_schema.
|
||||
$input_schema = $this->ability->get_input_schema();
|
||||
if ( ! empty( $input_schema ) ) {
|
||||
// Use SchemaTransformer to handle flattened schemas (consistent with tool behavior).
|
||||
$transform = SchemaTransformer::transform_to_object_schema( $input_schema );
|
||||
|
||||
// Track transformation state for _meta.
|
||||
$this->schema_was_transformed = $transform['was_transformed'];
|
||||
$this->schema_wrapper_property = $transform['wrapper_property'];
|
||||
|
||||
$arguments = $this->convert_input_schema_to_arguments( $transform['schema'] );
|
||||
if ( ! empty( $arguments ) ) {
|
||||
$prompt_data['arguments'] = $arguments;
|
||||
$this->arguments_source = 'schema';
|
||||
}
|
||||
}
|
||||
|
||||
return $prompt_data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get explicit arguments from ability meta.mcp.arguments.
|
||||
*
|
||||
* @return list<array<string,mixed>>|null Explicit arguments array or null if not defined.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function get_explicit_arguments(): ?array {
|
||||
$meta = $this->ability->get_meta();
|
||||
if ( ! isset( $meta['mcp'] ) || ! is_array( $meta['mcp'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$mcp = $meta['mcp'];
|
||||
if ( ! isset( $mcp['arguments'] ) || ! is_array( $mcp['arguments'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return array_values( $mcp['arguments'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert and validate explicit arguments from ability.meta.mcp.arguments.
|
||||
*
|
||||
* Per MCP 2025-11-25 specification, PromptArgument has:
|
||||
* - name (string, required): Argument identifier
|
||||
* - title (string, optional): Human-readable display name
|
||||
* - description (string, optional): Human-readable description
|
||||
* - required (boolean, optional): Whether the argument must be provided
|
||||
*
|
||||
* @param list<array<string,mixed>> $explicit_arguments User-defined arguments array.
|
||||
*
|
||||
* @return list<\WP\McpSchema\Server\Prompts\DTO\PromptArgument>|\WP_Error PromptArgument DTOs or WP_Error.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function convert_explicit_arguments( array $explicit_arguments ) {
|
||||
$arguments = array();
|
||||
|
||||
foreach ( $explicit_arguments as $index => $arg ) {
|
||||
if ( ! is_array( $arg ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_prompt_invalid_argument',
|
||||
sprintf(
|
||||
/* translators: 1: argument index, 2: ability name */
|
||||
__( 'Argument at index %1$d must be an array for ability "%2$s".', 'mcp-adapter' ),
|
||||
$index,
|
||||
$this->ability->get_name()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Validate required 'name' field.
|
||||
if ( ! isset( $arg['name'] ) || ! is_string( $arg['name'] ) || '' === trim( $arg['name'] ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_prompt_argument_missing_name',
|
||||
sprintf(
|
||||
/* translators: 1: argument index, 2: ability name */
|
||||
__( 'Argument at index %1$d is missing required "name" field for ability "%2$s".', 'mcp-adapter' ),
|
||||
$index,
|
||||
$this->ability->get_name()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$argument_data = array(
|
||||
'name' => trim( $arg['name'] ),
|
||||
);
|
||||
|
||||
// Map optional 'title' field.
|
||||
if ( isset( $arg['title'] ) && is_string( $arg['title'] ) && '' !== trim( $arg['title'] ) ) {
|
||||
$argument_data['title'] = trim( $arg['title'] );
|
||||
}
|
||||
|
||||
// Map optional 'description' field.
|
||||
if ( isset( $arg['description'] ) && is_string( $arg['description'] ) && '' !== trim( $arg['description'] ) ) {
|
||||
$argument_data['description'] = trim( $arg['description'] );
|
||||
}
|
||||
|
||||
// Map optional 'required' field (only emit when true, per existing pattern).
|
||||
if ( isset( $arg['required'] ) && true === $arg['required'] ) {
|
||||
$argument_data['required'] = true;
|
||||
}
|
||||
|
||||
$arguments[] = PromptArgument::fromArray( $argument_data );
|
||||
}
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert JSON Schema input_schema to MCP prompt arguments format.
|
||||
*
|
||||
* Converts from WordPress Abilities JSON Schema format:
|
||||
* {
|
||||
* "type": "object",
|
||||
* "properties": {
|
||||
* "topic": {"type": "string", "title": "Topic", "description": "..."},
|
||||
* "tone": {"type": "string", "description": "..."}
|
||||
* },
|
||||
* "required": ["topic"]
|
||||
* }
|
||||
*
|
||||
* To MCP prompt arguments format:
|
||||
* [
|
||||
* {"name": "topic", "title": "Topic", "description": "...", "required": true},
|
||||
* {"name": "tone", "description": "..."}
|
||||
* ]
|
||||
*
|
||||
* Note: `required` is only emitted when true; optional arguments omit the field entirely.
|
||||
*
|
||||
* @param array<string,mixed> $input_schema The JSON Schema from ability.
|
||||
*
|
||||
* @return list<\WP\McpSchema\Server\Prompts\DTO\PromptArgument> Argument DTO list.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function convert_input_schema_to_arguments( array $input_schema ): array {
|
||||
$arguments = array();
|
||||
|
||||
// Ensure we have properties to convert.
|
||||
if ( empty( $input_schema['properties'] ) || ! is_array( $input_schema['properties'] ) ) {
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
// Get the list of required properties.
|
||||
$required_fields = array();
|
||||
if ( isset( $input_schema['required'] ) && is_array( $input_schema['required'] ) ) {
|
||||
$required_fields = $input_schema['required'];
|
||||
}
|
||||
|
||||
// Convert each property to an MCP argument.
|
||||
foreach ( $input_schema['properties'] as $property_name => $property_schema ) {
|
||||
if ( ! is_array( $property_schema ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$is_required = in_array( $property_name, $required_fields, true );
|
||||
|
||||
$argument_data = array(
|
||||
'name' => $property_name,
|
||||
);
|
||||
|
||||
// Map JSON Schema title to PromptArgument.title when present.
|
||||
if ( ! empty( $property_schema['title'] ) && is_string( $property_schema['title'] ) ) {
|
||||
$argument_data['title'] = $property_schema['title'];
|
||||
}
|
||||
|
||||
// Map JSON Schema description to PromptArgument.description when present.
|
||||
if ( ! empty( $property_schema['description'] ) && is_string( $property_schema['description'] ) ) {
|
||||
$argument_data['description'] = $property_schema['description'];
|
||||
}
|
||||
|
||||
// Only emit required when true; omit for optional arguments.
|
||||
if ( $is_required ) {
|
||||
$argument_data['required'] = true;
|
||||
}
|
||||
|
||||
$arguments[] = PromptArgument::fromArray( $argument_data );
|
||||
}
|
||||
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the MCP prompt name from ability.
|
||||
*
|
||||
* Sanitizes the ability name to MCP-valid format, applies filter, and validates result.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @return string|\WP_Error Valid prompt name or error.
|
||||
*/
|
||||
private function resolve_prompt_name() {
|
||||
// Sanitize ability name to MCP-valid format.
|
||||
$sanitized_name = McpNameSanitizer::sanitize_name( $this->ability->get_name() );
|
||||
|
||||
if ( is_wp_error( $sanitized_name ) ) {
|
||||
return $sanitized_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the MCP prompt name derived from an ability.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $name The sanitized prompt name.
|
||||
* @param \WP_Ability $ability The source ability instance.
|
||||
*/
|
||||
$filtered_name = apply_filters( 'mcp_adapter_prompt_name', $sanitized_name, $this->ability );
|
||||
|
||||
// Validate post-filter (in case filter broke it).
|
||||
if ( ! is_string( $filtered_name ) || ! McpValidator::validate_name( $filtered_name ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_prompt_name_filter_invalid',
|
||||
sprintf(
|
||||
/* translators: %s: invalid prompt name returned by filter */
|
||||
__( 'Filter returned invalid MCP prompt name: %s', 'mcp-adapter' ),
|
||||
is_string( $filtered_name ) ? $filtered_name : gettype( $filtered_name )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $filtered_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a clean Prompt DTO and adapter metadata for internal wiring.
|
||||
*
|
||||
* This method returns a protocol-only Prompt DTO and provides the adapter metadata
|
||||
* separately. This keeps the DTO stable across MCP spec changes and avoids coupling internal execution
|
||||
* wiring to protocol surfaces.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
*
|
||||
* @return array{prompt: \WP\McpSchema\Server\Prompts\DTO\Prompt, adapter_meta: array<string, mixed>}|\WP_Error
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function build( \WP_Ability $ability ) {
|
||||
$prompt = new self( $ability );
|
||||
$data = $prompt->build_prompt_data();
|
||||
|
||||
if ( is_wp_error( $data ) ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
try {
|
||||
$prompt_dto = PromptDto::fromArray( $data['prompt_data'] );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'mcp_prompt_dto_creation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: error message */
|
||||
__( 'Failed to create Prompt DTO for ability %1$s: %2$s', 'mcp-adapter' ),
|
||||
$ability->get_name(),
|
||||
$e->getMessage()
|
||||
),
|
||||
array( 'exception' => $e )
|
||||
);
|
||||
}
|
||||
|
||||
// Optional deep validation if enabled.
|
||||
$mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false );
|
||||
if ( $mcp_validation_enabled ) {
|
||||
$validation_result = McpPromptValidator::validate_prompt_dto( $prompt_dto );
|
||||
if ( is_wp_error( $validation_result ) ) {
|
||||
return $validation_result;
|
||||
}
|
||||
}
|
||||
|
||||
return array(
|
||||
'prompt' => $prompt_dto,
|
||||
'adapter_meta' => $data['adapter_meta'],
|
||||
);
|
||||
}
|
||||
}
|
||||
+358
@@ -0,0 +1,358 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MCP Resource component.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Resources;
|
||||
|
||||
use WP\MCP\Domain\Contracts\McpComponentInterface;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\FailureReason;
|
||||
use WP\McpSchema\Common\Protocol\DTO\Annotations;
|
||||
use WP\McpSchema\Server\Resources\DTO\Resource as ResourceDto;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Resource component providing unified execution and permission checks.
|
||||
*
|
||||
* This class supports multiple ways to register resources:
|
||||
*
|
||||
* 1. Array configuration:
|
||||
* ```php
|
||||
* $resource = McpResource::fromArray([
|
||||
* 'uri' => 'WordPress://local/readme',
|
||||
* 'title' => 'README',
|
||||
* 'description' => 'Example resource',
|
||||
* 'handler' => fn() => 'Hello',
|
||||
* 'permission' => fn() => true,
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* 2. From WordPress Ability (ability-backed):
|
||||
* ```php
|
||||
* $resource = McpResource::fromAbility($ability);
|
||||
* ```
|
||||
*
|
||||
* McpResource wraps a protocol-only ResourceDto for MCP serialization. Internal
|
||||
* adapter metadata and execution wiring live on this class and are never
|
||||
* exposed to MCP clients. Use get_protocol_dto() for protocol responses.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
final class McpResource implements McpComponentInterface {
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// Runtime Properties
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Clean Resource DTO (protocol-only).
|
||||
*
|
||||
* @var \WP\McpSchema\Server\Resources\DTO\Resource
|
||||
*/
|
||||
private ResourceDto $mcp_resource_dto;
|
||||
|
||||
/**
|
||||
* Ability used for execution/permission checks (ability-backed resources).
|
||||
*
|
||||
* @var \WP_Ability|null
|
||||
*/
|
||||
private ?\WP_Ability $ability = null;
|
||||
|
||||
/**
|
||||
* Direct execution handler (callable-backed resources).
|
||||
*
|
||||
* @var callable|null
|
||||
*/
|
||||
private $handler = null;
|
||||
|
||||
/**
|
||||
* Direct permission callback (callable-backed resources).
|
||||
*
|
||||
* @var callable|null
|
||||
*/
|
||||
private $permission_callback = null;
|
||||
|
||||
/**
|
||||
* Internal adapter metadata (never exposed to clients).
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $adapter_meta = array();
|
||||
|
||||
/**
|
||||
* Observability context tags for logging/metrics.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $observability_context = array();
|
||||
|
||||
// =========================================================================
|
||||
// Constructor
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Private constructor - use factory methods.
|
||||
*
|
||||
* @param \WP\McpSchema\Server\Resources\DTO\Resource $resource_dto The Resource DTO.
|
||||
*/
|
||||
private function __construct( ResourceDto $resource_dto ) {
|
||||
$this->mcp_resource_dto = $resource_dto;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Factory Methods
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* @param array $config The resource configuration array.
|
||||
*
|
||||
* @return self|\WP_Error
|
||||
*/
|
||||
public static function fromArray( array $config ) {
|
||||
if ( empty( $config['uri'] ) ) {
|
||||
return new WP_Error( 'mcp_resource_missing_uri', 'Resource configuration must include a "uri" field.' );
|
||||
}
|
||||
|
||||
if ( ! isset( $config['handler'] ) || ! is_callable( $config['handler'] ) ) {
|
||||
return new WP_Error( 'mcp_resource_missing_handler', 'Resource configuration must include a callable "handler" field.' );
|
||||
}
|
||||
|
||||
$uri = trim( $config['uri'] );
|
||||
|
||||
if ( ! McpValidator::validate_resource_uri( $uri ) ) {
|
||||
return new WP_Error( 'mcp_resource_invalid_uri', 'Resource "uri" must be a valid RFC 3986 URI with a scheme.' );
|
||||
}
|
||||
|
||||
$name = isset( $config['name'] ) ? trim( $config['name'] ) : $uri;
|
||||
if ( '' === $name ) {
|
||||
return new WP_Error( 'mcp_resource_missing_name', 'Resource "name" cannot be empty.' );
|
||||
}
|
||||
|
||||
$resource_data = array(
|
||||
'name' => $name,
|
||||
'uri' => $uri,
|
||||
);
|
||||
|
||||
if ( isset( $config['title'] ) ) {
|
||||
$resource_data['title'] = $config['title'];
|
||||
}
|
||||
|
||||
if ( isset( $config['description'] ) ) {
|
||||
$resource_data['description'] = $config['description'];
|
||||
}
|
||||
|
||||
// Include mimeType only when valid.
|
||||
if ( isset( $config['mimeType'] ) ) {
|
||||
$mime_type = trim( $config['mimeType'] );
|
||||
if ( '' !== $mime_type && McpValidator::validate_mime_type( $mime_type ) ) {
|
||||
$resource_data['mimeType'] = $mime_type;
|
||||
}
|
||||
}
|
||||
|
||||
// Include size only when > 0.
|
||||
if ( isset( $config['size'] ) && $config['size'] > 0 ) {
|
||||
$resource_data['size'] = $config['size'];
|
||||
}
|
||||
|
||||
// Validate and include icons if set.
|
||||
if ( isset( $config['icons'] ) && is_array( $config['icons'] ) && ! empty( $config['icons'] ) ) {
|
||||
$icons_result = McpValidator::validate_icons_array( $config['icons'] );
|
||||
if ( ! empty( $icons_result['valid'] ) ) {
|
||||
$resource_data['icons'] = $icons_result['valid'];
|
||||
}
|
||||
}
|
||||
|
||||
if ( isset( $config['meta'] ) && is_array( $config['meta'] ) && ! empty( $config['meta'] ) ) {
|
||||
$resource_data['_meta'] = $config['meta'];
|
||||
}
|
||||
|
||||
// Create the Resource DTO - wrap in try-catch since Annotations::fromArray() and ResourceDto::fromArray() can throw.
|
||||
try {
|
||||
// Process annotations inside try-catch since Annotations::fromArray() can throw.
|
||||
if ( isset( $config['annotations'] ) && is_array( $config['annotations'] ) && ! empty( $config['annotations'] ) ) {
|
||||
$resource_data['annotations'] = Annotations::fromArray( $config['annotations'] );
|
||||
}
|
||||
|
||||
$resource = ResourceDto::fromArray( $resource_data );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'mcp_resource_dto_creation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: error message */
|
||||
__( 'Failed to create Resource DTO: %s', 'mcp-adapter' ),
|
||||
$e->getMessage()
|
||||
),
|
||||
array( 'exception' => $e )
|
||||
);
|
||||
}
|
||||
|
||||
// Optional deep validation if enabled.
|
||||
$mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false );
|
||||
if ( $mcp_validation_enabled ) {
|
||||
$validation_result = McpResourceValidator::validate_resource_dto( $resource );
|
||||
if ( is_wp_error( $validation_result ) ) {
|
||||
return $validation_result;
|
||||
}
|
||||
}
|
||||
|
||||
$instance = new self( $resource );
|
||||
$instance->handler = $config['handler'];
|
||||
|
||||
if ( isset( $config['permission'] ) && is_callable( $config['permission'] ) ) {
|
||||
$instance->permission_callback = $config['permission'];
|
||||
}
|
||||
|
||||
$instance->observability_context = array(
|
||||
'component_type' => 'resource',
|
||||
'resource_uri' => $uri,
|
||||
'source' => 'array',
|
||||
);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ability-backed MCP resource.
|
||||
*
|
||||
* @param \WP_Ability $ability WordPress ability.
|
||||
* @param \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface|null $error_handler Optional error handler.
|
||||
*
|
||||
* @return self|\WP_Error
|
||||
*/
|
||||
public static function fromAbility( \WP_Ability $ability, ?McpErrorHandlerInterface $error_handler = null ) {
|
||||
$resource_data = RegisterAbilityAsMcpResource::build( $ability, $error_handler );
|
||||
if ( $resource_data instanceof WP_Error ) {
|
||||
return $resource_data;
|
||||
}
|
||||
|
||||
$instance = new self( $resource_data['resource'] );
|
||||
$instance->adapter_meta = $resource_data['adapter_meta'];
|
||||
$instance->ability = $ability;
|
||||
|
||||
$instance->observability_context = array(
|
||||
'component_type' => 'resource',
|
||||
'resource_uri' => $resource_data['resource']->getUri(),
|
||||
'ability_name' => $ability->get_name(),
|
||||
'source' => 'ability',
|
||||
);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// McpComponentInterface Implementation
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get the clean protocol DTO for MCP responses.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Resources\DTO\Resource
|
||||
*/
|
||||
public function get_protocol_dto(): ResourceDto {
|
||||
return $this->mcp_resource_dto;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the resource read.
|
||||
*
|
||||
* @param mixed $arguments Read arguments (may be empty).
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function execute( $arguments ) {
|
||||
// Ability-backed resources match existing behavior: no args passed to abilities.
|
||||
if ( null !== $this->ability ) {
|
||||
try {
|
||||
return $this->ability->execute();
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_execution_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ( null !== $this->handler ) {
|
||||
try {
|
||||
return call_user_func( $this->handler, $arguments );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_execution_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new WP_Error( 'mcp_resource_no_handler', 'No resource execution strategy configured.' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the current request has permission to read this resource.
|
||||
*
|
||||
* @param mixed $arguments Read arguments (may be empty).
|
||||
*
|
||||
* @return bool|\WP_Error
|
||||
*/
|
||||
public function check_permission( $arguments ) {
|
||||
// Ability-backed resources match existing behavior: no args passed to abilities.
|
||||
if ( null !== $this->ability ) {
|
||||
try {
|
||||
return $this->ability->check_permissions();
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_permission_check_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ( null !== $this->permission_callback ) {
|
||||
try {
|
||||
$result = call_user_func( $this->permission_callback, $arguments );
|
||||
|
||||
return $result instanceof WP_Error ? $result : (bool) $result;
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_permission_check_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return new WP_Error(
|
||||
'mcp_permission_denied',
|
||||
'Access denied.',
|
||||
array( 'failure_reason' => FailureReason::NO_PERMISSION_STRATEGY )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get internal adapter metadata for this resource.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function get_adapter_meta(): array {
|
||||
return $this->adapter_meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get observability context tags for logging/metrics.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function get_observability_context(): array {
|
||||
return $this->observability_context;
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Resource Validator class for validating MCP resources according to the specification.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Resources;
|
||||
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\McpSchema\Server\Resources\DTO\Resource as ResourceDto;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Validates MCP resources against the Model Context Protocol specification.
|
||||
*
|
||||
* Provides minimal, resource-efficient validation to ensure resources conform
|
||||
* to the MCP schema requirements without heavy processing overhead.
|
||||
*
|
||||
* @link https://modelcontextprotocol.io/specification/2025-11-25/server/resources
|
||||
*/
|
||||
class McpResourceValidator {
|
||||
|
||||
/**
|
||||
* Validate the MCP resource data array against the MCP schema.
|
||||
*
|
||||
* @param array $resource_data The resource data to validate.
|
||||
* @param string $context Optional context for error messages.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
public static function validate_resource_data( array $resource_data, string $context = '' ) {
|
||||
$validation_errors = self::get_validation_errors( $resource_data );
|
||||
|
||||
if ( ! empty( $validation_errors ) ) {
|
||||
$error_message = $context ? "[{$context}] " : '';
|
||||
$error_message .= sprintf(
|
||||
/* translators: %s: comma-separated list of validation errors */
|
||||
__( 'Resource validation failed: %s', 'mcp-adapter' ),
|
||||
implode( ', ', $validation_errors )
|
||||
);
|
||||
return new WP_Error( 'mcp_resource_validation_failed', esc_html( $error_message ) );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a Resource DTO against the MCP schema.
|
||||
*
|
||||
* @param \WP\McpSchema\Server\Resources\DTO\Resource $resource_dto The resource DTO to validate.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error otherwise.
|
||||
*/
|
||||
public static function validate_resource_dto( ResourceDto $resource_dto ) {
|
||||
$errors = array();
|
||||
|
||||
// Validate URI.
|
||||
if ( ! McpValidator::validate_resource_uri( $resource_dto->getUri() ) ) {
|
||||
$errors[] = __( 'Resource URI must be a valid URI string', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate the MIME type if present.
|
||||
$mime_type = $resource_dto->getMimeType();
|
||||
if ( $mime_type && ! McpValidator::validate_mime_type( $mime_type ) ) {
|
||||
$errors[] = __( 'Resource MIME type is invalid', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate icons if present.
|
||||
$icons = $resource_dto->getIcons();
|
||||
if ( ! empty( $icons ) ) {
|
||||
$icons_array = array_map( static fn( $icon ) => $icon->toArray(), $icons );
|
||||
$icons_result = McpValidator::validate_icons_array( $icons_array );
|
||||
$icons_errors = self::format_icon_validation_errors( $icons_result );
|
||||
$errors = array_merge( $errors, $icons_errors );
|
||||
}
|
||||
|
||||
// Validate annotations if present.
|
||||
$annotations = $resource_dto->getAnnotations();
|
||||
if ( $annotations ) {
|
||||
$annotation_errors = McpValidator::get_annotation_validation_errors( $annotations->toArray() );
|
||||
$errors = array_merge( $errors, $annotation_errors );
|
||||
}
|
||||
|
||||
if ( ! empty( $errors ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_resource_validation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: list of validation errors */
|
||||
__( 'Resource validation failed: %s', 'mcp-adapter' ),
|
||||
implode( '; ', $errors )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an McpResource instance against the MCP schema.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Resources\McpResource $the_resource The resource instance to validate.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
public static function validate_resource_instance( McpResource $the_resource ) {
|
||||
return self::validate_resource_dto( $the_resource->get_protocol_dto() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors for MCP resource contents.
|
||||
*
|
||||
* NOTE: This validates the `resource` object used by:
|
||||
* - `resources/read` results (`TextResourceContents` / `BlobResourceContents`)
|
||||
* - `content` blocks of type `resource` (`EmbeddedResource.resource`)
|
||||
*
|
||||
* It does NOT validate the `Resource` metadata object returned by `resources/list`.
|
||||
* For `Resource` DTO validation (resources/list), use validate_resource_dto() instead.
|
||||
*
|
||||
* This validator focuses on the MCP-required fields and ignores unknown fields to remain
|
||||
* forward-compatible with future schema versions.
|
||||
*
|
||||
* @param array $resource_data The resource contents object to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
public static function get_validation_errors( array $resource_data ): array {
|
||||
$errors = array();
|
||||
|
||||
// Validate the required URI field.
|
||||
if ( empty( $resource_data['uri'] ) || ! is_string( $resource_data['uri'] ) ) {
|
||||
$errors[] = __( 'Resource URI is required and must be a non-empty string', 'mcp-adapter' );
|
||||
} elseif ( ! McpValidator::validate_resource_uri( $resource_data['uri'] ) ) {
|
||||
$errors[] = __( 'Resource URI must be a valid URI format', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate content: at least one of text/blob must be present and correctly typed.
|
||||
// Use array_key_exists to allow empty strings as valid content.
|
||||
$has_text_key = array_key_exists( 'text', $resource_data );
|
||||
$has_blob_key = array_key_exists( 'blob', $resource_data );
|
||||
|
||||
$has_text = $has_text_key && is_string( $resource_data['text'] );
|
||||
$has_blob = $has_blob_key && is_string( $resource_data['blob'] );
|
||||
|
||||
if ( ! $has_text && ! $has_blob ) {
|
||||
$errors[] = __( 'Resource contents must include at least one of: text (string) or blob (base64 string)', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
if ( $has_text_key && ! is_string( $resource_data['text'] ) ) {
|
||||
$errors[] = __( 'Resource text content must be a string when provided', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
if ( $has_blob_key && ! is_string( $resource_data['blob'] ) ) {
|
||||
$errors[] = __( 'Resource blob content must be a string when provided', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate blob content if present and typed.
|
||||
if ( $has_blob && ! McpValidator::validate_base64( $resource_data['blob'] ) ) {
|
||||
$errors[] = __( 'Resource blob content must be valid base64-encoded data', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate mimeType if present (optional).
|
||||
if ( isset( $resource_data['mimeType'] ) ) {
|
||||
if ( ! is_string( $resource_data['mimeType'] ) ) {
|
||||
$errors[] = __( 'Resource mimeType must be a string if provided', 'mcp-adapter' );
|
||||
} elseif ( ! McpValidator::validate_mime_type( $resource_data['mimeType'] ) ) {
|
||||
$errors[] = __( 'Resource mimeType must be a valid MIME type format', 'mcp-adapter' );
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format icon validation errors from the validation result.
|
||||
*
|
||||
* @param array{valid: array, errors: array} $icons_result The result from validate_icons_array.
|
||||
*
|
||||
* @return array Array of formatted error messages.
|
||||
*/
|
||||
private static function format_icon_validation_errors( array $icons_result ): array {
|
||||
$errors = array();
|
||||
|
||||
if ( ! empty( $icons_result['errors'] ) ) {
|
||||
foreach ( $icons_result['errors'] as $error_group ) {
|
||||
foreach ( $error_group['errors'] as $error ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: 1: icon index, 2: error message */
|
||||
__( 'Icon at index %1$d: %2$s', 'mcp-adapter' ),
|
||||
$error_group['index'],
|
||||
$error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
}
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* RegisterAbilityAsMcpResource class for converting WordPress abilities to MCP resources.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Resources;
|
||||
|
||||
use WP\MCP\Domain\Utils\McpAnnotationMapper;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface;
|
||||
use WP\McpSchema\Server\Resources\DTO\Resource as ResourceDto;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Converts WordPress abilities to MCP Resource metadata.
|
||||
*
|
||||
* This class builds Resource DTOs for resources/list responses.
|
||||
* It extracts metadata only (uri, name, title, description, mimeType, size, icons, annotations).
|
||||
* Resource content (text/blob) is resolved separately at resources/read time.
|
||||
*
|
||||
* All MCP-specific ability meta should be under 'mcp' key:
|
||||
*
|
||||
* Required ability meta:
|
||||
* - 'mcp.uri' (string): The resource URI (RFC 3986 format)
|
||||
*
|
||||
* Optional ability meta:
|
||||
* - 'mcp.mimeType' (string): MIME type of the resource content
|
||||
* - 'mcp.size' (int): Size of resource content in bytes
|
||||
* - 'mcp.annotations' (array): MCP annotations (audience, priority, lastModified)
|
||||
* - 'mcp.icons' (array): Array of icon objects for UI display
|
||||
* - 'mcp._meta' (array): User-provided metadata to pass through
|
||||
*
|
||||
* Note: Top-level meta keys 'uri', 'mimeType', 'annotations' are deprecated as of 0.5.0.
|
||||
* They still work for backward compatibility but will trigger a `_doing_it_wrong` notice.
|
||||
* Use 'mcp.uri', 'mcp.mimeType', 'mcp.annotations' instead.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
class RegisterAbilityAsMcpResource {
|
||||
|
||||
/**
|
||||
* The WordPress ability instance.
|
||||
*
|
||||
* @var \WP_Ability
|
||||
*/
|
||||
private \WP_Ability $ability;
|
||||
|
||||
/**
|
||||
* Optional error handler for logging deprecation notices.
|
||||
*
|
||||
* @var \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface|null
|
||||
*/
|
||||
private ?McpErrorHandlerInterface $error_handler;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
* @param \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface|null $error_handler Optional error handler.
|
||||
*/
|
||||
private function __construct( \WP_Ability $ability, ?McpErrorHandlerInterface $error_handler = null ) {
|
||||
$this->ability = $ability;
|
||||
$this->error_handler = $error_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make a new instance of the class.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
* @param \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface|null $error_handler Optional error handler for logging.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Resources\DTO\Resource|\WP_Error Returns Resource DTO or WP_Error if validation fails.
|
||||
*/
|
||||
public static function make( \WP_Ability $ability, ?McpErrorHandlerInterface $error_handler = null ) {
|
||||
$resource = new self( $ability, $error_handler );
|
||||
|
||||
return $resource->get_resource();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the MCP resource instance.
|
||||
*
|
||||
* Resource schema validity is enforced by the php-mcp-schema DTO constructor.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Resources\DTO\Resource|\WP_Error Returns the Resource DTO or WP_Error if validation fails.
|
||||
*/
|
||||
private function get_resource() {
|
||||
$data = $this->get_data();
|
||||
if ( is_wp_error( $data ) ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
try {
|
||||
return ResourceDto::fromArray( $data );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'mcp_resource_schema_invalid',
|
||||
$e->getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the MCP resource data array.
|
||||
*
|
||||
* Builds metadata-only Resource data. Content (text/blob) is NOT included here;
|
||||
* content is resolved at resources/read time by ResourcesHandler.
|
||||
*
|
||||
* @return array<string,mixed>|\WP_Error Resource data array or WP_Error if validation fails.
|
||||
*/
|
||||
private function get_data() {
|
||||
$built = $this->build_resource_data();
|
||||
if ( is_wp_error( $built ) ) {
|
||||
return $built;
|
||||
}
|
||||
|
||||
return $built['resource_data'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Resource DTO data and adapter metadata.
|
||||
*
|
||||
* @return array{resource_data: array<string, mixed>, adapter_meta: array<string, mixed>}|\WP_Error
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function build_resource_data() {
|
||||
$uri = $this->get_uri();
|
||||
if ( is_wp_error( $uri ) ) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
$ability_meta = $this->ability->get_meta();
|
||||
$mcp_meta = $ability_meta['mcp'] ?? array();
|
||||
|
||||
// Required fields.
|
||||
$resource_data = array(
|
||||
'name' => $this->resolve_resource_name(),
|
||||
'uri' => $uri,
|
||||
);
|
||||
|
||||
// Optional: title from ability label (human-readable display name).
|
||||
$label = trim( $this->ability->get_label() );
|
||||
if ( '' !== $label ) {
|
||||
$resource_data['title'] = $label;
|
||||
}
|
||||
|
||||
// Optional: description.
|
||||
$description = trim( $this->ability->get_description() );
|
||||
if ( '' !== $description ) {
|
||||
$resource_data['description'] = $description;
|
||||
}
|
||||
|
||||
// Optional: mimeType from ability meta (with validation).
|
||||
$mime_type = $this->get_mcp_meta( 'mimeType', 'string' );
|
||||
if ( null !== $mime_type ) {
|
||||
$mime_type = trim( $mime_type );
|
||||
if ( McpValidator::validate_mime_type( $mime_type ) ) {
|
||||
$resource_data['mimeType'] = $mime_type;
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: size from ability meta (bytes count for UI display).
|
||||
$size = $this->get_mcp_meta( 'size', 'int' );
|
||||
if ( null !== $size && $size > 0 ) {
|
||||
$resource_data['size'] = $size;
|
||||
}
|
||||
|
||||
// Optional: annotations from ability meta (standardized location: mcp.annotations).
|
||||
$annotations = $this->get_mcp_meta( 'annotations', 'array' );
|
||||
if ( null !== $annotations ) {
|
||||
$mcp_annotations = McpAnnotationMapper::map( $annotations, 'resource' );
|
||||
if ( ! empty( $mcp_annotations ) ) {
|
||||
// Validate annotation values per MCP specification.
|
||||
$validation_errors = McpValidator::get_annotation_validation_errors( $mcp_annotations );
|
||||
if ( ! empty( $validation_errors ) ) {
|
||||
// Log the issue but don't fail registration - drop invalid annotations.
|
||||
$this->log_deprecation(
|
||||
self::class . '::get_data',
|
||||
sprintf(
|
||||
/* translators: 1: ability name, 2: validation errors */
|
||||
__( 'Invalid annotations for resource ability "%1$s" will be dropped: %2$s', 'mcp-adapter' ),
|
||||
$this->ability->get_name(),
|
||||
implode( '; ', $validation_errors )
|
||||
),
|
||||
array( 'validation_errors' => $validation_errors )
|
||||
);
|
||||
} else {
|
||||
$resource_data['annotations'] = $mcp_annotations;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: icons from mcp.icons (already in correct location).
|
||||
if ( ! empty( $mcp_meta['icons'] ) && is_array( $mcp_meta['icons'] ) ) {
|
||||
$icons_result = McpValidator::validate_icons_array( $mcp_meta['icons'] );
|
||||
if ( ! empty( $icons_result['valid'] ) ) {
|
||||
$resource_data['icons'] = $icons_result['valid'];
|
||||
}
|
||||
}
|
||||
|
||||
// Build Resource `_meta`:
|
||||
// - Preserve user-provided `_meta` from ability.meta.mcp._meta.
|
||||
// - Adapter metadata is NEVER included in protocol DTO meta; it is returned separately in adapter_meta.
|
||||
$resource_meta = array();
|
||||
if ( ! empty( $mcp_meta['_meta'] ) && is_array( $mcp_meta['_meta'] ) ) {
|
||||
$resource_meta = $mcp_meta['_meta'];
|
||||
}
|
||||
if ( ! empty( $resource_meta ) ) {
|
||||
$resource_data['_meta'] = $resource_meta;
|
||||
}
|
||||
|
||||
$adapter_meta = array(
|
||||
'ability' => $this->ability->get_name(),
|
||||
);
|
||||
|
||||
return array(
|
||||
'resource_data' => $resource_data,
|
||||
'adapter_meta' => $adapter_meta,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the resource URI with validation.
|
||||
*
|
||||
* @return string|\WP_Error URI string or WP_Error if not found or invalid.
|
||||
*/
|
||||
private function get_uri() {
|
||||
$uri = $this->get_mcp_meta( 'uri', 'string' );
|
||||
|
||||
if ( null === $uri ) {
|
||||
return new WP_Error(
|
||||
'resource_uri_not_found',
|
||||
sprintf(
|
||||
/* translators: %s: ability name */
|
||||
__( "Resource URI not found in ability meta for '%s'. URI must be provided at 'mcp.uri'.", 'mcp-adapter' ),
|
||||
$this->ability->get_name()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$uri = trim( $uri );
|
||||
|
||||
// Validate URI format (RFC 3986).
|
||||
if ( ! McpValidator::validate_resource_uri( $uri ) ) {
|
||||
return new WP_Error(
|
||||
'resource_uri_invalid',
|
||||
sprintf(
|
||||
/* translators: 1: ability name, 2: invalid URI */
|
||||
__( "Invalid resource URI '%2\$s' for ability '%1\$s'. URI must be RFC 3986 compliant with a scheme.", 'mcp-adapter' ),
|
||||
$this->ability->get_name(),
|
||||
$uri
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the MCP resource URI derived from an ability.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $uri The validated resource URI.
|
||||
* @param \WP_Ability $ability The source ability instance.
|
||||
*/
|
||||
$filtered_uri = apply_filters( 'mcp_adapter_resource_uri', $uri, $this->ability );
|
||||
|
||||
// Validate post-filter.
|
||||
if ( ! is_string( $filtered_uri ) || ! McpValidator::validate_resource_uri( $filtered_uri ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_resource_uri_filter_invalid',
|
||||
sprintf(
|
||||
/* translators: %s: invalid URI returned by filter */
|
||||
__( 'Filter returned invalid MCP resource URI: %s', 'mcp-adapter' ),
|
||||
is_string( $filtered_uri ) ? $filtered_uri : gettype( $filtered_uri )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $filtered_uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a value from ability meta with standardized lookup.
|
||||
*
|
||||
* Looks in 'mcp' namespace first (preferred), then falls back to top-level (deprecated).
|
||||
* Logs deprecation notice when using top-level location.
|
||||
*
|
||||
* @param string $key The key to look up.
|
||||
* @param string $type Expected type: 'string', 'int', 'array'.
|
||||
* @param mixed $default_value Default value if not found.
|
||||
*
|
||||
* @return mixed The value or default.
|
||||
*/
|
||||
private function get_mcp_meta( string $key, string $type = 'string', $default_value = null ) {
|
||||
$ability_meta = $this->ability->get_meta();
|
||||
$mcp_meta = $ability_meta['mcp'] ?? array();
|
||||
|
||||
// Preferred: Check mcp.{key} first.
|
||||
if ( isset( $mcp_meta[ $key ] ) ) {
|
||||
$value = $mcp_meta[ $key ];
|
||||
if ( $this->validate_type( $value, $type ) ) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
// Deprecated fallback: Check top-level meta.{key}.
|
||||
if ( isset( $ability_meta[ $key ] ) ) {
|
||||
$value = $ability_meta[ $key ];
|
||||
if ( $this->validate_type( $value, $type ) ) {
|
||||
// Log deprecation notice.
|
||||
$this->log_deprecation(
|
||||
__METHOD__,
|
||||
sprintf(
|
||||
/* translators: 1: deprecated meta key, 2: new meta key path */
|
||||
__( 'Ability meta key "%1$s" is deprecated. Use "mcp.%1$s" instead.', 'mcp-adapter' ),
|
||||
$key
|
||||
),
|
||||
array( 'deprecated_key' => $key )
|
||||
);
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $default_value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a value against expected type.
|
||||
*
|
||||
* @param mixed $value The value to validate.
|
||||
* @param string $type Expected type.
|
||||
*
|
||||
* @return bool True if valid.
|
||||
*/
|
||||
private function validate_type( $value, string $type ): bool {
|
||||
switch ( $type ) {
|
||||
case 'string':
|
||||
return is_string( $value ) && '' !== trim( $value );
|
||||
case 'int':
|
||||
return is_int( $value ) && $value >= 0;
|
||||
case 'array':
|
||||
// Array must be non-empty AND have at least one non-null, non-empty value.
|
||||
// This prevents false positives when WordPress adds default empty annotations.
|
||||
if ( ! is_array( $value ) || empty( $value ) ) {
|
||||
return false;
|
||||
}
|
||||
// Check if any value in the array is actually meaningful (non-null, non-empty string).
|
||||
foreach ( $value as $item ) {
|
||||
if ( null !== $item && '' !== $item && array() !== $item ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log a deprecation notice via both WordPress _doing_it_wrong and McpErrorHandler.
|
||||
*
|
||||
* This ensures deprecation notices are visible both as HTTP headers (WordPress REST API)
|
||||
* and in debug.log (McpErrorHandler).
|
||||
*
|
||||
* @param string $method The method name where deprecation occurred.
|
||||
* @param string $message The deprecation message.
|
||||
* @param array $context Additional context for error handler.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function log_deprecation( string $method, string $message, array $context = array() ): void {
|
||||
// WordPress standard deprecation notice (appears as X-WP-DoingItWrong header in REST API).
|
||||
_doing_it_wrong( esc_html( $method ), esc_html( $message ), '0.5.0' );
|
||||
|
||||
// Also log via McpErrorHandler for debug.log visibility.
|
||||
if ( ! $this->error_handler ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->error_handler->log(
|
||||
$message,
|
||||
array_merge(
|
||||
array( 'ability' => $this->ability->get_name() ),
|
||||
$context
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the MCP resource name from ability.
|
||||
*
|
||||
* Resource names have no charset restrictions (unlike Tool names).
|
||||
*
|
||||
* @return string The resolved resource name.
|
||||
*/
|
||||
private function resolve_resource_name(): string {
|
||||
$name = $this->ability->get_name();
|
||||
|
||||
/**
|
||||
* Filters the MCP resource name derived from an ability.
|
||||
*
|
||||
* Unlike tools, resource names have no charset restrictions.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $name The resource name.
|
||||
* @param \WP_Ability $ability The source ability instance.
|
||||
*/
|
||||
$filtered_name = apply_filters( 'mcp_adapter_resource_name', $name, $this->ability );
|
||||
|
||||
// Resource names have no charset restrictions, so just ensure it's a non-empty string.
|
||||
if ( is_string( $filtered_name ) && '' !== trim( $filtered_name ) ) {
|
||||
return $filtered_name;
|
||||
}
|
||||
|
||||
// Fall back to original name if filter returns invalid value.
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a clean Resource DTO and adapter metadata for internal wiring.
|
||||
*
|
||||
* This method returns a protocol-only Resource DTO and provides the adapter metadata
|
||||
* separately. This keeps the DTO stable across MCP spec changes and avoids coupling internal execution
|
||||
* wiring to protocol surfaces.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
* @param \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface|null $error_handler Optional error handler.
|
||||
*
|
||||
* @return array{resource: \WP\McpSchema\Server\Resources\DTO\Resource, adapter_meta: array<string, mixed>}|\WP_Error
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function build( \WP_Ability $ability, ?McpErrorHandlerInterface $error_handler = null ) {
|
||||
$resource = new self( $ability, $error_handler );
|
||||
$data = $resource->build_resource_data();
|
||||
|
||||
if ( is_wp_error( $data ) ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
try {
|
||||
$resource_dto = ResourceDto::fromArray( $data['resource_data'] );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'mcp_resource_dto_creation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: error message */
|
||||
__( 'Failed to create Resource DTO for ability %1$s: %2$s', 'mcp-adapter' ),
|
||||
$ability->get_name(),
|
||||
$e->getMessage()
|
||||
),
|
||||
array( 'exception' => $e )
|
||||
);
|
||||
}
|
||||
|
||||
// Optional deep validation if enabled.
|
||||
$mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false );
|
||||
if ( $mcp_validation_enabled ) {
|
||||
$validation_result = McpResourceValidator::validate_resource_dto( $resource_dto );
|
||||
if ( is_wp_error( $validation_result ) ) {
|
||||
return $validation_result;
|
||||
}
|
||||
}
|
||||
|
||||
return array(
|
||||
'resource' => $resource_dto,
|
||||
'adapter_meta' => $data['adapter_meta'],
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+416
@@ -0,0 +1,416 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MCP Tool component.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Tools;
|
||||
|
||||
use WP\MCP\Domain\Contracts\McpComponentInterface;
|
||||
use WP\MCP\Domain\Utils\AbilityArgumentNormalizer;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\MCP\Infrastructure\Observability\FailureReason;
|
||||
use WP\McpSchema\Server\Tools\DTO\Tool as ToolDto;
|
||||
use WP\McpSchema\Server\Tools\DTO\ToolAnnotations;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Tool component providing unified execution and permission checks.
|
||||
*
|
||||
* This class provides multiple flexible ways to create MCP tools:
|
||||
*
|
||||
* 1. Array configuration:
|
||||
* ```php
|
||||
* $tool = McpTool::fromArray([
|
||||
* 'name' => 'uppercase-text',
|
||||
* 'title' => 'Uppercase Text',
|
||||
* 'description' => 'Converts text to uppercase',
|
||||
* 'inputSchema' => ['type' => 'object', 'properties' => [...]],
|
||||
* 'handler' => fn($args) => ['result' => strtoupper($args['text'])],
|
||||
* 'permission' => fn() => true,
|
||||
* 'annotations' => ['readOnlyHint' => true],
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* 2. From WordPress Ability (ability-backed):
|
||||
* ```php
|
||||
* $tool = McpTool::fromAbility($ability);
|
||||
* ```
|
||||
*
|
||||
* McpTool wraps a protocol-only ToolDto for MCP serialization. Internal
|
||||
* adapter metadata and execution wiring live on this class and are never
|
||||
* exposed to MCP clients. Use get_protocol_dto() for protocol responses.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
final class McpTool implements McpComponentInterface {
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// Runtime Properties
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Clean Tool DTO (protocol-only).
|
||||
*
|
||||
* @var \WP\McpSchema\Server\Tools\DTO\Tool
|
||||
*/
|
||||
private ToolDto $tool;
|
||||
|
||||
/**
|
||||
* Ability used for execution/permission checks (ability-backed tools).
|
||||
*
|
||||
* @var \WP_Ability|null
|
||||
*/
|
||||
private ?\WP_Ability $ability = null;
|
||||
|
||||
/**
|
||||
* Direct execution handler (callable-backed tools).
|
||||
*
|
||||
* @var callable|null
|
||||
*/
|
||||
private $handler = null;
|
||||
|
||||
/**
|
||||
* Direct permission callback (callable-backed tools).
|
||||
*
|
||||
* @var callable|null
|
||||
*/
|
||||
private $permission_callback = null;
|
||||
|
||||
/**
|
||||
* Internal adapter metadata (never exposed to clients).
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $adapter_meta = array();
|
||||
|
||||
/**
|
||||
* Observability context tags for logging/metrics.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private array $observability_context = array();
|
||||
|
||||
// =========================================================================
|
||||
// Constructor
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Private constructor - use factory methods.
|
||||
*
|
||||
* @param \WP\McpSchema\Server\Tools\DTO\Tool $tool The Tool DTO.
|
||||
*/
|
||||
private function __construct( ToolDto $tool ) {
|
||||
$this->tool = $tool;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Factory Methods
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Create a tool definition from an array configuration.
|
||||
*
|
||||
* @param array $config The tool configuration array.
|
||||
*
|
||||
* @return self|\WP_Error
|
||||
*/
|
||||
public static function fromArray( array $config ) {
|
||||
if ( empty( $config['name'] ) ) {
|
||||
return new WP_Error( 'mcp_tool_missing_name', 'Tool configuration must include a "name" field.' );
|
||||
}
|
||||
|
||||
if ( ! isset( $config['handler'] ) || ! is_callable( $config['handler'] ) ) {
|
||||
return new WP_Error( 'mcp_tool_missing_handler', 'Tool configuration must include a callable "handler" field.' );
|
||||
}
|
||||
|
||||
// Prepare input schema - ensure it's an object type for MCP compliance.
|
||||
$input_schema = $config['inputSchema'] ?? array( 'type' => 'object' );
|
||||
if ( ! isset( $input_schema['type'] ) ) {
|
||||
$input_schema['type'] = 'object';
|
||||
}
|
||||
|
||||
// Build tool data array.
|
||||
$tool_data = array(
|
||||
'name' => $config['name'],
|
||||
'inputSchema' => $input_schema,
|
||||
);
|
||||
|
||||
// Optional fields.
|
||||
if ( isset( $config['title'] ) ) {
|
||||
$tool_data['title'] = $config['title'];
|
||||
}
|
||||
|
||||
if ( isset( $config['description'] ) ) {
|
||||
$tool_data['description'] = $config['description'];
|
||||
}
|
||||
|
||||
if ( isset( $config['outputSchema'] ) && is_array( $config['outputSchema'] ) ) {
|
||||
$tool_data['outputSchema'] = $config['outputSchema'];
|
||||
}
|
||||
|
||||
// Validate and prepare icons if set.
|
||||
if ( isset( $config['icons'] ) && is_array( $config['icons'] ) && ! empty( $config['icons'] ) ) {
|
||||
$icons_result = McpValidator::validate_icons_array( $config['icons'] );
|
||||
if ( ! empty( $icons_result['valid'] ) ) {
|
||||
$tool_data['icons'] = $icons_result['valid'];
|
||||
}
|
||||
}
|
||||
|
||||
// Preserve user-provided _meta as-is.
|
||||
if ( isset( $config['meta'] ) && is_array( $config['meta'] ) && ! empty( $config['meta'] ) ) {
|
||||
$tool_data['_meta'] = $config['meta'];
|
||||
}
|
||||
|
||||
// Create the Tool DTO - wrap in try-catch since ToolAnnotations::fromArray() and ToolDto::fromArray() can throw.
|
||||
try {
|
||||
// Process annotations inside try-catch since ToolAnnotations::fromArray() can throw.
|
||||
if ( isset( $config['annotations'] ) && is_array( $config['annotations'] ) && ! empty( $config['annotations'] ) ) {
|
||||
$tool_data['annotations'] = ToolAnnotations::fromArray( $config['annotations'] );
|
||||
}
|
||||
|
||||
$tool = ToolDto::fromArray( $tool_data );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'mcp_tool_dto_creation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: error message */
|
||||
__( 'Failed to create Tool DTO: %s', 'mcp-adapter' ),
|
||||
$e->getMessage()
|
||||
),
|
||||
array( 'exception' => $e )
|
||||
);
|
||||
}
|
||||
|
||||
// Optional deep validation if enabled.
|
||||
$mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false );
|
||||
if ( $mcp_validation_enabled ) {
|
||||
$validation_result = McpToolValidator::validate_tool_dto( $tool );
|
||||
if ( is_wp_error( $validation_result ) ) {
|
||||
return $validation_result;
|
||||
}
|
||||
}
|
||||
|
||||
$instance = new self( $tool );
|
||||
$instance->handler = $config['handler'];
|
||||
|
||||
if ( isset( $config['permission'] ) && is_callable( $config['permission'] ) ) {
|
||||
$instance->permission_callback = $config['permission'];
|
||||
}
|
||||
|
||||
$instance->observability_context = array(
|
||||
'component_type' => 'tool',
|
||||
'tool_name' => $config['name'],
|
||||
'source' => 'array',
|
||||
);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ability-backed MCP tool.
|
||||
*
|
||||
* @param \WP_Ability $ability WordPress ability.
|
||||
*
|
||||
* @return self|\WP_Error
|
||||
*/
|
||||
public static function fromAbility( \WP_Ability $ability ) {
|
||||
$tool_data = RegisterAbilityAsMcpTool::build( $ability );
|
||||
if ( $tool_data instanceof WP_Error ) {
|
||||
return $tool_data;
|
||||
}
|
||||
|
||||
$instance = new self( $tool_data['tool'] );
|
||||
$instance->adapter_meta = $tool_data['adapter_meta'];
|
||||
$instance->ability = $ability;
|
||||
|
||||
$instance->observability_context = array(
|
||||
'component_type' => 'tool',
|
||||
'tool_name' => $tool_data['tool']->getName(),
|
||||
'ability_name' => $ability->get_name(),
|
||||
'source' => 'ability',
|
||||
);
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// McpComponentInterface Implementation
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get the clean protocol DTO for MCP responses.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Tools\DTO\Tool
|
||||
*/
|
||||
public function get_protocol_dto(): ToolDto {
|
||||
return $this->tool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the tool.
|
||||
*
|
||||
* @param mixed $arguments Tool arguments.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function execute( $arguments ) {
|
||||
$args = $this->unwrap_input_if_needed( $arguments );
|
||||
|
||||
if ( null !== $this->ability ) {
|
||||
$args = AbilityArgumentNormalizer::normalize( $this->ability, $args );
|
||||
|
||||
try {
|
||||
$result = $this->ability->execute( $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_execution_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
} elseif ( null !== $this->handler ) {
|
||||
try {
|
||||
$result = call_user_func( $this->handler, $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_execution_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
} else {
|
||||
return new WP_Error( 'mcp_tool_no_handler', 'No tool execution strategy configured.' );
|
||||
}
|
||||
|
||||
if ( $result instanceof WP_Error ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$result = $this->wrap_output_if_needed( $result );
|
||||
|
||||
if ( ! is_array( $result ) ) {
|
||||
$result = array( 'result' => $result );
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwrap tool input arguments when the input schema was transformed (flattened → object wrapper).
|
||||
*
|
||||
* @param mixed $arguments Raw tool arguments.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
private function unwrap_input_if_needed( $arguments ) {
|
||||
$is_transformed = true === ( $this->adapter_meta['input_schema_transformed'] ?? false );
|
||||
|
||||
if ( ! $is_transformed ) {
|
||||
return $arguments;
|
||||
}
|
||||
|
||||
$wrapper = $this->adapter_meta['input_schema_wrapper'] ?? 'input';
|
||||
$wrapper = is_string( $wrapper ) && '' !== trim( $wrapper ) ? $wrapper : 'input';
|
||||
|
||||
return is_array( $arguments ) ? ( $arguments[ $wrapper ] ?? null ) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap tool results when the output schema was transformed (flattened → object wrapper).
|
||||
*
|
||||
* @param mixed $result Raw result.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
private function wrap_output_if_needed( $result ) {
|
||||
$is_transformed = true === ( $this->adapter_meta['output_schema_transformed'] ?? false );
|
||||
|
||||
if ( ! $is_transformed ) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$wrapper = $this->adapter_meta['output_schema_wrapper'] ?? 'result';
|
||||
$wrapper = is_string( $wrapper ) && '' !== trim( $wrapper ) ? $wrapper : 'result';
|
||||
|
||||
return array( $wrapper => $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the current request has permission to execute this tool.
|
||||
*
|
||||
* @param mixed $arguments Tool arguments.
|
||||
*
|
||||
* @return bool|\WP_Error
|
||||
*/
|
||||
public function check_permission( $arguments ) {
|
||||
$args = $this->unwrap_input_if_needed( $arguments );
|
||||
|
||||
// Ability-backed tools delegate to the ability's permission system.
|
||||
if ( null !== $this->ability ) {
|
||||
$args = AbilityArgumentNormalizer::normalize( $this->ability, $args );
|
||||
|
||||
try {
|
||||
return $this->ability->check_permissions( $args );
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_permission_check_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Callable-backed tools use their required permission callback.
|
||||
if ( null !== $this->permission_callback ) {
|
||||
try {
|
||||
$result = call_user_func( $this->permission_callback, $args );
|
||||
|
||||
return $result instanceof WP_Error ? $result : (bool) $result;
|
||||
} catch ( \Throwable $throwable ) {
|
||||
return new WP_Error(
|
||||
'mcp_permission_check_failed',
|
||||
$throwable->getMessage(),
|
||||
array( 'error_type' => get_class( $throwable ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Defensive fallback: should never reach here if factories are used correctly.
|
||||
return new WP_Error(
|
||||
'mcp_permission_denied',
|
||||
'Access denied.',
|
||||
array(
|
||||
'failure_reason' => FailureReason::NO_PERMISSION_STRATEGY,
|
||||
'tool_name' => $this->tool->getName(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Private Helper Methods
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get internal adapter metadata for this tool.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function get_adapter_meta(): array {
|
||||
return $this->adapter_meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get observability context tags for logging/metrics.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function get_observability_context(): array {
|
||||
return $this->observability_context;
|
||||
}
|
||||
}
|
||||
+482
@@ -0,0 +1,482 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Tool Validator class for validating MCP tools according to the specification.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Tools;
|
||||
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\McpSchema\Server\Tools\DTO\Tool as ToolDto;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Validates MCP tools against the Model Context Protocol specification.
|
||||
*
|
||||
* Provides minimal, resource-efficient validation to ensure tools conform
|
||||
* to the MCP schema requirements without heavy processing overhead.
|
||||
*
|
||||
* @link https://modelcontextprotocol.io/specification/2025-11-25/server/tools
|
||||
*/
|
||||
class McpToolValidator {
|
||||
|
||||
/**
|
||||
* Valid task support values for tool execution.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
private static array $valid_task_support_values = array(
|
||||
'forbidden',
|
||||
'optional',
|
||||
'required',
|
||||
);
|
||||
|
||||
/**
|
||||
* Validate the MCP tool data array against the MCP schema.
|
||||
*
|
||||
* @param array $tool_data The tool data to validate.
|
||||
* @param string $context Optional context for error messages.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
public static function validate_tool_data( array $tool_data, string $context = '' ) {
|
||||
$validation_errors = self::get_validation_errors( $tool_data );
|
||||
|
||||
if ( ! empty( $validation_errors ) ) {
|
||||
$error_message = $context ? "[$context] " : '';
|
||||
$error_message .= sprintf(
|
||||
/* translators: %s: comma-separated list of validation errors */
|
||||
__( 'Tool validation failed: %s', 'mcp-adapter' ),
|
||||
implode( ', ', $validation_errors )
|
||||
);
|
||||
return new WP_Error( 'mcp_tool_validation_failed', esc_html( $error_message ) );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an McpTool instance against the MCP schema.
|
||||
*
|
||||
* @param \WP\MCP\Domain\Tools\McpTool $tool The tool instance to validate.
|
||||
* @param string $context Optional context for error messages.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error if validation fails.
|
||||
*/
|
||||
public static function validate_tool_instance( McpTool $tool, string $context = '' ) {
|
||||
return self::validate_tool_data( $tool->get_protocol_dto()->toArray(), $context );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a Tool DTO against the MCP schema.
|
||||
*
|
||||
* @param \WP\McpSchema\Server\Tools\DTO\Tool $tool The tool DTO to validate.
|
||||
*
|
||||
* @return bool|\WP_Error True if valid, WP_Error otherwise.
|
||||
*/
|
||||
public static function validate_tool_dto( ToolDto $tool ) {
|
||||
$errors = array();
|
||||
|
||||
// Validate name (required, 1-128 chars, alphanumeric + _.-).
|
||||
if ( ! McpValidator::validate_name( $tool->getName() ) ) {
|
||||
$errors[] = __( 'Tool name must be 1-128 characters and contain only [A-Za-z0-9_.-]', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate icons if present.
|
||||
$icons = $tool->getIcons();
|
||||
if ( ! empty( $icons ) ) {
|
||||
// Convert DTO icons to arrays for validation.
|
||||
$icons_array = array_map( static fn( $icon ) => $icon->toArray(), $icons );
|
||||
$icons_result = McpValidator::validate_icons_array( $icons_array );
|
||||
$icons_errors = self::format_icon_validation_errors( $icons_result );
|
||||
$errors = array_merge( $errors, $icons_errors );
|
||||
}
|
||||
|
||||
// Validate annotations if present (tool-specific only).
|
||||
$annotations = $tool->getAnnotations();
|
||||
if ( $annotations ) {
|
||||
$annotations_array = $annotations->toArray();
|
||||
$annotation_errors = self::get_tool_annotation_validation_errors( $annotations_array );
|
||||
$errors = array_merge( $errors, $annotation_errors );
|
||||
}
|
||||
|
||||
// Validate execution if present.
|
||||
$execution = $tool->getExecution();
|
||||
if ( $execution ) {
|
||||
$execution_array = $execution->toArray();
|
||||
$execution_errors = self::get_execution_validation_errors( $execution_array );
|
||||
$errors = array_merge( $errors, $execution_errors );
|
||||
}
|
||||
|
||||
// Validate schemas (inputSchema and outputSchema).
|
||||
$tool_array = $tool->toArray();
|
||||
|
||||
// Validate inputSchema (required field).
|
||||
$input_schema_errors = self::get_schema_validation_errors(
|
||||
$tool_array['inputSchema'] ?? null,
|
||||
'inputSchema'
|
||||
);
|
||||
$errors = array_merge( $errors, $input_schema_errors );
|
||||
|
||||
// Validate outputSchema if present (optional field).
|
||||
if ( isset( $tool_array['outputSchema'] ) ) {
|
||||
$output_schema_errors = self::get_schema_validation_errors(
|
||||
$tool_array['outputSchema'],
|
||||
'outputSchema'
|
||||
);
|
||||
$errors = array_merge( $errors, $output_schema_errors );
|
||||
}
|
||||
|
||||
if ( ! empty( $errors ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_tool_validation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: list of validation errors */
|
||||
__( 'Tool validation failed: %s', 'mcp-adapter' ),
|
||||
implode( '; ', $errors )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation error details for debugging purposes.
|
||||
* This is the core validation method - all other validation methods use this.
|
||||
*
|
||||
* @param array $tool_data The tool data to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
public static function get_validation_errors( array $tool_data ): array {
|
||||
$errors = array();
|
||||
|
||||
// Check the required field: name.
|
||||
if ( empty( $tool_data['name'] ) || ! is_string( $tool_data['name'] ) || ! McpValidator::validate_name( $tool_data['name'] ) ) {
|
||||
$errors[] = __( 'Tool name is required and must only contain letters, numbers, hyphens (-), underscores (_), and dots (.), and be 128 characters or less', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Description is optional per MCP 2025-11-25 spec, but validate if present.
|
||||
if ( isset( $tool_data['description'] ) && ! is_string( $tool_data['description'] ) ) {
|
||||
$errors[] = __( 'Tool description must be a string if provided', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate inputSchema (required field).
|
||||
$input_schema_errors = self::get_schema_validation_errors( $tool_data['inputSchema'] ?? null, 'inputSchema' );
|
||||
if ( ! empty( $input_schema_errors ) ) {
|
||||
$errors = array_merge( $errors, $input_schema_errors );
|
||||
}
|
||||
|
||||
// Check optional fields if present.
|
||||
if ( isset( $tool_data['title'] ) && ! is_string( $tool_data['title'] ) ) {
|
||||
$errors[] = __( 'Tool title must be a string if provided', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// Validate outputSchema (optional field).
|
||||
if ( isset( $tool_data['outputSchema'] ) ) {
|
||||
$output_schema_errors = self::get_schema_validation_errors( $tool_data['outputSchema'], 'outputSchema' );
|
||||
if ( ! empty( $output_schema_errors ) ) {
|
||||
$errors = array_merge( $errors, $output_schema_errors );
|
||||
}
|
||||
}
|
||||
|
||||
// Validate icons (optional field, new in 2025-11-25).
|
||||
if ( isset( $tool_data['icons'] ) ) {
|
||||
$icons_errors = self::get_icons_validation_errors( $tool_data['icons'] );
|
||||
if ( ! empty( $icons_errors ) ) {
|
||||
$errors = array_merge( $errors, $icons_errors );
|
||||
}
|
||||
}
|
||||
|
||||
// Validate execution (optional field, new in 2025-11-25).
|
||||
if ( isset( $tool_data['execution'] ) ) {
|
||||
$execution_errors = self::get_execution_validation_errors( $tool_data['execution'] );
|
||||
if ( ! empty( $execution_errors ) ) {
|
||||
$errors = array_merge( $errors, $execution_errors );
|
||||
}
|
||||
}
|
||||
|
||||
// Validate annotations structure if present (tool-specific annotations only).
|
||||
if ( isset( $tool_data['annotations'] ) ) {
|
||||
if ( ! is_array( $tool_data['annotations'] ) ) {
|
||||
$errors[] = __( 'Tool annotations must be an array if provided', 'mcp-adapter' );
|
||||
} else {
|
||||
// Validate tool-specific annotations (readOnlyHint, destructiveHint, etc.).
|
||||
$tool_annotation_errors = self::get_tool_annotation_validation_errors( $tool_data['annotations'] );
|
||||
if ( ! empty( $tool_annotation_errors ) ) {
|
||||
$errors = array_merge( $errors, $tool_annotation_errors );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate _meta (optional field).
|
||||
if ( isset( $tool_data['_meta'] ) && ! is_array( $tool_data['_meta'] ) ) {
|
||||
$errors[] = __( 'Tool _meta must be an object/array if provided', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get detailed validation errors for a schema object.
|
||||
*
|
||||
* @param array|mixed $schema The schema to validate.
|
||||
* @param string $field_name The name of the field being validated (for error messages).
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
private static function get_schema_validation_errors( $schema, string $field_name ): array {
|
||||
// Normalize stdClass to array for validation and reject scalars/null.
|
||||
if ( $schema instanceof \stdClass ) {
|
||||
$schema = (array) $schema;
|
||||
}
|
||||
|
||||
// Schema must be an array/object - early return for performance.
|
||||
if ( ! is_array( $schema ) ) {
|
||||
return array(
|
||||
sprintf(
|
||||
/* translators: %s: field name (inputSchema or outputSchema) */
|
||||
__( 'Tool %s must be a valid JSON schema object', 'mcp-adapter' ),
|
||||
$field_name
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
$errors = array();
|
||||
|
||||
// MCP Tool inputSchema and outputSchema are currently restricted to a root type of "object".
|
||||
if ( ! isset( $schema['type'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: field name */
|
||||
__( 'Tool %s must specify a root type of \'object\'', 'mcp-adapter' ),
|
||||
$field_name
|
||||
);
|
||||
} elseif ( ! is_string( $schema['type'] ) || 'object' !== $schema['type'] ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: field name */
|
||||
__( 'Tool %s root type must be \'object\'', 'mcp-adapter' ),
|
||||
$field_name
|
||||
);
|
||||
}
|
||||
|
||||
// If properties exist, they must be an array/object.
|
||||
if ( isset( $schema['properties'] ) && ! is_array( $schema['properties'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: field name */
|
||||
__( 'Tool %s properties must be an object/array', 'mcp-adapter' ),
|
||||
$field_name
|
||||
);
|
||||
}
|
||||
|
||||
// If required exists, it must be an array.
|
||||
if ( isset( $schema['required'] ) && ! is_array( $schema['required'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: field name */
|
||||
__( 'Tool %s required field must be an array', 'mcp-adapter' ),
|
||||
$field_name
|
||||
);
|
||||
}
|
||||
|
||||
// If properties are provided, validate their basic structure.
|
||||
if ( isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) {
|
||||
foreach ( $schema['properties'] as $property_name => $property ) {
|
||||
// Normalize stdClass to array for property validation.
|
||||
if ( $property instanceof \stdClass ) {
|
||||
$property = (array) $property;
|
||||
}
|
||||
|
||||
if ( ! is_array( $property ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %1$s: field name, %2$s: property name */
|
||||
__( 'Tool %1$s property \'%2$s\' must be an object', 'mcp-adapter' ),
|
||||
$field_name,
|
||||
$property_name
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Each property should have a type (though not strictly required by JSON Schema).
|
||||
if ( ! isset( $property['type'] ) || is_string( $property['type'] ) || is_array( $property['type'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the type is neither string nor array, it's invalid.
|
||||
$errors[] = sprintf(
|
||||
/* translators: %1$s: field name, %2$s: property name */
|
||||
__( 'Tool %1$s property \'%2$s\' type must be a string or array of strings (union type)', 'mcp-adapter' ),
|
||||
$field_name,
|
||||
$property_name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If the required array is provided, validate its structure.
|
||||
if ( isset( $schema['required'] ) && is_array( $schema['required'] ) ) {
|
||||
foreach ( $schema['required'] as $required_field ) {
|
||||
if ( ! is_string( $required_field ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: field name */
|
||||
__( 'Tool %s required field names must be strings', 'mcp-adapter' ),
|
||||
$field_name
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check that required fields exist in properties (if properties are defined).
|
||||
if ( ! isset( $schema['properties'] ) || isset( $schema['properties'][ $required_field ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$errors[] = sprintf(
|
||||
/* translators: %1$s: field name, %2$s: required field */
|
||||
__( 'Tool %1$s required field \'%2$s\' does not exist in properties', 'mcp-adapter' ),
|
||||
$field_name,
|
||||
$required_field
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors for tool icons array.
|
||||
*
|
||||
* @param mixed $icons The icons data to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
private static function get_icons_validation_errors( $icons ): array {
|
||||
if ( ! is_array( $icons ) ) {
|
||||
return array( __( 'Tool icons must be an array if provided', 'mcp-adapter' ) );
|
||||
}
|
||||
|
||||
$icons_result = McpValidator::validate_icons_array( $icons, false );
|
||||
|
||||
return self::format_icon_validation_errors( $icons_result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Format icon validation errors from the validation result.
|
||||
*
|
||||
* @param array{valid: array, errors: array} $icons_result The result from validate_icons_array.
|
||||
*
|
||||
* @return array Array of formatted error messages.
|
||||
*/
|
||||
private static function format_icon_validation_errors( array $icons_result ): array {
|
||||
$errors = array();
|
||||
|
||||
if ( ! empty( $icons_result['errors'] ) ) {
|
||||
foreach ( $icons_result['errors'] as $error_group ) {
|
||||
foreach ( $error_group['errors'] as $error ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: 1: icon index, 2: error message */
|
||||
__( 'Icon at index %1$d: %2$s', 'mcp-adapter' ),
|
||||
$error_group['index'],
|
||||
$error
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors for tool execution properties.
|
||||
*
|
||||
* Validates execution-related properties per MCP 2025-11-25 specification:
|
||||
* - taskSupport must be one of: "forbidden", "optional", "required"
|
||||
*
|
||||
* @param mixed $execution The execution data to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
public static function get_execution_validation_errors( $execution ): array {
|
||||
if ( ! is_array( $execution ) ) {
|
||||
return array( __( 'Tool execution must be an object/array if provided', 'mcp-adapter' ) );
|
||||
}
|
||||
|
||||
$errors = array();
|
||||
|
||||
// Validate taskSupport if present.
|
||||
if ( isset( $execution['taskSupport'] ) ) {
|
||||
if ( ! is_string( $execution['taskSupport'] ) ) {
|
||||
$errors[] = __( 'Tool execution taskSupport must be a string', 'mcp-adapter' );
|
||||
} elseif ( ! in_array( $execution['taskSupport'], self::$valid_task_support_values, true ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: comma-separated list of valid values */
|
||||
__( 'Tool execution taskSupport must be one of: %s', 'mcp-adapter' ),
|
||||
implode( ', ', self::$valid_task_support_values )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors for tool-specific MCP annotations.
|
||||
*
|
||||
* Validates tool annotation fields per MCP 2025-11-25 specification:
|
||||
* - readOnlyHint, destructiveHint, idempotentHint, openWorldHint must be booleans
|
||||
* - title must be a non-empty string
|
||||
*
|
||||
* Note: Tools use ToolAnnotations which is different from the shared Annotations class.
|
||||
* ToolAnnotations does NOT include audience, lastModified, or priority fields.
|
||||
*
|
||||
* @param array $annotations The annotations to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
public static function get_tool_annotation_validation_errors( array $annotations ): array {
|
||||
$errors = array();
|
||||
|
||||
foreach ( $annotations as $field => $value ) {
|
||||
switch ( $field ) {
|
||||
case 'readOnlyHint':
|
||||
case 'destructiveHint':
|
||||
case 'idempotentHint':
|
||||
case 'openWorldHint':
|
||||
if ( ! is_bool( $value ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: annotation field name */
|
||||
__( 'Tool annotation field %s must be a boolean', 'mcp-adapter' ),
|
||||
$field
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'title':
|
||||
if ( ! is_string( $value ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: annotation field name */
|
||||
__( 'Tool annotation field %s must be a string', 'mcp-adapter' ),
|
||||
$field
|
||||
);
|
||||
break;
|
||||
}
|
||||
if ( empty( trim( $value ) ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: annotation field name */
|
||||
__( 'Tool annotation field %s must be a non-empty string', 'mcp-adapter' ),
|
||||
$field
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
// Unknown fields are ignored to allow forward compatibility.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* RegisterAbilityAsMcpTool class for converting WordPress abilities to MCP tools.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Tools;
|
||||
|
||||
use WP\MCP\Domain\Utils\McpAnnotationMapper;
|
||||
use WP\MCP\Domain\Utils\McpNameSanitizer;
|
||||
use WP\MCP\Domain\Utils\McpValidator;
|
||||
use WP\MCP\Domain\Utils\SchemaTransformer;
|
||||
use WP\McpSchema\Server\Tools\DTO\Tool as ToolDto;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* RegisterAbilityAsMcpTool class.
|
||||
*
|
||||
* This class registers a WordPress ability as an MCP tool.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
class RegisterAbilityAsMcpTool {
|
||||
|
||||
/**
|
||||
* The WordPress ability instance.
|
||||
*
|
||||
* @var \WP_Ability
|
||||
*/
|
||||
private \WP_Ability $ability;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
*/
|
||||
private function __construct( \WP_Ability $ability ) {
|
||||
$this->ability = $ability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a clean Tool DTO and adapter metadata for internal wiring.
|
||||
*
|
||||
* This method returns a protocol-only Tool DTO and provides the adapter metadata
|
||||
* separately. This keeps the DTO stable across MCP spec changes and avoids coupling internal execution
|
||||
* wiring to protocol surfaces.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability.
|
||||
*
|
||||
* @return array{tool: \WP\McpSchema\Server\Tools\DTO\Tool, adapter_meta: array<string, mixed>}|\WP_Error
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function build( \WP_Ability $ability ) {
|
||||
$tool = new self( $ability );
|
||||
$data = $tool->build_tool_data();
|
||||
|
||||
if ( is_wp_error( $data ) ) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
try {
|
||||
$tool_dto = ToolDto::fromArray( $data['tool_data'] );
|
||||
} catch ( \Throwable $e ) {
|
||||
return new WP_Error(
|
||||
'mcp_tool_dto_creation_failed',
|
||||
sprintf(
|
||||
/* translators: %s: error message */
|
||||
__( 'Failed to create Tool DTO for ability %1$s: %2$s', 'mcp-adapter' ),
|
||||
$ability->get_name(),
|
||||
$e->getMessage()
|
||||
),
|
||||
array( 'exception' => $e )
|
||||
);
|
||||
}
|
||||
|
||||
// Optional deep validation if enabled.
|
||||
$mcp_validation_enabled = apply_filters( 'mcp_adapter_validation_enabled', false );
|
||||
if ( $mcp_validation_enabled ) {
|
||||
$validation_result = McpToolValidator::validate_tool_dto( $tool_dto );
|
||||
if ( is_wp_error( $validation_result ) ) {
|
||||
return $validation_result;
|
||||
}
|
||||
}
|
||||
|
||||
return array(
|
||||
'tool' => $tool_dto,
|
||||
'adapter_meta' => $data['adapter_meta'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Tool DTO data and adapter metadata.
|
||||
*
|
||||
* @return array{tool_data: array<string, mixed>, adapter_meta: array<string, mixed>}|\WP_Error
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function build_tool_data() {
|
||||
// Resolve tool name first (can fail).
|
||||
$tool_name = $this->resolve_tool_name();
|
||||
if ( is_wp_error( $tool_name ) ) {
|
||||
return $tool_name;
|
||||
}
|
||||
|
||||
// Transform input schema to MCP-compatible object format.
|
||||
$input_transform = SchemaTransformer::transform_to_object_schema(
|
||||
$this->ability->get_input_schema()
|
||||
);
|
||||
|
||||
$tool_data = array(
|
||||
'name' => $tool_name,
|
||||
'description' => trim( $this->ability->get_description() ),
|
||||
'inputSchema' => $input_transform['schema'],
|
||||
);
|
||||
|
||||
// Add optional title from ability label.
|
||||
$label = $this->ability->get_label();
|
||||
$label = trim( $label );
|
||||
if ( ! empty( $label ) ) {
|
||||
$tool_data['title'] = $label;
|
||||
}
|
||||
|
||||
// Add optional output schema, transformed to object format if needed.
|
||||
$output_schema = $this->ability->get_output_schema();
|
||||
$output_transform = null;
|
||||
if ( ! empty( $output_schema ) ) {
|
||||
$output_transform = SchemaTransformer::transform_to_object_schema(
|
||||
$output_schema,
|
||||
'result'
|
||||
);
|
||||
$tool_data['outputSchema'] = $output_transform['schema'];
|
||||
}
|
||||
|
||||
// Map annotations from ability meta to MCP format using unified mapper.
|
||||
$ability_meta = $this->ability->get_meta();
|
||||
if ( ! empty( $ability_meta['annotations'] ) && is_array( $ability_meta['annotations'] ) ) {
|
||||
$mcp_annotations = McpAnnotationMapper::map( $ability_meta['annotations'], 'tool' );
|
||||
if ( ! empty( $mcp_annotations ) ) {
|
||||
$tool_data['annotations'] = $mcp_annotations;
|
||||
}
|
||||
}
|
||||
|
||||
// Set annotations.title from label if annotations exist but don't have a title.
|
||||
if ( ! empty( $label ) && isset( $tool_data['annotations'] ) && ! isset( $tool_data['annotations']['title'] ) ) {
|
||||
$tool_data['annotations']['title'] = $label;
|
||||
}
|
||||
|
||||
// Store transformation metadata as internal metadata (stripped before responding to clients).
|
||||
// Only record keys when semantically meaningful to keep metadata minimal and accurate.
|
||||
$adapter_meta = array(
|
||||
'ability' => $this->ability->get_name(),
|
||||
);
|
||||
|
||||
// Only record input transformation metadata when a wrapper was actually applied.
|
||||
if ( ! empty( $input_transform['was_transformed'] ) ) {
|
||||
$adapter_meta['input_schema_transformed'] = true;
|
||||
$adapter_meta['input_schema_wrapper'] = $input_transform['wrapper_property'];
|
||||
}
|
||||
|
||||
// Only record output transformation metadata when outputSchema exists.
|
||||
// Record wrapper only when transformation actually occurred.
|
||||
if ( null !== $output_transform && ! empty( $output_transform['was_transformed'] ) ) {
|
||||
$adapter_meta['output_schema_transformed'] = true;
|
||||
$adapter_meta['output_schema_wrapper'] = $output_transform['wrapper_property'];
|
||||
}
|
||||
|
||||
// Map icons from ability.meta.mcp.icons if present.
|
||||
$mcp_meta = $ability_meta['mcp'] ?? array();
|
||||
if ( ! empty( $mcp_meta['icons'] ) && is_array( $mcp_meta['icons'] ) ) {
|
||||
$icons_result = McpValidator::validate_icons_array( $mcp_meta['icons'] );
|
||||
if ( ! empty( $icons_result['valid'] ) ) {
|
||||
$tool_data['icons'] = $icons_result['valid'];
|
||||
}
|
||||
}
|
||||
|
||||
// Build Tool `_meta`:
|
||||
// - Preserve user-provided `_meta` from ability.meta.mcp._meta.
|
||||
// - Adapter metadata is NEVER included in protocol DTO meta; it is returned separately in adapter_meta.
|
||||
$tool_meta = array();
|
||||
if ( ! empty( $mcp_meta['_meta'] ) && is_array( $mcp_meta['_meta'] ) ) {
|
||||
$tool_meta = $mcp_meta['_meta'];
|
||||
}
|
||||
if ( ! empty( $tool_meta ) ) {
|
||||
$tool_data['_meta'] = $tool_meta;
|
||||
}
|
||||
|
||||
return array(
|
||||
'tool_data' => $tool_data,
|
||||
'adapter_meta' => $adapter_meta,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the MCP tool name from ability.
|
||||
*
|
||||
* Sanitizes the ability name to MCP-valid format, applies filter, and validates result.
|
||||
*
|
||||
* @return string|\WP_Error Valid tool name or error.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
private function resolve_tool_name() {
|
||||
// Sanitize ability name to MCP-valid format.
|
||||
$sanitized_name = McpNameSanitizer::sanitize_name( $this->ability->get_name() );
|
||||
|
||||
if ( is_wp_error( $sanitized_name ) ) {
|
||||
return $sanitized_name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the MCP tool name derived from an ability.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $name The sanitized tool name.
|
||||
* @param \WP_Ability $ability The source ability instance.
|
||||
*/
|
||||
$filtered_name = apply_filters( 'mcp_adapter_tool_name', $sanitized_name, $this->ability );
|
||||
|
||||
// Validate post-filter (in case filter broke it).
|
||||
if ( ! is_string( $filtered_name ) || ! McpValidator::validate_name( $filtered_name ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_tool_name_filter_invalid',
|
||||
sprintf(
|
||||
/* translators: %s: invalid tool name returned by filter */
|
||||
__( 'Filter returned invalid MCP tool name: %s', 'mcp-adapter' ),
|
||||
is_string( $filtered_name ) ? $filtered_name : gettype( $filtered_name )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $filtered_name;
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
/**
|
||||
* Normalizes ability arguments for MCP protocol compatibility.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Utils;
|
||||
|
||||
/**
|
||||
* Normalizes ability arguments between MCP and WordPress Abilities API.
|
||||
*
|
||||
* MCP clients send {} (empty object) for tools without arguments.
|
||||
* PHP decodes this as [] (empty array).
|
||||
* Abilities without input_schema expect null, not empty array.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
class AbilityArgumentNormalizer {
|
||||
|
||||
/**
|
||||
* Normalize parameters for an ability based on its input schema.
|
||||
*
|
||||
* If the ability has no input schema, empty arrays are converted to null.
|
||||
* This ensures compatibility with abilities that don't accept parameters.
|
||||
*
|
||||
* @param \WP_Ability $ability The ability to normalize parameters for.
|
||||
* @param mixed $parameters The parameters to normalize.
|
||||
*
|
||||
* @return mixed Normalized parameters (null if ability has no schema and params are empty).
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function normalize( \WP_Ability $ability, $parameters ) {
|
||||
$input_schema = $ability->get_input_schema();
|
||||
|
||||
if ( empty( $input_schema ) && is_array( $parameters ) && empty( $parameters ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
<?php
|
||||
/**
|
||||
* ContentBlockHelper - Factory for creating MCP content block DTOs.
|
||||
*
|
||||
* This helper provides convenience methods for constructing typed content block DTOs
|
||||
* from the php-mcp-schema library. It simplifies the creation of TextContent,
|
||||
* ImageContent, AudioContent, and EmbeddedResource instances.
|
||||
*
|
||||
* @package WP\MCP\Domain\Utils
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Utils;
|
||||
|
||||
use WP\McpSchema\Common\Content\DTO\AudioContent;
|
||||
use WP\McpSchema\Common\Content\DTO\ImageContent;
|
||||
use WP\McpSchema\Common\Content\DTO\TextContent;
|
||||
use WP\McpSchema\Common\Protocol\DTO\Annotations;
|
||||
use WP\McpSchema\Common\Protocol\DTO\BlobResourceContents;
|
||||
use WP\McpSchema\Common\Protocol\DTO\EmbeddedResource;
|
||||
use WP\McpSchema\Common\Protocol\DTO\TextResourceContents;
|
||||
use WP\McpSchema\Common\Protocol\Union\ContentBlockInterface;
|
||||
|
||||
/**
|
||||
* Helper class for creating MCP content block DTOs.
|
||||
*
|
||||
* Provides static factory methods to create typed content blocks that implement
|
||||
* ContentBlockInterface. These DTOs are used in tool call results, prompt messages,
|
||||
* and resource contents throughout the MCP protocol.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
final class ContentBlockHelper {
|
||||
|
||||
/**
|
||||
* Creates an ImageContent DTO.
|
||||
*
|
||||
* @param string $data Base64-encoded image data.
|
||||
* @param string $mime_type The MIME type of the image (e.g., 'image/png').
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\Annotations|null $annotations Optional annotations for the client.
|
||||
* @param array|null $_meta Optional metadata.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Content\DTO\ImageContent The created ImageContent DTO.
|
||||
*/
|
||||
public static function image( string $data, string $mime_type, ?Annotations $annotations = null, ?array $_meta = null ): ImageContent {
|
||||
return ImageContent::fromArray(
|
||||
array(
|
||||
'type' => ImageContent::TYPE,
|
||||
'data' => $data,
|
||||
'mimeType' => $mime_type,
|
||||
'annotations' => $annotations,
|
||||
'_meta' => $_meta,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an AudioContent DTO.
|
||||
*
|
||||
* @param string $data Base64-encoded audio data.
|
||||
* @param string $mime_type The MIME type of the audio (e.g., 'audio/mp3').
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\Annotations|null $annotations Optional annotations for the client.
|
||||
* @param array|null $_meta Optional metadata.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Content\DTO\AudioContent The created AudioContent DTO.
|
||||
*/
|
||||
public static function audio( string $data, string $mime_type, ?Annotations $annotations = null, ?array $_meta = null ): AudioContent {
|
||||
return AudioContent::fromArray(
|
||||
array(
|
||||
'type' => AudioContent::TYPE,
|
||||
'data' => $data,
|
||||
'mimeType' => $mime_type,
|
||||
'annotations' => $annotations,
|
||||
'_meta' => $_meta,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an EmbeddedResource DTO with TextResourceContents.
|
||||
*
|
||||
* Use this for embedding text-based resources (files, documents, etc.) in content.
|
||||
*
|
||||
* @param string $uri The URI of the resource.
|
||||
* @param string $text The text content of the resource.
|
||||
* @param string|null $mime_type Optional MIME type of the resource.
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\Annotations|null $annotations Optional annotations for the client.
|
||||
* @param array|null $_meta Optional metadata.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Protocol\DTO\EmbeddedResource The created EmbeddedResource DTO.
|
||||
*/
|
||||
public static function embedded_text_resource(
|
||||
string $uri,
|
||||
string $text,
|
||||
?string $mime_type = null,
|
||||
?Annotations $annotations = null,
|
||||
?array $_meta = null
|
||||
): EmbeddedResource {
|
||||
$resource = TextResourceContents::fromArray(
|
||||
array(
|
||||
'uri' => $uri,
|
||||
'text' => $text,
|
||||
'mimeType' => $mime_type,
|
||||
)
|
||||
);
|
||||
|
||||
return EmbeddedResource::fromArray(
|
||||
array(
|
||||
'type' => EmbeddedResource::TYPE,
|
||||
'resource' => $resource,
|
||||
'annotations' => $annotations,
|
||||
'_meta' => $_meta,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an EmbeddedResource DTO with BlobResourceContents.
|
||||
*
|
||||
* Use this for embedding binary resources (images, PDFs, etc.) in content.
|
||||
*
|
||||
* @param string $uri The URI of the resource.
|
||||
* @param string $blob Base64-encoded binary data.
|
||||
* @param string|null $mime_type Optional MIME type of the resource.
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\Annotations|null $annotations Optional annotations for the client.
|
||||
* @param array|null $_meta Optional metadata.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Protocol\DTO\EmbeddedResource The created EmbeddedResource DTO.
|
||||
*/
|
||||
public static function embedded_blob_resource(
|
||||
string $uri,
|
||||
string $blob,
|
||||
?string $mime_type = null,
|
||||
?Annotations $annotations = null,
|
||||
?array $_meta = null
|
||||
): EmbeddedResource {
|
||||
$resource = BlobResourceContents::fromArray(
|
||||
array(
|
||||
'uri' => $uri,
|
||||
'blob' => $blob,
|
||||
'mimeType' => $mime_type,
|
||||
)
|
||||
);
|
||||
|
||||
return EmbeddedResource::fromArray(
|
||||
array(
|
||||
'type' => EmbeddedResource::TYPE,
|
||||
'resource' => $resource,
|
||||
'annotations' => $annotations,
|
||||
'_meta' => $_meta,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a TextContent DTO for error messages.
|
||||
*
|
||||
* Convenience method for creating text content specifically for error responses.
|
||||
* This is semantically equivalent to text() but makes the intent clearer in code.
|
||||
*
|
||||
* @param string $message The error message.
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\Annotations|null $annotations Optional annotations for the client.
|
||||
* @param array|null $_meta Optional metadata.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Content\DTO\TextContent The created TextContent DTO.
|
||||
*/
|
||||
public static function error_text( string $message, ?Annotations $annotations = null, ?array $_meta = null ): TextContent {
|
||||
return self::text( $message, $annotations, $_meta );
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a TextContent DTO.
|
||||
*
|
||||
* @param string $text The text content.
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\Annotations|null $annotations Optional annotations for the client.
|
||||
* @param array|null $_meta Optional metadata.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Content\DTO\TextContent The created TextContent DTO.
|
||||
*/
|
||||
public static function text( string $text, ?Annotations $annotations = null, ?array $_meta = null ): TextContent {
|
||||
return TextContent::fromArray(
|
||||
array(
|
||||
'type' => TextContent::TYPE,
|
||||
'text' => $text,
|
||||
'annotations' => $annotations,
|
||||
'_meta' => $_meta,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a TextContent DTO with JSON-encoded data.
|
||||
*
|
||||
* Convenience method for creating text content from structured data.
|
||||
* The data is encoded as JSON and wrapped in a TextContent DTO.
|
||||
*
|
||||
* @param mixed $data The data to JSON-encode.
|
||||
* @param int $flags JSON encoding flags (default: 0).
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\Annotations|null $annotations Optional annotations for the client.
|
||||
* @param array|null $_meta Optional metadata.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Content\DTO\TextContent The created TextContent DTO.
|
||||
*/
|
||||
public static function json_text( $data, int $flags = 0, ?Annotations $annotations = null, ?array $_meta = null ): TextContent {
|
||||
$json = wp_json_encode( $data, $flags );
|
||||
if ( false === $json ) {
|
||||
$json = '{}';
|
||||
}
|
||||
|
||||
return self::text( $json, $annotations, $_meta );
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of ContentBlockInterface DTOs to their array representations.
|
||||
*
|
||||
* Use this at the serialization boundary when preparing content blocks for JSON output.
|
||||
*
|
||||
* @param \WP\McpSchema\Common\Protocol\Union\ContentBlockInterface[] $blocks Array of content block DTOs.
|
||||
*
|
||||
* @return array[] Array of content block arrays.
|
||||
*/
|
||||
public static function to_array_list( array $blocks ): array {
|
||||
return array_map(
|
||||
static function ( ContentBlockInterface $block ): array {
|
||||
return $block->toArray();
|
||||
},
|
||||
$blocks
|
||||
);
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Annotation Mapper utility class for mapping WordPress ability annotations to MCP format.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Utils;
|
||||
|
||||
/**
|
||||
* Utility class for mapping WordPress ability annotations to MCP Annotations format.
|
||||
*
|
||||
* Provides shared annotation mapping and transformation logic used across multiple
|
||||
* MCP component registration classes. Handles conversion of WordPress-format annotations
|
||||
* to MCP-compliant annotation structures.
|
||||
*/
|
||||
class McpAnnotationMapper {
|
||||
|
||||
/**
|
||||
* Comprehensive mapping of MCP annotations.
|
||||
*
|
||||
* Maps MCP annotation fields to their type, which features they apply to,
|
||||
* and their WordPress Ability API equivalent property names.
|
||||
*
|
||||
* Structure:
|
||||
* - type: The data type (boolean, string, array, number)
|
||||
* - features: Array of MCP features where this annotation is used (tool, resource)
|
||||
* - ability_property: The WordPress Ability API property name (may differ from MCP field name), or null if mapping 1:1
|
||||
*
|
||||
* Note: Per MCP 2025-11-25 spec:
|
||||
* - Tools use ToolAnnotations (title, *Hint fields only)
|
||||
* - Resources use shared Annotations (audience, priority, lastModified)
|
||||
* - Prompts do NOT support annotations at template level (only on message content blocks)
|
||||
*
|
||||
* @var array<string, array{type: string, features: array<string>, ability_property: string|null}>
|
||||
*/
|
||||
private static array $mcp_annotations = array(
|
||||
// Shared annotations - Resources only (NOT Tools or Prompt templates per MCP spec).
|
||||
// ToolAnnotations is a separate type that does not include these fields.
|
||||
// Prompt templates do not support annotations; only content blocks inside messages do.
|
||||
'audience' => array(
|
||||
'type' => 'array',
|
||||
'features' => array( 'resource' ),
|
||||
'ability_property' => null,
|
||||
),
|
||||
'lastModified' => array(
|
||||
'type' => 'string',
|
||||
'features' => array( 'resource' ),
|
||||
'ability_property' => null,
|
||||
),
|
||||
'priority' => array(
|
||||
'type' => 'number',
|
||||
'features' => array( 'resource' ),
|
||||
'ability_property' => null,
|
||||
),
|
||||
// Tool-specific annotations (ToolAnnotations type per MCP 2025-11-25 spec).
|
||||
'readOnlyHint' => array(
|
||||
'type' => 'boolean',
|
||||
'features' => array( 'tool' ),
|
||||
'ability_property' => 'readonly',
|
||||
),
|
||||
'destructiveHint' => array(
|
||||
'type' => 'boolean',
|
||||
'features' => array( 'tool' ),
|
||||
'ability_property' => 'destructive',
|
||||
),
|
||||
'idempotentHint' => array(
|
||||
'type' => 'boolean',
|
||||
'features' => array( 'tool' ),
|
||||
'ability_property' => 'idempotent',
|
||||
),
|
||||
'openWorldHint' => array(
|
||||
'type' => 'boolean',
|
||||
'features' => array( 'tool' ),
|
||||
'ability_property' => null,
|
||||
),
|
||||
'title' => array(
|
||||
'type' => 'string',
|
||||
'features' => array( 'tool' ),
|
||||
'ability_property' => null,
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Map WordPress ability annotation property names to MCP field names.
|
||||
*
|
||||
* Maps WordPress-format field names to MCP equivalents (e.g., readonly → readOnlyHint).
|
||||
* Only includes annotations applicable to the specified feature type.
|
||||
* Null values are excluded from the result.
|
||||
*
|
||||
* @param array $ability_annotations WordPress ability annotations.
|
||||
* @param string $feature_type The MCP feature type ('tool', 'resource', or 'prompt').
|
||||
*
|
||||
* @return array Mapped annotations for the specified feature type.
|
||||
*/
|
||||
public static function map( array $ability_annotations, string $feature_type ): array {
|
||||
$result = array();
|
||||
|
||||
foreach ( self::$mcp_annotations as $mcp_field => $config ) {
|
||||
if ( ! in_array( $feature_type, $config['features'], true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = self::resolve_annotation_value(
|
||||
$ability_annotations,
|
||||
$mcp_field,
|
||||
$config['ability_property']
|
||||
);
|
||||
|
||||
if ( null === $value ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized = self::normalize_annotation_value( $config['type'], $value );
|
||||
if ( null === $normalized ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[ $mcp_field ] = $normalized;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the annotation value, preferring WordPress-format overrides when available.
|
||||
*
|
||||
* @param array $annotations Raw annotations from the ability.
|
||||
* @param string $mcp_field The MCP field name.
|
||||
* @param string|null $ability_property Optional WordPress-format field name, or null if mapping 1:1.
|
||||
*
|
||||
* @return mixed The annotation value, or null if not found.
|
||||
*/
|
||||
private static function resolve_annotation_value( array $annotations, string $mcp_field, ?string $ability_property ) {
|
||||
// WordPress-format overrides take precedence when present.
|
||||
if ( null !== $ability_property && array_key_exists( $ability_property, $annotations ) && ! is_null( $annotations[ $ability_property ] ) ) {
|
||||
return $annotations[ $ability_property ];
|
||||
}
|
||||
|
||||
if ( array_key_exists( $mcp_field, $annotations ) && ! is_null( $annotations[ $mcp_field ] ) ) {
|
||||
return $annotations[ $mcp_field ];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize annotation values to the types expected by MCP.
|
||||
*
|
||||
* @param string $field_type Expected MCP type (boolean, string, array, number).
|
||||
* @param mixed $value Raw annotation value.
|
||||
*
|
||||
* @return mixed|null Normalized value or null if invalid.
|
||||
*/
|
||||
private static function normalize_annotation_value( string $field_type, $value ) {
|
||||
switch ( $field_type ) {
|
||||
case 'boolean':
|
||||
return self::normalize_boolean( $value );
|
||||
|
||||
case 'string':
|
||||
if ( ! is_scalar( $value ) ) {
|
||||
return null;
|
||||
}
|
||||
$trimmed = trim( (string) $value );
|
||||
|
||||
return '' === $trimmed ? null : $trimmed;
|
||||
|
||||
case 'array':
|
||||
return is_array( $value ) && ! empty( $value ) ? $value : null;
|
||||
|
||||
case 'number':
|
||||
return is_numeric( $value ) ? (float) $value : null;
|
||||
|
||||
default:
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a value to a strict boolean.
|
||||
*
|
||||
* Accepts only well-defined boolean representations to avoid ambiguous conversions.
|
||||
* PHP's default (bool) cast incorrectly converts 'false' string to true.
|
||||
*
|
||||
* Accepted values:
|
||||
* - true, false (PHP booleans)
|
||||
* - 1, 0 (integers)
|
||||
* - '1', '0', 'true', 'false' (case-insensitive strings)
|
||||
*
|
||||
* @param mixed $value The value to normalize.
|
||||
*
|
||||
* @return bool|null The normalized boolean, or null if value cannot be safely converted.
|
||||
*/
|
||||
private static function normalize_boolean( $value ): ?bool {
|
||||
// Already a boolean - return as-is.
|
||||
if ( is_bool( $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// Integer 1 or 0.
|
||||
if ( is_int( $value ) ) {
|
||||
if ( 1 === $value ) {
|
||||
return true;
|
||||
}
|
||||
if ( 0 === $value ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Other integers are invalid (e.g., 2, -1).
|
||||
return null;
|
||||
}
|
||||
|
||||
// String representations (case-insensitive).
|
||||
if ( is_string( $value ) ) {
|
||||
$lower = strtolower( trim( $value ) );
|
||||
if ( 'true' === $lower || '1' === $lower ) {
|
||||
return true;
|
||||
}
|
||||
if ( 'false' === $lower || '0' === $lower ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Other strings are invalid (e.g., 'yes', 'no', empty string).
|
||||
return null;
|
||||
}
|
||||
|
||||
// All other types (arrays, objects, floats, null) are invalid.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Name Sanitizer utility for normalizing component names.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Utils;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* Utility class for sanitizing names to MCP-valid format.
|
||||
*
|
||||
* Implements best-effort sanitization per MCP 2025-11-25 spec:
|
||||
* - Length: 1-128 characters
|
||||
* - Charset: A-Za-z0-9_.-
|
||||
*
|
||||
* Used for both tools and prompts (same naming rules).
|
||||
* NOT used for resources (which use URIs as identifiers).
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
class McpNameSanitizer {
|
||||
|
||||
/**
|
||||
* Maximum length for MCP tool/prompt names per spec.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const MAX_LENGTH = 128;
|
||||
|
||||
/**
|
||||
* Length of the hash suffix used for truncation uniqueness.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const HASH_LENGTH = 12;
|
||||
|
||||
/**
|
||||
* Maximum characters to keep when truncating (MAX_LENGTH - 1 separator - HASH_LENGTH).
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public const TRUNCATE_LENGTH = 115;
|
||||
|
||||
/**
|
||||
* Sanitize a name to be MCP-valid for tools and prompts.
|
||||
*
|
||||
* Normalization steps:
|
||||
* 1. Trim whitespace
|
||||
* 2. Replace `/` with `-` (forward slash not allowed in MCP)
|
||||
* 3. If valid, return as-is
|
||||
* 4. Otherwise: transliterate accents, replace invalid chars, collapse hyphens, trim edges
|
||||
* 5. If too long: truncate + add hash suffix for uniqueness
|
||||
* 6. If still invalid/empty: return WP_Error
|
||||
*
|
||||
* @param string $name Original name.
|
||||
*
|
||||
* @return string|\WP_Error Sanitized name or WP_Error if unsalvageable.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function sanitize_name( string $name ) {
|
||||
$original = $name;
|
||||
|
||||
// Step 1: Trim whitespace.
|
||||
$name = trim( $name );
|
||||
|
||||
// Step 2: Replace / with - (forward slash not allowed in MCP).
|
||||
$name = str_replace( '/', '-', $name );
|
||||
|
||||
// Step 3: Early validation - if already valid, return as-is.
|
||||
if ( McpValidator::validate_name( $name ) ) {
|
||||
return $name;
|
||||
}
|
||||
|
||||
// Step 4a: Transliterate accented characters to ASCII equivalents.
|
||||
// Uses WordPress core function: é→e, ü→u, ñ→n, etc.
|
||||
$name = remove_accents( $name );
|
||||
|
||||
// Step 4b: Replace any remaining non-allowed chars with hyphen.
|
||||
$name = (string) preg_replace( '/[^a-zA-Z0-9_.-]/', '-', $name );
|
||||
|
||||
// Step 4c: Collapse consecutive hyphens.
|
||||
$name = (string) preg_replace( '/-+/', '-', $name );
|
||||
|
||||
// Step 4d: Trim leading/trailing hyphens and underscores.
|
||||
$name = trim( $name, '-_' );
|
||||
|
||||
// Step 5: Handle length > 128.
|
||||
if ( strlen( $name ) > self::MAX_LENGTH ) {
|
||||
$hash = substr( md5( $original ), 0, self::HASH_LENGTH );
|
||||
$name = substr( $name, 0, self::TRUNCATE_LENGTH ) . '-' . $hash;
|
||||
}
|
||||
|
||||
// Step 6: Final check - only empty is possible failure after sanitization.
|
||||
// Characters are guaranteed valid (replaced), length is handled (truncated).
|
||||
if ( empty( $name ) ) {
|
||||
return new WP_Error(
|
||||
'mcp_name_invalid',
|
||||
sprintf(
|
||||
/* translators: %s: original ability name */
|
||||
__( 'Unable to derive valid MCP name from: %s', 'mcp-adapter' ),
|
||||
$original
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
+533
@@ -0,0 +1,533 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* MCP Validator utility class for validating MCP component data.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Utils;
|
||||
|
||||
use DateTime;
|
||||
|
||||
/**
|
||||
* Utility class for validating MCP component data according to MCP specification.
|
||||
*
|
||||
* Provides shared validation implementations used across multiple MCP component
|
||||
* validators and registration classes. Each method focuses on a specific validation concern.
|
||||
*/
|
||||
class McpValidator {
|
||||
|
||||
/**
|
||||
* Allowed MIME types for MCP icons per specification.
|
||||
*
|
||||
* MUST support: image/png, image/jpeg, image/jpg
|
||||
* SHOULD support: image/svg+xml, image/webp
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
private static array $allowed_icon_mime_types = array(
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/jpg',
|
||||
'image/svg+xml',
|
||||
'image/webp',
|
||||
);
|
||||
|
||||
/**
|
||||
* Validate an MCP component name.
|
||||
*
|
||||
* Validates that a name follows MCP naming conventions per MCP 2025-11-25 spec:
|
||||
* - Must not be empty
|
||||
* - Must not exceed the maximum length
|
||||
* - Must only contain letters, numbers, hyphens (-), underscores (_), and dots (.)
|
||||
*
|
||||
* @param string $name The name to validate.
|
||||
* @param int $max_length Maximum allowed length. Default is 128 per MCP spec.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function validate_name( string $name, int $max_length = 128 ): bool {
|
||||
// Names should not be empty (but allow "0" since it matches the regex).
|
||||
if ( '' === $name ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check length constraints.
|
||||
if ( strlen( $name ) > $max_length ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only allow letters, numbers, hyphens, underscores, and dots per MCP spec.
|
||||
return (bool) preg_match( '/^[a-zA-Z0-9_.-]+$/', $name );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate image MIME type.
|
||||
*
|
||||
* Checks if the MIME type is a valid image type according to MCP specification.
|
||||
*
|
||||
* @param string $mime_type The MIME type to validate.
|
||||
*
|
||||
* @return bool True if valid image MIME type, false otherwise.
|
||||
*/
|
||||
public static function validate_image_mime_type( string $mime_type ): bool {
|
||||
return str_starts_with( strtolower( $mime_type ), 'image/' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate audio MIME type.
|
||||
*
|
||||
* Checks if the MIME type is a valid audio type according to MCP specification.
|
||||
*
|
||||
* @param string $mime_type The MIME type to validate.
|
||||
*
|
||||
* @return bool True if valid audio MIME type, false otherwise.
|
||||
*/
|
||||
public static function validate_audio_mime_type( string $mime_type ): bool {
|
||||
return str_starts_with( strtolower( $mime_type ), 'audio/' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate base64 content.
|
||||
*
|
||||
* Checks if a string is valid base64-encoded content.
|
||||
*
|
||||
* @param string $content The content to validate as base64.
|
||||
*
|
||||
* @return bool True if valid base64, false otherwise.
|
||||
*/
|
||||
public static function validate_base64( string $content ): bool {
|
||||
// Base64 content should not be empty.
|
||||
if ( empty( $content ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Reject whitespace-only strings (they decode to empty string but aren't valid base64 content).
|
||||
if ( trim( $content ) === '' ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if it's valid base64 encoding.
|
||||
return base64_decode( $content, true ) !== false; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an array of icons.
|
||||
*
|
||||
* Returns valid icons and logs warnings for invalid ones.
|
||||
* Invalid icons are filtered out (graceful degradation).
|
||||
*
|
||||
* @param array $icons Array of icon data.
|
||||
* @param bool $log_warnings Whether to log warnings for invalid icons. Default true.
|
||||
*
|
||||
* @return array{valid: array, errors: array} Array with 'valid' icons and 'errors' details.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function validate_icons_array( array $icons, bool $log_warnings = true ): array {
|
||||
$valid_icons = array();
|
||||
$all_errors = array();
|
||||
|
||||
foreach ( $icons as $index => $icon ) {
|
||||
if ( ! is_array( $icon ) ) {
|
||||
$all_errors[] = array(
|
||||
'index' => $index,
|
||||
'errors' => array( __( 'Icon must be an array', 'mcp-adapter' ) ),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
$errors = self::get_icon_validation_errors( $icon );
|
||||
|
||||
if ( empty( $errors ) ) {
|
||||
$valid_icons[] = $icon;
|
||||
} else {
|
||||
$all_errors[] = array(
|
||||
'index' => $index,
|
||||
'errors' => $errors,
|
||||
);
|
||||
|
||||
if ( $log_warnings ) {
|
||||
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
error_log(
|
||||
sprintf(
|
||||
'MCP Adapter: Invalid icon at index %d skipped: %s',
|
||||
$index,
|
||||
implode( '; ', $errors )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array(
|
||||
'valid' => $valid_icons,
|
||||
'errors' => $all_errors,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors for an MCP icon object.
|
||||
*
|
||||
* Validates icon fields per MCP 2025-11-25 specification:
|
||||
* - src (required): Valid URL or data: URI
|
||||
* - mimeType (optional): One of allowed image MIME types
|
||||
* - sizes (optional): Array of size strings in WxH format or "any"
|
||||
* - theme (optional): "light" or "dark"
|
||||
*
|
||||
* @param array $icon The icon data to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function get_icon_validation_errors( array $icon ): array {
|
||||
$errors = array();
|
||||
|
||||
// src is required.
|
||||
if ( ! isset( $icon['src'] ) ) {
|
||||
$errors[] = __( 'Icon must have a src field', 'mcp-adapter' );
|
||||
} elseif ( ! is_string( $icon['src'] ) ) {
|
||||
$errors[] = __( 'Icon src must be a string', 'mcp-adapter' );
|
||||
} elseif ( ! self::validate_icon_src( $icon['src'] ) ) {
|
||||
$errors[] = __( 'Icon src must be a valid URL (http/https) or data: URI', 'mcp-adapter' );
|
||||
}
|
||||
|
||||
// mimeType is optional but must be valid if present.
|
||||
if ( isset( $icon['mimeType'] ) ) {
|
||||
if ( ! is_string( $icon['mimeType'] ) ) {
|
||||
$errors[] = __( 'Icon mimeType must be a string', 'mcp-adapter' );
|
||||
} elseif ( ! self::validate_icon_mime_type( $icon['mimeType'] ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %s: comma-separated list of allowed MIME types */
|
||||
__( 'Icon mimeType must be one of: %s', 'mcp-adapter' ),
|
||||
implode( ', ', self::$allowed_icon_mime_types )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// sizes is optional but must be valid if present.
|
||||
if ( isset( $icon['sizes'] ) ) {
|
||||
if ( ! is_array( $icon['sizes'] ) ) {
|
||||
$errors[] = __( 'Icon sizes must be an array', 'mcp-adapter' );
|
||||
} else {
|
||||
foreach ( $icon['sizes'] as $index => $size ) {
|
||||
if ( ! is_string( $size ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: %d: array index */
|
||||
__( 'Icon size at index %d must be a string', 'mcp-adapter' ),
|
||||
$index
|
||||
);
|
||||
} elseif ( ! self::validate_icon_size( $size ) ) {
|
||||
$errors[] = sprintf(
|
||||
/* translators: 1: size value, 2: array index */
|
||||
__( 'Icon size "%1$s" at index %2$d must be in WxH format (e.g., "48x48") or "any"', 'mcp-adapter' ),
|
||||
$size,
|
||||
$index
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// theme is optional but must be valid if present.
|
||||
if ( isset( $icon['theme'] ) ) {
|
||||
if ( ! is_string( $icon['theme'] ) ) {
|
||||
$errors[] = __( 'Icon theme must be a string', 'mcp-adapter' );
|
||||
} elseif ( ! self::validate_icon_theme( $icon['theme'] ) ) {
|
||||
$errors[] = __( 'Icon theme must be "light" or "dark"', 'mcp-adapter' );
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an icon source (src) value.
|
||||
*
|
||||
* Icon src must be a valid URL (http/https) or a data: URI with base64-encoded image data.
|
||||
*
|
||||
* @param string $src The icon source to validate.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function validate_icon_src( string $src ): bool {
|
||||
$src = trim( $src );
|
||||
|
||||
if ( empty( $src ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for data: URI.
|
||||
if ( str_starts_with( $src, 'data:' ) ) {
|
||||
// data:[<mediatype>][;base64],<data>
|
||||
// Simplified validation: must have data: prefix and contain comma.
|
||||
return str_contains( $src, ',' );
|
||||
}
|
||||
|
||||
// Check for http/https URL.
|
||||
if ( str_starts_with( $src, 'http://' ) || str_starts_with( $src, 'https://' ) ) {
|
||||
return filter_var( $src, FILTER_VALIDATE_URL ) !== false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an icon MIME type.
|
||||
*
|
||||
* Per MCP spec, clients MUST support image/png, image/jpeg (and image/jpg).
|
||||
* Clients SHOULD support image/svg+xml, image/webp.
|
||||
*
|
||||
* @param string $mime_type The MIME type to validate.
|
||||
*
|
||||
* @return bool True if valid icon MIME type, false otherwise.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function validate_icon_mime_type( string $mime_type ): bool {
|
||||
return in_array( strtolower( trim( $mime_type ) ), self::$allowed_icon_mime_types, true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an icon size string.
|
||||
*
|
||||
* Icon sizes must be in WxH format (e.g., "48x48", "96x96") or "any" for scalable formats.
|
||||
* Both width and height must be positive integers (no zero dimensions, no leading zeros).
|
||||
*
|
||||
* @param string $size The size string to validate.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function validate_icon_size( string $size ): bool {
|
||||
$size = trim( $size );
|
||||
|
||||
if ( empty( $size ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// "any" is valid for scalable formats like SVG.
|
||||
if ( 'any' === strtolower( $size ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Must match WxH format with positive integers (no zero dimensions, no leading zeros).
|
||||
// [1-9]\d* matches: 1, 2, ..., 9, 10, 11, ..., 99, 100, etc.
|
||||
return (bool) preg_match( '/^[1-9]\d*x[1-9]\d*$/', $size );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an icon theme value.
|
||||
*
|
||||
* Valid themes are "light" or "dark".
|
||||
*
|
||||
* @param string $theme The theme to validate.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
* @since 0.5.0
|
||||
*
|
||||
*/
|
||||
public static function validate_icon_theme( string $theme ): bool {
|
||||
return in_array( strtolower( trim( $theme ) ), array( 'light', 'dark' ), true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation errors for shared MCP annotations.
|
||||
*
|
||||
* Validates shared annotation fields per MCP 2025-11-25 specification:
|
||||
* - audience must be an array of valid Role values ("user", "assistant")
|
||||
* - lastModified must be a valid ISO 8601 formatted string
|
||||
* - priority must be a number between 0.0 and 1.0
|
||||
*
|
||||
* Only validates known shared annotation fields. Unknown fields are ignored.
|
||||
* Used by resources and content types (text, image, audio).
|
||||
*
|
||||
* Note: Tools use ToolAnnotations which is a separate type validated by McpToolValidator.
|
||||
*
|
||||
* @param array $annotations The annotations to validate.
|
||||
*
|
||||
* @return array Array of validation errors, empty if valid.
|
||||
*/
|
||||
public static function get_annotation_validation_errors( array $annotations ): array {
|
||||
$errors = array();
|
||||
|
||||
foreach ( $annotations as $field => $value ) {
|
||||
switch ( $field ) {
|
||||
case 'audience':
|
||||
if ( ! is_array( $value ) ) {
|
||||
$errors[] = __( 'Annotation field audience must be an array', 'mcp-adapter' );
|
||||
break;
|
||||
}
|
||||
if ( ! self::validate_roles_array( $value ) ) {
|
||||
$errors[] = __( 'Annotation field audience must contain only valid roles ("user" or "assistant")', 'mcp-adapter' );
|
||||
}
|
||||
break;
|
||||
|
||||
case 'lastModified':
|
||||
if ( ! is_string( $value ) || empty( trim( $value ) ) ) {
|
||||
$errors[] = __( 'Annotation field lastModified must be a non-empty string', 'mcp-adapter' );
|
||||
break;
|
||||
}
|
||||
if ( ! self::validate_iso8601_timestamp( trim( $value ) ) ) {
|
||||
$errors[] = __( 'Annotation field lastModified must be a valid ISO 8601 timestamp', 'mcp-adapter' );
|
||||
}
|
||||
break;
|
||||
|
||||
case 'priority':
|
||||
if ( ! is_numeric( $value ) ) {
|
||||
$errors[] = __( 'Annotation field priority must be a number', 'mcp-adapter' );
|
||||
break;
|
||||
}
|
||||
if ( ! self::validate_priority( $value ) ) {
|
||||
$errors[] = __( 'Annotation field priority must be between 0.0 and 1.0', 'mcp-adapter' );
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
// Unknown fields are ignored to allow forward compatibility.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an array of roles according to MCP specification.
|
||||
*
|
||||
* All roles must be strings and must be either "user" or "assistant".
|
||||
*
|
||||
* @param array $roles The roles array to validate.
|
||||
*
|
||||
* @return bool True if all roles are valid, false otherwise.
|
||||
*/
|
||||
public static function validate_roles_array( array $roles ): bool {
|
||||
foreach ( $roles as $role ) {
|
||||
if ( ! is_string( $role ) || ! self::validate_role( $role ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a role value according to MCP specification.
|
||||
*
|
||||
* Valid roles are "user" or "assistant".
|
||||
*
|
||||
* @param string $role The role to validate.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
*/
|
||||
public static function validate_role( string $role ): bool {
|
||||
return in_array( $role, array( 'user', 'assistant' ), true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate ISO 8601 timestamp format.
|
||||
*
|
||||
* Checks if a string is a valid ISO 8601 timestamp by attempting to parse
|
||||
* it using multiple ISO 8601 format variations.
|
||||
*
|
||||
* @param string $timestamp The timestamp to validate.
|
||||
*
|
||||
* @return bool True if valid ISO 8601 timestamp, false otherwise.
|
||||
*/
|
||||
public static function validate_iso8601_timestamp( string $timestamp ): bool {
|
||||
// Try to parse as DateTime with ISO 8601 format.
|
||||
$datetime = DateTime::createFromFormat( DateTime::ATOM, $timestamp );
|
||||
if ( $datetime && $datetime->format( DateTime::ATOM ) === $timestamp ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Try alternative ISO 8601 formats.
|
||||
$formats = array(
|
||||
'Y-m-d\TH:i:s\Z', // UTC format
|
||||
'Y-m-d\TH:i:sP', // With timezone offset
|
||||
'Y-m-d\TH:i:s.u\Z', // With microseconds UTC
|
||||
'Y-m-d\TH:i:s.uP', // With microseconds and timezone
|
||||
);
|
||||
|
||||
foreach ( $formats as $format ) {
|
||||
$datetime = DateTime::createFromFormat( $format, $timestamp );
|
||||
if ( $datetime && $datetime->format( $format ) === $timestamp ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a priority value according to MCP specification.
|
||||
*
|
||||
* Priority must be a number between 0.0 and 1.0 (inclusive).
|
||||
*
|
||||
* @param mixed $priority The priority value to validate.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
*/
|
||||
public static function validate_priority( $priority ): bool {
|
||||
if ( ! is_numeric( $priority ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$priority_float = (float) $priority;
|
||||
|
||||
return $priority_float >= 0.0 && $priority_float <= 1.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a resource URI format.
|
||||
*
|
||||
* Per MCP spec: "The URI can use any protocol; it is up to the server how to interpret it."
|
||||
* This validates basic URI structure per RFC 3986.
|
||||
*
|
||||
* @param string $uri The URI to validate.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
*/
|
||||
public static function validate_resource_uri( string $uri ): bool {
|
||||
// URI should not be empty.
|
||||
if ( empty( $uri ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check reasonable length constraints.
|
||||
if ( strlen( $uri ) > 2048 ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Basic URI validation: must have scheme followed by colon (RFC 3986).
|
||||
// This accepts any protocol as per MCP specification.
|
||||
return (bool) preg_match( '/^[a-zA-Z][a-zA-Z0-9+.-]*:.+/', $uri );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate general MIME type format.
|
||||
*
|
||||
* Validates that a MIME type follows the standard format: type/subtype
|
||||
* where both type and subtype contain valid characters.
|
||||
*
|
||||
* @param string $mime_type The MIME type to validate.
|
||||
*
|
||||
* @return bool True if valid MIME type format, false otherwise.
|
||||
*/
|
||||
public static function validate_mime_type( string $mime_type ): bool {
|
||||
// RFC 2045 compliant: allows +, ., and other valid MIME type characters.
|
||||
// Examples: image/svg+xml, application/vnd.api+json, text/plain.
|
||||
return (bool) preg_match( '/^[a-zA-Z0-9][a-zA-Z0-9!#$&^_.+-]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&^_.+-]*$/', $mime_type );
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
/**
|
||||
* SchemaTransformer class for converting flattened schemas to MCP-compatible object schemas.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Domain\Utils;
|
||||
|
||||
/**
|
||||
* SchemaTransformer class.
|
||||
*
|
||||
* This class transforms flattened JSON schemas (e.g., type: string, number, boolean, array)
|
||||
* into MCP-compatible object schemas. MCP requires all tool input schemas to be of type "object".
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
class SchemaTransformer {
|
||||
/**
|
||||
* Transform a schema to MCP-compatible object format.
|
||||
*
|
||||
* If the schema is already an object type, it is returned unchanged.
|
||||
* If the schema is a flattened type (string, number, boolean, array), it is
|
||||
* wrapped in an object structure with a single property (defaults to "input").
|
||||
*
|
||||
* @param array<string,mixed>|null $schema The JSON schema to transform.
|
||||
* @param string $wrapper_key Property name to use when wrapping non-object schemas.
|
||||
*
|
||||
* @return array<string,mixed> Array containing 'schema', 'was_transformed' (bool), and 'wrapper_property' when transformed.
|
||||
*/
|
||||
public static function transform_to_object_schema( ?array $schema, string $wrapper_key = 'input' ): array {
|
||||
// Convert any objects to arrays and strip empty properties.
|
||||
// Abilities may contain objects from JSON decode cycles. Empty properties must be removed
|
||||
// because MCP expects properties to be a JSON object, and PHP serializes empty arrays as [].
|
||||
$schema = self::normalize( $schema );
|
||||
|
||||
// Handle null or empty schema - return minimal valid MCP object schema.
|
||||
if ( empty( $schema ) ) {
|
||||
return array(
|
||||
'schema' => array(
|
||||
'type' => 'object',
|
||||
),
|
||||
'was_transformed' => false,
|
||||
'wrapper_property' => null,
|
||||
);
|
||||
}
|
||||
|
||||
// If no type is specified, add 'object' type since MCP requires it.
|
||||
if ( ! isset( $schema['type'] ) ) {
|
||||
$schema['type'] = 'object';
|
||||
|
||||
return array(
|
||||
'schema' => $schema,
|
||||
'was_transformed' => false,
|
||||
'wrapper_property' => null,
|
||||
);
|
||||
}
|
||||
|
||||
// If already an object type, return as-is
|
||||
if ( 'object' === $schema['type'] ) {
|
||||
return array(
|
||||
'schema' => $schema,
|
||||
'was_transformed' => false,
|
||||
'wrapper_property' => null,
|
||||
);
|
||||
}
|
||||
|
||||
// Transform flattened schema to object format
|
||||
return array(
|
||||
'schema' => self::wrap_in_object( $schema, $wrapper_key ),
|
||||
'was_transformed' => true,
|
||||
'wrapper_property' => $wrapper_key,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a flattened schema in an object structure.
|
||||
*
|
||||
* Creates an object schema with a single property (named by $wrapper_key) that
|
||||
* contains the original flattened schema.
|
||||
*
|
||||
* @param array<string,mixed> $schema The flattened schema to wrap.
|
||||
* @param string $wrapper_key Property name to wrap the value under.
|
||||
*
|
||||
* @return array<string,mixed> The wrapped object schema.
|
||||
*/
|
||||
private static function wrap_in_object( array $schema, string $wrapper_key ): array {
|
||||
return array(
|
||||
'type' => 'object',
|
||||
'properties' => array(
|
||||
$wrapper_key => $schema,
|
||||
),
|
||||
'required' => array( $wrapper_key ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert objects to arrays and strip empty properties.
|
||||
*
|
||||
* @param array<string,mixed>|null $schema The schema to normalize.
|
||||
*
|
||||
* @return array<string,mixed>|null The normalized schema.
|
||||
*/
|
||||
private static function normalize( ?array $schema ): ?array {
|
||||
if ( null === $schema ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$schema = self::convert_objects_to_arrays( $schema );
|
||||
|
||||
if ( array_key_exists( 'properties', $schema ) && is_array( $schema['properties'] ) && empty( $schema['properties'] ) ) {
|
||||
unset( $schema['properties'] );
|
||||
}
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively convert objects to arrays.
|
||||
*
|
||||
* @param mixed $value The value to convert.
|
||||
*
|
||||
* @return mixed The converted value.
|
||||
*/
|
||||
private static function convert_objects_to_arrays( $value ) {
|
||||
if ( is_object( $value ) ) {
|
||||
$value = (array) $value;
|
||||
}
|
||||
|
||||
if ( is_array( $value ) ) {
|
||||
return array_map( array( self::class, 'convert_objects_to_arrays' ), $value );
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
/**
|
||||
* Helper trait for MCP handlers.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Handlers;
|
||||
|
||||
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface;
|
||||
|
||||
/**
|
||||
* Provides common helper methods for MCP handlers.
|
||||
*/
|
||||
trait HandlerHelperTrait {
|
||||
/**
|
||||
* Extracts parameters from a request message.
|
||||
*
|
||||
* Handles both direct params and nested params structure for backward compatibility.
|
||||
* This normalizes the dual parameter patterns found throughout handlers.
|
||||
*
|
||||
* @param array $data Request data that may have params at root or nested.
|
||||
*
|
||||
* @return array Extracted parameters.
|
||||
*/
|
||||
protected function extract_params( array $data ): array {
|
||||
return $data['params'] ?? $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that a filtered list value is still an array.
|
||||
*
|
||||
* If a filter callback returns a non-array value, logs a warning
|
||||
* and falls back to the original unfiltered array to prevent
|
||||
* downstream type errors.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param mixed $filtered The value returned by apply_filters.
|
||||
* @param array $original The original unfiltered array.
|
||||
* @param string $filter_name The filter hook name (for logging).
|
||||
* @param \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface $error_handler The error handler for logging.
|
||||
*
|
||||
* @return array The validated array (filtered if valid, original if not).
|
||||
*/
|
||||
protected function validate_filtered_list( $filtered, array $original, string $filter_name, McpErrorHandlerInterface $error_handler ): array {
|
||||
if ( is_array( $filtered ) ) {
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
$error_handler->log(
|
||||
'Filter returned non-array value, falling back to original list',
|
||||
array(
|
||||
'filter' => $filter_name,
|
||||
'returned_type' => gettype( $filtered ),
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
|
||||
return $original;
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
/**
|
||||
* Initialize method handler for MCP requests.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Handlers\Initialize;
|
||||
|
||||
use WP\MCP\Core\McpServer;
|
||||
use WP\MCP\Core\McpVersionNegotiator;
|
||||
use WP\McpSchema\Common\Lifecycle\DTO\Implementation;
|
||||
use WP\McpSchema\Common\Protocol\DTO\InitializeResult;
|
||||
use WP\McpSchema\Server\Lifecycle\DTO\ServerCapabilities;
|
||||
|
||||
/**
|
||||
* Handles the initialize MCP method.
|
||||
*/
|
||||
class InitializeHandler {
|
||||
/**
|
||||
* The WordPress MCP instance.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
private McpServer $mcp;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP\MCP\Core\McpServer $mcp The WordPress MCP instance.
|
||||
*/
|
||||
public function __construct( McpServer $mcp ) {
|
||||
$this->mcp = $mcp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the initialize request.
|
||||
*
|
||||
* Negotiates the protocol version with the client using McpVersionNegotiator.
|
||||
* If the client requests a supported version, that version is used. Otherwise
|
||||
* the server falls back to the latest supported version.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $client_protocol_version The protocol version requested by the client.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Protocol\DTO\InitializeResult Response with server capabilities and information.
|
||||
*/
|
||||
public function handle( string $client_protocol_version ): InitializeResult {
|
||||
$negotiated_version = McpVersionNegotiator::negotiate( $client_protocol_version );
|
||||
|
||||
$server_info = Implementation::fromArray(
|
||||
array(
|
||||
'name' => $this->mcp->get_server_name(),
|
||||
'version' => $this->mcp->get_server_version(),
|
||||
)
|
||||
);
|
||||
|
||||
// Capabilities should only be advertised if they are implemented end-to-end.
|
||||
// IMPORTANT: We set explicit boolean values (not empty arrays) to ensure proper JSON serialization.
|
||||
// Empty arrays `[]` serialize as JSON arrays `[]`, but MCP spec requires JSON objects `{}`.
|
||||
// Setting explicit values like `listChanged: false` produces associative arrays that serialize correctly.
|
||||
$capabilities = ServerCapabilities::fromArray(
|
||||
array(
|
||||
'prompts' => array( 'listChanged' => false ),
|
||||
'resources' => array(
|
||||
'subscribe' => false,
|
||||
'listChanged' => false,
|
||||
),
|
||||
'tools' => array( 'listChanged' => false ),
|
||||
)
|
||||
);
|
||||
|
||||
$result = InitializeResult::fromArray(
|
||||
array(
|
||||
'protocolVersion' => $negotiated_version,
|
||||
'capabilities' => $capabilities,
|
||||
'serverInfo' => $server_info,
|
||||
'instructions' => $this->mcp->get_server_description(),
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* Filters the initialize response before returning to the client.
|
||||
*
|
||||
* Use this filter to modify server capabilities, instructions, or
|
||||
* other initialization data dynamically. To modify the result, call
|
||||
* `$result->toArray()`, change the data, and return
|
||||
* `InitializeResult::fromArray( $modified_data )`.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param \WP\McpSchema\Common\Protocol\DTO\InitializeResult $result The initialize result DTO.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
return apply_filters( 'mcp_adapter_initialize_response', $result, $this->mcp );
|
||||
}
|
||||
}
|
||||
+612
@@ -0,0 +1,612 @@
|
||||
<?php
|
||||
/**
|
||||
* Prompts method handlers for MCP requests.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Handlers\Prompts;
|
||||
|
||||
use WP\MCP\Core\McpServer;
|
||||
use WP\MCP\Handlers\HandlerHelperTrait;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\McpErrorFactory;
|
||||
use WP\McpSchema\Server\Prompts\DTO\GetPromptResult;
|
||||
use WP\McpSchema\Server\Prompts\DTO\ListPromptsResult;
|
||||
use WP\McpSchema\Server\Prompts\DTO\Prompt as PromptDto;
|
||||
use WP\McpSchema\Server\Prompts\DTO\PromptMessage;
|
||||
|
||||
/**
|
||||
* Handles prompts-related MCP methods.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
class PromptsHandler {
|
||||
use HandlerHelperTrait;
|
||||
|
||||
/**
|
||||
* Valid content types from ContentBlockFactory.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private static array $valid_content_types = array( 'text', 'image', 'audio', 'resource_link', 'resource' );
|
||||
|
||||
/**
|
||||
* Valid role values for PromptMessage.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private static array $valid_roles = array( 'user', 'assistant' );
|
||||
|
||||
/**
|
||||
* Default role for messages when not specified.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private static string $default_role = 'user';
|
||||
|
||||
/**
|
||||
* The WordPress MCP instance.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
private McpServer $mcp;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP\MCP\Core\McpServer $mcp The WordPress MCP instance.
|
||||
*/
|
||||
public function __construct( McpServer $mcp ) {
|
||||
$this->mcp = $mcp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the prompts/list request.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\ListPromptsResult Response with prompts list DTO.
|
||||
*/
|
||||
public function list_prompts(): ListPromptsResult {
|
||||
$prompts = array_values( $this->mcp->get_prompts() );
|
||||
|
||||
/**
|
||||
* Filters the list of prompts before returning to the client.
|
||||
*
|
||||
* Use this filter to filter prompts by context, add dynamic prompts,
|
||||
* or reorder the prompts list.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array<\WP\McpSchema\Server\Prompts\DTO\Prompt> $prompts Array of Prompt DTOs.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$prompts = $this->validate_filtered_list(
|
||||
apply_filters( 'mcp_adapter_prompts_list', $prompts, $this->mcp ),
|
||||
$prompts,
|
||||
'mcp_adapter_prompts_list',
|
||||
$this->mcp->get_error_handler()
|
||||
);
|
||||
|
||||
return ListPromptsResult::fromArray(
|
||||
array(
|
||||
'prompts' => $prompts,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the prompts/get request.
|
||||
*
|
||||
* @param array $params Request parameters.
|
||||
* @param string|int|null $request_id Optional. The request ID for JSON-RPC. Default 0.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\GetPromptResult|\WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse Response with prompt execution results or error.
|
||||
*/
|
||||
public function get_prompt( array $params, $request_id = 0 ) {
|
||||
// Extract parameters using helper method.
|
||||
$request_params = $this->extract_params( $params );
|
||||
|
||||
if ( ! isset( $request_params['name'] ) ) {
|
||||
return McpErrorFactory::missing_parameter( $request_id, 'name' );
|
||||
}
|
||||
|
||||
$prompt_name = (string) $request_params['name'];
|
||||
$prompt_name = trim( $prompt_name );
|
||||
|
||||
if ( isset( $request_params['arguments'] ) && ! is_array( $request_params['arguments'] ) ) {
|
||||
return McpErrorFactory::invalid_params( $request_id, 'arguments must be an object' );
|
||||
}
|
||||
|
||||
$mcp_prompt = $this->mcp->get_mcp_prompt( $prompt_name );
|
||||
|
||||
if ( ! $mcp_prompt ) {
|
||||
return McpErrorFactory::prompt_not_found( $request_id, $prompt_name );
|
||||
}
|
||||
|
||||
/** @var \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt */
|
||||
$prompt = $mcp_prompt->get_protocol_dto();
|
||||
|
||||
// Get the arguments for the prompt.
|
||||
$arguments = $request_params['arguments'] ?? array();
|
||||
|
||||
try {
|
||||
$permission = $mcp_prompt->check_permission( $arguments );
|
||||
if ( true !== $permission ) {
|
||||
$error_message = 'Access denied for prompt: ' . $prompt_name;
|
||||
if ( is_wp_error( $permission ) ) {
|
||||
$error_message = $permission->get_error_message();
|
||||
}
|
||||
|
||||
return McpErrorFactory::permission_denied( $request_id, $error_message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters prompt arguments before execution, or short-circuits execution entirely.
|
||||
*
|
||||
* Return the (optionally modified) arguments array to proceed with execution,
|
||||
* or return a WP_Error to block execution and return an error to the client.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $arguments The prompt arguments.
|
||||
* @param string $prompt_name The prompt name being retrieved.
|
||||
* @param \WP\MCP\Domain\Prompts\McpPrompt $mcp_prompt The MCP prompt instance.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$arguments = apply_filters( 'mcp_adapter_pre_prompt_get', $arguments, $prompt_name, $mcp_prompt, $this->mcp );
|
||||
|
||||
// Allow pre-filter to short-circuit execution by returning WP_Error.
|
||||
if ( is_wp_error( $arguments ) ) {
|
||||
return McpErrorFactory::internal_error( $request_id, $arguments->get_error_message() );
|
||||
}
|
||||
|
||||
$result = $mcp_prompt->execute( $arguments );
|
||||
|
||||
/**
|
||||
* Filters the prompt execution result before normalization.
|
||||
*
|
||||
* Use this filter for message transformation, context injection,
|
||||
* content enrichment, or audit logging.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param mixed|\WP_Error $result The raw execution result (may be WP_Error).
|
||||
* @param array $arguments The prompt arguments used.
|
||||
* @param string $prompt_name The prompt name.
|
||||
* @param \WP\MCP\Domain\Prompts\McpPrompt $mcp_prompt The MCP prompt instance.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$result = apply_filters( 'mcp_adapter_prompt_get_result', $result, $arguments, $prompt_name, $mcp_prompt, $this->mcp );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Prompt execution returned WP_Error',
|
||||
array(
|
||||
'prompt_name' => $prompt_name,
|
||||
'error_code' => $result->get_error_code(),
|
||||
'error_message' => $result->get_error_message(),
|
||||
)
|
||||
);
|
||||
|
||||
return McpErrorFactory::internal_error( $request_id, $result->get_error_message() );
|
||||
}
|
||||
|
||||
return $this->normalize_result_to_dto( $result, $prompt, $prompt_name );
|
||||
} catch ( \Throwable $e ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Prompt execution failed',
|
||||
array(
|
||||
'prompt_name' => $prompt_name,
|
||||
'arguments' => $arguments,
|
||||
'error' => $e->getMessage(),
|
||||
)
|
||||
);
|
||||
|
||||
return McpErrorFactory::internal_error( $request_id, 'Prompt execution failed' );
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Result Normalization (Tiered Convenience Shortcuts)
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Normalize and convert prompt execution result to GetPromptResult DTO.
|
||||
*
|
||||
* Supports tiered return formats:
|
||||
* - Tier 1: Full MCP format with 'messages' array
|
||||
* - Tier 2: Simple 'text' shorthand
|
||||
* - Tier 3: Single message with 'role' and 'content'
|
||||
* - Tier 4: Multi-text with 'texts' array
|
||||
* - Tier 5: Fallback JSON encoding for arbitrary data
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $result Raw result from prompt execution.
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The prompt DTO for description fallback.
|
||||
* @param string $prompt_name Prompt name for logging.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\GetPromptResult
|
||||
*/
|
||||
private function normalize_result_to_dto(
|
||||
array $result,
|
||||
PromptDto $prompt,
|
||||
string $prompt_name
|
||||
): GetPromptResult {
|
||||
// Tier 1: Full MCP format with 'messages' array.
|
||||
if ( isset( $result['messages'] ) && is_array( $result['messages'] ) ) {
|
||||
return $this->normalize_tier1_messages( $result, $prompt, $prompt_name );
|
||||
}
|
||||
|
||||
// Tier 2: Simple 'text' shorthand.
|
||||
if ( isset( $result['text'] ) && is_string( $result['text'] ) ) {
|
||||
return $this->normalize_tier2_text( $result, $prompt );
|
||||
}
|
||||
|
||||
// Tier 3: Single message with 'role' key.
|
||||
if ( isset( $result['role'] ) && isset( $result['content'] ) ) {
|
||||
return $this->normalize_tier3_single_message( $result, $prompt, $prompt_name );
|
||||
}
|
||||
|
||||
// Tier 4: Multi-text with 'texts' array.
|
||||
if ( isset( $result['texts'] ) && is_array( $result['texts'] ) ) {
|
||||
return $this->normalize_tier4_texts( $result, $prompt );
|
||||
}
|
||||
|
||||
// Tier 5: Fallback - JSON encode arbitrary data.
|
||||
return $this->normalize_tier5_fallback( $result, $prompt, $prompt_name );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 1: Full MCP-compliant format with 'messages' array.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $result Raw result with 'messages' key.
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The prompt DTO.
|
||||
* @param string $prompt_name Prompt name for logging.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\GetPromptResult
|
||||
*/
|
||||
private function normalize_tier1_messages(
|
||||
array $result,
|
||||
PromptDto $prompt,
|
||||
string $prompt_name
|
||||
): GetPromptResult {
|
||||
$message_dtos = array();
|
||||
|
||||
foreach ( $result['messages'] as $index => $message ) {
|
||||
if ( ! is_array( $message ) ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Invalid message structure in prompt result, skipping',
|
||||
array(
|
||||
'prompt_name' => $prompt_name,
|
||||
'message_index' => $index,
|
||||
'message_type' => gettype( $message ),
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
$message_dtos[] = $this->validate_and_create_message( $message, $prompt_name );
|
||||
}
|
||||
|
||||
// Ensure we have at least one message.
|
||||
if ( empty( $message_dtos ) ) {
|
||||
$message_dtos[] = PromptMessage::fromArray(
|
||||
array(
|
||||
'role' => self::$default_role,
|
||||
'content' => array(
|
||||
'type' => 'text',
|
||||
'text' => '(No messages returned)',
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return GetPromptResult::fromArray(
|
||||
array(
|
||||
'messages' => $message_dtos,
|
||||
'description' => $result['description'] ?? $prompt->getDescription(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 2: Simple 'text' shorthand.
|
||||
*
|
||||
* Creates a single user message with text content.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $result Raw result with 'text' key.
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The prompt DTO.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\GetPromptResult
|
||||
*/
|
||||
private function normalize_tier2_text( array $result, PromptDto $prompt ): GetPromptResult {
|
||||
$content = array(
|
||||
'type' => 'text',
|
||||
'text' => (string) $result['text'],
|
||||
);
|
||||
|
||||
// Support optional annotations on the text.
|
||||
if ( isset( $result['annotations'] ) && is_array( $result['annotations'] ) ) {
|
||||
$content['annotations'] = $result['annotations'];
|
||||
}
|
||||
|
||||
$message_dto = PromptMessage::fromArray(
|
||||
array(
|
||||
'role' => self::$default_role,
|
||||
'content' => $content,
|
||||
)
|
||||
);
|
||||
|
||||
return GetPromptResult::fromArray(
|
||||
array(
|
||||
'messages' => array( $message_dto ),
|
||||
'description' => $result['description'] ?? $prompt->getDescription(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 3: Single message with 'role' and 'content'.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $result Raw result with 'role' and 'content' keys.
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The prompt DTO.
|
||||
* @param string $prompt_name Prompt name for logging.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\GetPromptResult
|
||||
*/
|
||||
private function normalize_tier3_single_message(
|
||||
array $result,
|
||||
PromptDto $prompt,
|
||||
string $prompt_name
|
||||
): GetPromptResult {
|
||||
$message_dto = $this->validate_and_create_message( $result, $prompt_name );
|
||||
|
||||
return GetPromptResult::fromArray(
|
||||
array(
|
||||
'messages' => array( $message_dto ),
|
||||
'description' => $result['description'] ?? $prompt->getDescription(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 4: Multi-text with 'texts' array.
|
||||
*
|
||||
* Creates multiple messages with the same role.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $result Raw result with 'texts' key.
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The prompt DTO.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\GetPromptResult
|
||||
*/
|
||||
private function normalize_tier4_texts( array $result, PromptDto $prompt ): GetPromptResult {
|
||||
$role = $this->validate_role( $result['role'] ?? self::$default_role, '' );
|
||||
$message_dtos = array();
|
||||
|
||||
foreach ( $result['texts'] as $text ) {
|
||||
if ( ! is_string( $text ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$message_dtos[] = PromptMessage::fromArray(
|
||||
array(
|
||||
'role' => $role,
|
||||
'content' => array(
|
||||
'type' => 'text',
|
||||
'text' => $text,
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Ensure we have at least one message.
|
||||
if ( empty( $message_dtos ) ) {
|
||||
$message_dtos[] = PromptMessage::fromArray(
|
||||
array(
|
||||
'role' => $role,
|
||||
'content' => array(
|
||||
'type' => 'text',
|
||||
'text' => '(No texts provided)',
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return GetPromptResult::fromArray(
|
||||
array(
|
||||
'messages' => $message_dtos,
|
||||
'description' => $result['description'] ?? $prompt->getDescription(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 5: Fallback - JSON encode arbitrary data.
|
||||
*
|
||||
* Used when no other tier matches. Logs an observability event.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $result Raw result (arbitrary structure).
|
||||
* @param \WP\McpSchema\Server\Prompts\DTO\Prompt $prompt The prompt DTO.
|
||||
* @param string $prompt_name Prompt name for logging.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\GetPromptResult
|
||||
*/
|
||||
private function normalize_tier5_fallback(
|
||||
array $result,
|
||||
PromptDto $prompt,
|
||||
string $prompt_name
|
||||
): GetPromptResult {
|
||||
// Log observability event for fallback normalization.
|
||||
$this->mcp->get_observability_handler()->record_event(
|
||||
'prompt_result_fallback_normalization',
|
||||
array(
|
||||
'prompt_name' => $prompt_name,
|
||||
'result_keys' => array_keys( $result ),
|
||||
)
|
||||
);
|
||||
|
||||
$json_content = wp_json_encode( $result, JSON_PRETTY_PRINT );
|
||||
if ( false === $json_content ) {
|
||||
$json_content = '{}';
|
||||
}
|
||||
|
||||
$message_dto = PromptMessage::fromArray(
|
||||
array(
|
||||
'role' => self::$default_role,
|
||||
'content' => array(
|
||||
'type' => 'text',
|
||||
'text' => $json_content,
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
return GetPromptResult::fromArray(
|
||||
array(
|
||||
'messages' => array( $message_dto ),
|
||||
'description' => $prompt->getDescription(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Validation Helpers
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Validate message structure and create PromptMessage DTO.
|
||||
*
|
||||
* Validates role and content type, applying defaults where needed.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $message Raw message array.
|
||||
* @param string $prompt_name Prompt name for logging.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Prompts\DTO\PromptMessage
|
||||
*/
|
||||
private function validate_and_create_message( array $message, string $prompt_name ): PromptMessage {
|
||||
// Validate and normalize role.
|
||||
$role = $this->validate_role( $message['role'] ?? self::$default_role, $prompt_name );
|
||||
|
||||
// Validate and normalize content.
|
||||
$content = $message['content'] ?? array();
|
||||
if ( ! is_array( $content ) ) {
|
||||
// If content is a string, wrap it as text.
|
||||
$content = array(
|
||||
'type' => 'text',
|
||||
'text' => is_string( $content ) ? $content : (string) $content,
|
||||
);
|
||||
}
|
||||
|
||||
$content = $this->validate_content_type( $content, $prompt_name );
|
||||
|
||||
return PromptMessage::fromArray(
|
||||
array(
|
||||
'role' => $role,
|
||||
'content' => $content,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate content type against ContentBlockFactory registry.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $content Content array with 'type' key.
|
||||
* @param string $prompt_name Prompt name for logging.
|
||||
*
|
||||
* @return array Validated content array (may be modified if invalid type).
|
||||
*/
|
||||
private function validate_content_type( array $content, string $prompt_name ): array {
|
||||
$type = $content['type'] ?? null;
|
||||
|
||||
// Check if type is missing.
|
||||
if ( null === $type || '' === $type ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Missing content type in prompt result, defaulting to text',
|
||||
array(
|
||||
'prompt_name' => $prompt_name,
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
|
||||
$text = isset( $content['text'] ) ? (string) $content['text'] : wp_json_encode( $content, JSON_PRETTY_PRINT );
|
||||
|
||||
return array(
|
||||
'type' => 'text',
|
||||
'text' => false === $text ? '{}' : $text,
|
||||
);
|
||||
}
|
||||
|
||||
// Check if type is valid.
|
||||
if ( ! in_array( $type, self::$valid_content_types, true ) ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Invalid content type in prompt result, converting to text',
|
||||
array(
|
||||
'prompt_name' => $prompt_name,
|
||||
'invalid_type' => $type,
|
||||
'valid_types' => self::$valid_content_types,
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
|
||||
// Convert the entire content to a text representation.
|
||||
$json_content = wp_json_encode( $content, JSON_PRETTY_PRINT );
|
||||
if ( false === $json_content ) {
|
||||
$json_content = '{}';
|
||||
}
|
||||
|
||||
return array(
|
||||
'type' => 'text',
|
||||
'text' => $json_content,
|
||||
);
|
||||
}
|
||||
|
||||
// Type is valid, return content as-is (preserves annotations).
|
||||
return $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate role value and apply default if invalid.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $role Role value to validate.
|
||||
* @param string $prompt_name Prompt name for logging (empty to skip logging).
|
||||
*
|
||||
* @return string Valid role value.
|
||||
*/
|
||||
private function validate_role( string $role, string $prompt_name ): string {
|
||||
if ( in_array( $role, self::$valid_roles, true ) ) {
|
||||
return $role;
|
||||
}
|
||||
|
||||
if ( '' !== $prompt_name ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Invalid role in prompt message, defaulting to user',
|
||||
array(
|
||||
'prompt_name' => $prompt_name,
|
||||
'invalid_role' => $role,
|
||||
'valid_roles' => self::$valid_roles,
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
|
||||
return self::$default_role;
|
||||
}
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
<?php
|
||||
/**
|
||||
* Resources method handlers for MCP requests.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Handlers\Resources;
|
||||
|
||||
use WP\MCP\Core\McpServer;
|
||||
use WP\MCP\Handlers\HandlerHelperTrait;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\McpErrorFactory;
|
||||
use WP\McpSchema\Common\Protocol\DTO\BlobResourceContents;
|
||||
use WP\McpSchema\Common\Protocol\DTO\TextResourceContents;
|
||||
use WP\McpSchema\Server\Resources\DTO\ListResourcesResult;
|
||||
use WP\McpSchema\Server\Resources\DTO\ReadResourceResult;
|
||||
|
||||
/**
|
||||
* Handles resources-related MCP methods.
|
||||
*/
|
||||
class ResourcesHandler {
|
||||
use HandlerHelperTrait;
|
||||
|
||||
/**
|
||||
* The WordPress MCP instance.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
private McpServer $mcp;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP\MCP\Core\McpServer $mcp The WordPress MCP instance.
|
||||
*/
|
||||
public function __construct( McpServer $mcp ) {
|
||||
$this->mcp = $mcp;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handles the resources/list request.
|
||||
*
|
||||
* Returns a ListResourcesResult DTO containing all registered resources.
|
||||
* Returns protocol DTOs as-is; any `_meta` fields are passed through unchanged.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Resources\DTO\ListResourcesResult Response with resources list.
|
||||
*/
|
||||
public function list_resources(): ListResourcesResult {
|
||||
$resources = array_values( $this->mcp->get_resources() );
|
||||
|
||||
/**
|
||||
* Filters the list of resources before returning to the client.
|
||||
*
|
||||
* Use this filter to filter resources by context, add dynamic resources,
|
||||
* or reorder the resources list.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array<\WP\McpSchema\Server\Resources\DTO\Resource> $resources Array of Resource DTOs.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$resources = $this->validate_filtered_list(
|
||||
apply_filters( 'mcp_adapter_resources_list', $resources, $this->mcp ),
|
||||
$resources,
|
||||
'mcp_adapter_resources_list',
|
||||
$this->mcp->get_error_handler()
|
||||
);
|
||||
|
||||
return ListResourcesResult::fromArray(
|
||||
array(
|
||||
'resources' => $resources,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the resources/read request.
|
||||
*
|
||||
* Returns either a ReadResourceResult DTO (for success) or a JSONRPCErrorResponse DTO
|
||||
* (for protocol errors like missing parameter or resource not found).
|
||||
*
|
||||
* Unlike tools, resources don't have a concept of "execution errors" that should be
|
||||
* reported with isError=true. Resource reads either succeed or fail at the protocol level.
|
||||
*
|
||||
* @param array $params Request parameters.
|
||||
* @param string|int|null $request_id Optional. The request ID for JSON-RPC. Default 0.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Resources\DTO\ReadResourceResult|\WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public function read_resource( array $params, $request_id = 0 ) {
|
||||
// Extract parameters using helper method.
|
||||
$request_params = $this->extract_params( $params );
|
||||
|
||||
if ( ! isset( $request_params['uri'] ) ) {
|
||||
return McpErrorFactory::missing_parameter( $request_id, 'uri' );
|
||||
}
|
||||
|
||||
$uri = $request_params['uri'];
|
||||
$uri = is_string( $uri ) ? trim( $uri ) : '';
|
||||
|
||||
$mcp_resource = $this->mcp->get_mcp_resource( $uri );
|
||||
if ( ! $mcp_resource ) {
|
||||
return McpErrorFactory::resource_not_found( $request_id, $uri );
|
||||
}
|
||||
|
||||
/** @var \WP\McpSchema\Server\Resources\DTO\Resource $resource */
|
||||
$resource = $mcp_resource->get_protocol_dto();
|
||||
|
||||
try {
|
||||
$has_permission = $mcp_resource->check_permission( $request_params );
|
||||
if ( true !== $has_permission ) {
|
||||
// Extract detailed error message if WP_Error was returned.
|
||||
$error_message = 'Access denied for resource: ' . $resource->getName();
|
||||
|
||||
if ( is_wp_error( $has_permission ) ) {
|
||||
$error_message = $has_permission->get_error_message();
|
||||
}
|
||||
|
||||
return McpErrorFactory::permission_denied( $request_id, $error_message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters resource parameters before execution, or short-circuits execution entirely.
|
||||
*
|
||||
* Return the (optionally modified) parameters array to proceed with execution,
|
||||
* or return a WP_Error to block execution and return an error to the client.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $params The request parameters.
|
||||
* @param string $uri The resource URI.
|
||||
* @param \WP\MCP\Domain\Resources\McpResource $mcp_resource The MCP resource instance.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$request_params = apply_filters( 'mcp_adapter_pre_resource_read', $request_params, $uri, $mcp_resource, $this->mcp );
|
||||
|
||||
// Allow pre-filter to short-circuit execution by returning WP_Error.
|
||||
if ( is_wp_error( $request_params ) ) {
|
||||
return McpErrorFactory::internal_error( $request_id, $request_params->get_error_message() );
|
||||
}
|
||||
|
||||
$contents = $mcp_resource->execute( $request_params );
|
||||
|
||||
/**
|
||||
* Filters the resource contents after execution.
|
||||
*
|
||||
* Use this filter for content transformation, caching storage,
|
||||
* PII redaction, or audit logging.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param mixed|\WP_Error $contents The raw resource contents (may be WP_Error).
|
||||
* @param array $params The request parameters used.
|
||||
* @param string $uri The resource URI.
|
||||
* @param \WP\MCP\Domain\Resources\McpResource $mcp_resource The MCP resource instance.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$contents = apply_filters( 'mcp_adapter_resource_read_result', $contents, $request_params, $uri, $mcp_resource, $this->mcp );
|
||||
|
||||
// Handle WP_Error objects returned by McpResource execution.
|
||||
if ( is_wp_error( $contents ) ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Resource execution returned WP_Error object',
|
||||
array(
|
||||
'uri' => $uri,
|
||||
'error_code' => $contents->get_error_code(),
|
||||
'error_message' => $contents->get_error_message(),
|
||||
)
|
||||
);
|
||||
|
||||
return McpErrorFactory::internal_error( $request_id, $contents->get_error_message() );
|
||||
}
|
||||
|
||||
// Successful execution - convert contents to DTOs.
|
||||
// Contents should be an array of resource content items.
|
||||
// If it's already an array of properly formatted items, convert each to a DTO.
|
||||
// Otherwise, wrap the result as text content.
|
||||
$content_dtos = $this->convert_contents_to_dtos( $contents, $uri );
|
||||
|
||||
return ReadResourceResult::fromArray(
|
||||
array(
|
||||
'contents' => $content_dtos,
|
||||
)
|
||||
);
|
||||
} catch ( \Throwable $exception ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Error reading resource',
|
||||
array(
|
||||
'uri' => $uri,
|
||||
'exception' => $exception->getMessage(),
|
||||
)
|
||||
);
|
||||
|
||||
return McpErrorFactory::internal_error( $request_id, 'Failed to read resource' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ability execution results to resource content DTOs.
|
||||
*
|
||||
* The MCP spec expects contents to be an array of TextResourceContents or BlobResourceContents.
|
||||
* This method handles various return formats from abilities and normalizes them.
|
||||
*
|
||||
* @param mixed $contents The contents returned by the ability.
|
||||
* @param string $uri The resource URI.
|
||||
*
|
||||
* @return array<\WP\McpSchema\Common\Protocol\DTO\TextResourceContents|\WP\McpSchema\Common\Protocol\DTO\BlobResourceContents>
|
||||
*/
|
||||
private function convert_contents_to_dtos( $contents, string $uri ): array {
|
||||
// If contents is already an array of properly structured items, convert each.
|
||||
if ( is_array( $contents ) && ! empty( $contents ) ) {
|
||||
// Check if this is an array of content items (has 'uri' or 'text' keys in first item).
|
||||
$first_item = reset( $contents );
|
||||
if ( is_array( $first_item ) && ( isset( $first_item['uri'] ) || isset( $first_item['text'] ) ) ) {
|
||||
return array_map(
|
||||
function ( $item ) use ( $uri ) {
|
||||
return $this->create_content_dto( $item, $uri );
|
||||
},
|
||||
$contents
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: wrap as a single text content item.
|
||||
if ( is_string( $contents ) ) {
|
||||
$text = $contents;
|
||||
} else {
|
||||
$text = wp_json_encode( $contents );
|
||||
if ( false === $text ) {
|
||||
$text = '{}';
|
||||
}
|
||||
}
|
||||
|
||||
return array(
|
||||
TextResourceContents::fromArray(
|
||||
array(
|
||||
'uri' => $uri,
|
||||
'text' => $text,
|
||||
)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a content DTO from an array item.
|
||||
*
|
||||
* @param array $item The content item array.
|
||||
* @param string $default_uri The default URI to use if not specified.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\Protocol\DTO\TextResourceContents|\WP\McpSchema\Common\Protocol\DTO\BlobResourceContents
|
||||
*/
|
||||
private function create_content_dto( array $item, string $default_uri ) {
|
||||
$item_uri = $item['uri'] ?? $default_uri;
|
||||
$mime_type = $item['mimeType'] ?? null;
|
||||
|
||||
// If there's blob data, create BlobResourceContents.
|
||||
if ( isset( $item['blob'] ) ) {
|
||||
return BlobResourceContents::fromArray(
|
||||
array(
|
||||
'uri' => $item_uri,
|
||||
'blob' => (string) $item['blob'],
|
||||
'mimeType' => is_string( $mime_type ) ? $mime_type : null,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Default to TextResourceContents.
|
||||
$text = $item['text'] ?? '';
|
||||
|
||||
return TextResourceContents::fromArray(
|
||||
array(
|
||||
'uri' => $item_uri,
|
||||
'text' => (string) $text,
|
||||
'mimeType' => is_string( $mime_type ) ? $mime_type : null,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
/**
|
||||
* System method handlers for MCP requests.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Handlers\System;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Protocol\DTO\Result;
|
||||
|
||||
/**
|
||||
* Handles system-related MCP methods.
|
||||
*/
|
||||
class SystemHandler {
|
||||
/**
|
||||
* Handles the ping request.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\AbstractDataTransferObject Empty result DTO per MCP specification.
|
||||
*/
|
||||
public function ping(): AbstractDataTransferObject {
|
||||
return Result::fromArray( array() );
|
||||
}
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
<?php
|
||||
/**
|
||||
* Tools method handlers for MCP requests.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Handlers\Tools;
|
||||
|
||||
use WP\MCP\Core\McpServer;
|
||||
use WP\MCP\Domain\Utils\ContentBlockHelper;
|
||||
use WP\MCP\Handlers\HandlerHelperTrait;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\McpErrorFactory;
|
||||
use WP\MCP\Infrastructure\Observability\FailureReason;
|
||||
use WP\McpSchema\Server\Tools\DTO\CallToolResult;
|
||||
use WP\McpSchema\Server\Tools\DTO\ListToolsResult;
|
||||
|
||||
/**
|
||||
* Handles tools-related MCP methods.
|
||||
*/
|
||||
class ToolsHandler {
|
||||
use HandlerHelperTrait;
|
||||
|
||||
/**
|
||||
* Default MIME type for image results when none is specified.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const DEFAULT_IMAGE_MIME_TYPE = 'image/png';
|
||||
|
||||
/**
|
||||
* The WordPress MCP instance.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
private McpServer $mcp;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP\MCP\Core\McpServer $mcp The WordPress MCP instance.
|
||||
*/
|
||||
public function __construct( McpServer $mcp ) {
|
||||
$this->mcp = $mcp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the tools/list/all request.
|
||||
*
|
||||
* This is a custom extension to the MCP spec that includes availability status.
|
||||
* Returns a ListToolsResult DTO containing all registered tools.
|
||||
*
|
||||
* Note: The 'available' flag is a non-standard extension and is not currently implemented.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Tools\DTO\ListToolsResult Response with all tools.
|
||||
*/
|
||||
public function list_all_tools(): ListToolsResult {
|
||||
// Return the standard tools list.
|
||||
return $this->list_tools();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the tools/list request.
|
||||
*
|
||||
* Returns a ListToolsResult DTO containing all registered tools.
|
||||
* Tool DTOs are protocol-only; internal adapter metadata is stored in McpTool instances and is never exposed
|
||||
* to MCP clients.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Tools\DTO\ListToolsResult Response with tools list.
|
||||
*/
|
||||
public function list_tools(): ListToolsResult {
|
||||
$tools = array_values( $this->mcp->get_tools() );
|
||||
|
||||
/**
|
||||
* Filters the list of tools before returning to the client.
|
||||
*
|
||||
* Use this filter to hide tools per user/role, add dynamic tools,
|
||||
* or reorder the tools list.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array<\WP\McpSchema\Server\Tools\DTO\Tool> $tools Array of Tool DTOs.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$tools = $this->validate_filtered_list(
|
||||
apply_filters( 'mcp_adapter_tools_list', $tools, $this->mcp ),
|
||||
$tools,
|
||||
'mcp_adapter_tools_list',
|
||||
$this->mcp->get_error_handler()
|
||||
);
|
||||
|
||||
return ListToolsResult::fromArray(
|
||||
array(
|
||||
'tools' => $tools,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the tools/call request.
|
||||
*
|
||||
* Returns either a CallToolResult DTO (for success or tool execution errors)
|
||||
* or a JSONRPCErrorResponse DTO (for protocol errors like tool not found).
|
||||
*
|
||||
* The MCP spec distinguishes between:
|
||||
* 1. **Protocol errors** (tool not found, server error) → JSONRPCErrorResponse
|
||||
* 2. **Tool execution errors** (permission denied, runtime error) → CallToolResult with isError=true
|
||||
*
|
||||
* This distinction is critical for LLM self-correction - execution errors are
|
||||
* visible to the LLM, while protocol errors indicate infrastructure issues.
|
||||
*
|
||||
* @param array $params Request params.
|
||||
* @param string|int|null $request_id Optional. The request ID for JSON-RPC. Default 0.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Tools\DTO\CallToolResult|\WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public function call_tool( array $params, $request_id = 0 ) {
|
||||
// Extract parameters using helper method.
|
||||
$request_params = $this->extract_params( $params );
|
||||
|
||||
if ( ! isset( $request_params['name'] ) ) {
|
||||
return McpErrorFactory::missing_parameter( $request_id, 'tool name' );
|
||||
}
|
||||
|
||||
if ( isset( $request_params['arguments'] ) && ! is_array( $request_params['arguments'] ) ) {
|
||||
return McpErrorFactory::invalid_params( $request_id, 'arguments must be an object' );
|
||||
}
|
||||
|
||||
try {
|
||||
$tool_name = trim( (string) $request_params['name'] );
|
||||
$args = $request_params['arguments'] ?? array();
|
||||
|
||||
$mcp_tool = $this->mcp->get_mcp_tool( $tool_name );
|
||||
if ( ! $mcp_tool ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Tool not found',
|
||||
array(
|
||||
'tool_name' => $tool_name,
|
||||
),
|
||||
'warning'
|
||||
);
|
||||
|
||||
return McpErrorFactory::tool_not_found( $request_id, $tool_name );
|
||||
}
|
||||
|
||||
$permission = $mcp_tool->check_permission( $args );
|
||||
if ( true !== $permission ) {
|
||||
$error_message = __( 'Permission denied', 'mcp-adapter' );
|
||||
if ( is_wp_error( $permission ) ) {
|
||||
$error_message = $permission->get_error_message();
|
||||
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Tool permission check failed',
|
||||
array(
|
||||
'tool_name' => $tool_name,
|
||||
'error_code' => $permission->get_error_code(),
|
||||
'error_message' => $permission->get_error_message(),
|
||||
'error_data' => $permission->get_error_data(),
|
||||
'failure_reason' => FailureReason::PERMISSION_CHECK_FAILED,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $this->create_error_result( $error_message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters tool arguments before execution, or short-circuits execution entirely.
|
||||
*
|
||||
* Return the (optionally modified) arguments array to proceed with execution,
|
||||
* or return a WP_Error to block execution and return an error to the client.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param array $args The tool arguments.
|
||||
* @param string $tool_name The tool name being called.
|
||||
* @param \WP\MCP\Domain\Tools\McpTool $mcp_tool The MCP tool instance.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$args = apply_filters( 'mcp_adapter_pre_tool_call', $args, $tool_name, $mcp_tool, $this->mcp );
|
||||
|
||||
// Allow pre-filter to short-circuit execution by returning WP_Error.
|
||||
if ( is_wp_error( $args ) ) {
|
||||
return $this->create_error_result( $args->get_error_message() );
|
||||
}
|
||||
|
||||
$result = $mcp_tool->execute( $args );
|
||||
|
||||
/**
|
||||
* Filters the tool execution result before response assembly.
|
||||
*
|
||||
* Use this filter for result transformation, PII redaction,
|
||||
* audit logging, or content enrichment.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param mixed|\WP_Error $result The raw execution result (may be WP_Error).
|
||||
* @param array $args The tool arguments used.
|
||||
* @param string $tool_name The tool name that was called.
|
||||
* @param \WP\MCP\Domain\Tools\McpTool $mcp_tool The MCP tool instance.
|
||||
* @param \WP\MCP\Core\McpServer $server The MCP server instance.
|
||||
*/
|
||||
$result = apply_filters( 'mcp_adapter_tool_call_result', $result, $args, $tool_name, $mcp_tool, $this->mcp );
|
||||
|
||||
if ( is_wp_error( $result ) ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Tool execution returned WP_Error',
|
||||
array(
|
||||
'tool_name' => $tool_name,
|
||||
'error_code' => $result->get_error_code(),
|
||||
'error_message' => $result->get_error_message(),
|
||||
'error_data' => $result->get_error_data(),
|
||||
)
|
||||
);
|
||||
|
||||
return $this->create_error_result( $result->get_error_message() );
|
||||
}
|
||||
|
||||
// Backward compatibility: treat `{ success: false, error: string }` as tool execution error.
|
||||
if (
|
||||
is_array( $result )
|
||||
&& array_key_exists( 'success', $result )
|
||||
&& false === $result['success']
|
||||
&& isset( $result['error'] )
|
||||
&& is_string( $result['error'] )
|
||||
&& '' !== trim( $result['error'] )
|
||||
) {
|
||||
return $this->create_error_result( $result['error'] );
|
||||
}
|
||||
|
||||
// Successful tool execution - build CallToolResult DTO.
|
||||
|
||||
// Handle embedded resource results (MCP ContentBlock type: "resource").
|
||||
// This allows tools to return text/blob resources using the MCP schema's EmbeddedResource content block.
|
||||
if ( isset( $result['type'] ) && 'resource' === $result['type'] ) {
|
||||
$resource_item = $result;
|
||||
if ( isset( $result['resource'] ) && is_array( $result['resource'] ) ) {
|
||||
$resource_item = $result['resource'];
|
||||
}
|
||||
|
||||
$uri = $resource_item['uri'] ?? null;
|
||||
$mime_type = $resource_item['mimeType'] ?? null;
|
||||
|
||||
if ( is_string( $uri ) ) {
|
||||
$uri = trim( $uri );
|
||||
}
|
||||
|
||||
// Only return an EmbeddedResource if we have a valid URI and some content.
|
||||
if ( is_string( $uri ) && '' !== $uri ) {
|
||||
if ( isset( $resource_item['text'] ) && is_string( $resource_item['text'] ) ) {
|
||||
return CallToolResult::fromArray(
|
||||
array(
|
||||
'content' => array(
|
||||
ContentBlockHelper::embedded_text_resource(
|
||||
$uri,
|
||||
$resource_item['text'],
|
||||
is_string( $mime_type ) ? $mime_type : null
|
||||
),
|
||||
),
|
||||
'isError' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if ( isset( $resource_item['blob'] ) && is_string( $resource_item['blob'] ) ) {
|
||||
return CallToolResult::fromArray(
|
||||
array(
|
||||
'content' => array(
|
||||
ContentBlockHelper::embedded_blob_resource(
|
||||
$uri,
|
||||
$resource_item['blob'],
|
||||
is_string( $mime_type ) ? $mime_type : null
|
||||
),
|
||||
),
|
||||
'isError' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle image results.
|
||||
if ( isset( $result['type'] ) && 'image' === $result['type'] && isset( $result['results'] ) ) {
|
||||
$image_data = base64_encode( $result['results'] ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
|
||||
$mime_type = $result['mimeType'] ?? self::DEFAULT_IMAGE_MIME_TYPE;
|
||||
|
||||
return CallToolResult::fromArray(
|
||||
array(
|
||||
'content' => array( ContentBlockHelper::image( $image_data, $mime_type ) ),
|
||||
'structuredContent' => null,
|
||||
'isError' => false,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Standard result - JSON-encode for text content, include as structuredContent.
|
||||
$json_text = wp_json_encode( $result );
|
||||
if ( false === $json_text ) {
|
||||
$json_text = '{}';
|
||||
}
|
||||
|
||||
return CallToolResult::fromArray(
|
||||
array(
|
||||
'content' => array( ContentBlockHelper::text( $json_text ) ),
|
||||
'structuredContent' => $result,
|
||||
'isError' => false,
|
||||
)
|
||||
);
|
||||
} catch ( \Throwable $exception ) {
|
||||
$this->mcp->get_error_handler()->log(
|
||||
'Error calling tool',
|
||||
array(
|
||||
'tool' => $request_params['name'],
|
||||
'exception' => $exception->getMessage(),
|
||||
)
|
||||
);
|
||||
|
||||
return McpErrorFactory::internal_error( $request_id, 'Failed to execute tool' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an error CallToolResult from a message string.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param string $message The error message.
|
||||
*
|
||||
* @return \WP\McpSchema\Server\Tools\DTO\CallToolResult
|
||||
*/
|
||||
private function create_error_result( string $message ): CallToolResult {
|
||||
return CallToolResult::fromArray(
|
||||
array(
|
||||
'content' => array( ContentBlockHelper::text( $message ) ),
|
||||
'structuredContent' => null,
|
||||
'isError' => true,
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
/**
|
||||
* Interface for MCP error handlers.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\ErrorHandling\Contracts;
|
||||
|
||||
/**
|
||||
* Interface for handling MCP error logging.
|
||||
*
|
||||
* This interface defines the contract for error handlers that can log
|
||||
* error messages with context information and different severity types.
|
||||
*/
|
||||
interface McpErrorHandlerInterface {
|
||||
|
||||
/**
|
||||
* Log an error message with optional context and type.
|
||||
*
|
||||
* @param string $message The log message.
|
||||
* @param array $context Additional context data.
|
||||
* @param string $type The log type (e.g., 'error', 'info', 'debug').
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function log( string $message, array $context = array(), string $type = 'error' ): void;
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
/**
|
||||
* ErrorLogMcpErrorHandler class for logging MCP errors to PHP error log.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\ErrorHandling;
|
||||
|
||||
/**
|
||||
* Class ErrorLogMcpErrorHandler
|
||||
*
|
||||
* This class handles error logging by writing logs to the PHP error log.
|
||||
*
|
||||
* @package WP\MCP\ErrorHandlers
|
||||
*/
|
||||
class ErrorLogMcpErrorHandler implements Contracts\McpErrorHandlerInterface {
|
||||
|
||||
/**
|
||||
* Log with context.
|
||||
*
|
||||
* @param string $message The log message.
|
||||
* @param array $context Additional context data.
|
||||
* @param string $type The type of log (e.g., 'error', 'info', etc.). Default is 'error'.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function log( string $message, array $context = array(), string $type = 'error' ): void {
|
||||
$user_id = function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0;
|
||||
$log_message = sprintf(
|
||||
'[%s] %s | Context: %s | User ID: %d',
|
||||
strtoupper( $type ),
|
||||
$message,
|
||||
wp_json_encode( $context ),
|
||||
$user_id
|
||||
);
|
||||
error_log( $log_message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
}
|
||||
}
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
<?php
|
||||
/**
|
||||
* Factory class for creating MCP error responses.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\ErrorHandling;
|
||||
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\Error;
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse;
|
||||
use WP\McpSchema\Common\McpConstants;
|
||||
|
||||
/**
|
||||
* Factory for creating standardized MCP error responses.
|
||||
*
|
||||
* This class provides static methods for creating various types of JSON-RPC
|
||||
* error responses according to the MCP specification. All methods return
|
||||
* typed DTOs from php-mcp-schema for type safety and protocol compliance.
|
||||
*/
|
||||
class McpErrorFactory {
|
||||
|
||||
/**
|
||||
* Standard JSON-RPC error codes as defined in the specification.
|
||||
*/
|
||||
public const PARSE_ERROR = McpConstants::PARSE_ERROR;
|
||||
public const INVALID_REQUEST = McpConstants::INVALID_REQUEST;
|
||||
public const METHOD_NOT_FOUND = McpConstants::METHOD_NOT_FOUND;
|
||||
public const INVALID_PARAMS = McpConstants::INVALID_PARAMS;
|
||||
public const INTERNAL_ERROR = McpConstants::INTERNAL_ERROR;
|
||||
|
||||
/**
|
||||
* Implementation-defined server error codes (in -32000 to -32099 range as per JSON-RPC spec).
|
||||
* Using conservative, well-established error codes only.
|
||||
*/
|
||||
public const SERVER_ERROR = -32000; // Generic server error (includes MCP disabled)
|
||||
public const TIMEOUT_ERROR = -32001; // Request timeout
|
||||
public const RESOURCE_NOT_FOUND = -32002; // Resource not found
|
||||
public const TOOL_NOT_FOUND = -32003; // Tool not found
|
||||
public const PROMPT_NOT_FOUND = -32004; // Prompt not found
|
||||
public const SESSION_NOT_FOUND = -32005; // Session not found or expired
|
||||
public const PERMISSION_DENIED = -32008; // Access denied/forbidden
|
||||
public const UNAUTHORIZED = -32010; // Authentication required
|
||||
|
||||
/**
|
||||
* Create a parse error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Optional additional details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function parse_error( $id, string $details = '' ): JSONRPCErrorResponse {
|
||||
$message = __( 'Parse error', 'mcp-adapter' );
|
||||
if ( $details ) {
|
||||
$message .= ': ' . $details;
|
||||
}
|
||||
|
||||
return self::create_error_response( $id, self::PARSE_ERROR, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a standardized JSON-RPC error response DTO.
|
||||
*
|
||||
* @param string|int|null $id The request ID (JSON-RPC allows string, int, or null).
|
||||
* @param int $code The error code.
|
||||
* @param string $message The error message.
|
||||
* @param mixed|null $data Optional additional error data.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function create_error_response( $id, int $code, string $message, $data = null ): JSONRPCErrorResponse {
|
||||
return JSONRPCErrorResponse::fromArray(
|
||||
array(
|
||||
'jsonrpc' => McpConstants::JSONRPC_VERSION,
|
||||
'error' => self::create_error( $code, $message, $data ),
|
||||
'id' => $id,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an Error DTO.
|
||||
*
|
||||
* @param int $code The error code.
|
||||
* @param string $message The error message.
|
||||
* @param mixed|null $data Optional additional error data.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\Error
|
||||
*/
|
||||
public static function create_error( int $code, string $message, $data = null ): Error {
|
||||
return Error::fromArray(
|
||||
array(
|
||||
'code' => $code,
|
||||
'message' => $message,
|
||||
'data' => $data,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a method not found error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $method The method that was not found.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function method_not_found( $id, string $method ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::METHOD_NOT_FOUND,
|
||||
sprintf(
|
||||
/* translators: %s: method name */
|
||||
__( 'Method not found: %s', 'mcp-adapter' ),
|
||||
$method
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an invalid params error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Optional additional details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function invalid_params( $id, string $details = '' ): JSONRPCErrorResponse {
|
||||
$message = __( 'Invalid params', 'mcp-adapter' );
|
||||
if ( $details ) {
|
||||
$message .= ': ' . $details;
|
||||
}
|
||||
|
||||
return self::create_error_response( $id, self::INVALID_PARAMS, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an internal error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Optional additional details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function internal_error( $id, string $details = '' ): JSONRPCErrorResponse {
|
||||
$message = __( 'Internal error', 'mcp-adapter' );
|
||||
if ( $details ) {
|
||||
$message .= ': ' . $details;
|
||||
}
|
||||
|
||||
return self::create_error_response( $id, self::INTERNAL_ERROR, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an MCP disabled error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function mcp_disabled( $id ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::SERVER_ERROR,
|
||||
__( 'MCP functionality is currently disabled', 'mcp-adapter' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a validation error response (uses standard invalid params error).
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Validation error details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function validation_error( $id, string $details ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::INVALID_PARAMS,
|
||||
sprintf(
|
||||
/* translators: %s: validation details */
|
||||
__( 'Validation error: %s', 'mcp-adapter' ),
|
||||
$details
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a missing parameter error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $parameter The missing parameter name.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function missing_parameter( $id, string $parameter ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::INVALID_PARAMS,
|
||||
sprintf(
|
||||
/* translators: %s: parameter name */
|
||||
__( 'Missing required parameter: %s', 'mcp-adapter' ),
|
||||
$parameter
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a resource not found error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $resource_uri The resource identifier.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function resource_not_found( $id, string $resource_uri ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::RESOURCE_NOT_FOUND,
|
||||
sprintf(
|
||||
/* translators: %s: resource identifier */
|
||||
__( 'Resource not found: %s', 'mcp-adapter' ),
|
||||
$resource_uri
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a tool not found error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $tool The tool name.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function tool_not_found( $id, string $tool ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::TOOL_NOT_FOUND,
|
||||
sprintf(
|
||||
/* translators: %s: tool name */
|
||||
__( 'Tool not found: %s', 'mcp-adapter' ),
|
||||
$tool
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ability not found error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $ability The ability name.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function ability_not_found( $id, string $ability ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::TOOL_NOT_FOUND,
|
||||
sprintf(
|
||||
/* translators: %s: ability name */
|
||||
__( 'Ability not found: %s', 'mcp-adapter' ),
|
||||
$ability
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a prompt not found error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $prompt The prompt name.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function prompt_not_found( $id, string $prompt ): JSONRPCErrorResponse {
|
||||
return self::create_error_response(
|
||||
$id,
|
||||
self::PROMPT_NOT_FOUND,
|
||||
sprintf(
|
||||
/* translators: %s: prompt name */
|
||||
__( 'Prompt not found: %s', 'mcp-adapter' ),
|
||||
$prompt
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a session not found error response.
|
||||
*
|
||||
* Used when an MCP session ID is invalid or expired. Maps to HTTP 404
|
||||
* per the MCP specification requirement for invalid/expired sessions.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Optional additional details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function session_not_found( $id, string $details = '' ): JSONRPCErrorResponse {
|
||||
$message = __( 'Session not found', 'mcp-adapter' );
|
||||
if ( $details ) {
|
||||
$message .= ': ' . $details;
|
||||
}
|
||||
|
||||
return self::create_error_response( $id, self::SESSION_NOT_FOUND, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a permission denied error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Optional additional details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function permission_denied( $id, string $details = '' ): JSONRPCErrorResponse {
|
||||
$message = __( 'Permission denied', 'mcp-adapter' );
|
||||
if ( $details ) {
|
||||
$message .= ': ' . $details;
|
||||
}
|
||||
|
||||
return self::create_error_response( $id, self::PERMISSION_DENIED, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an unauthorized error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Optional additional details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function unauthorized( $id, string $details = '' ): JSONRPCErrorResponse {
|
||||
$message = __( 'Unauthorized', 'mcp-adapter' );
|
||||
if ( $details ) {
|
||||
$message .= ': ' . $details;
|
||||
}
|
||||
|
||||
return self::create_error_response( $id, self::UNAUTHORIZED, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if an MCP error should return HTTP 200 or an HTTP error status.
|
||||
*
|
||||
* This method helps distinguish between transport-level errors (which should
|
||||
* return HTTP error codes) and application-level errors (which should return
|
||||
* HTTP 200 with a JSON-RPC error response).
|
||||
*
|
||||
* @param \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse|array $error_response The MCP error response (DTO or array).
|
||||
*
|
||||
* @return int The appropriate HTTP status code.
|
||||
*/
|
||||
public static function get_http_status_for_error( $error_response ): int {
|
||||
// Handle DTO
|
||||
if ( $error_response instanceof JSONRPCErrorResponse ) {
|
||||
return self::mcp_error_to_http_status( $error_response->getError()->getCode() );
|
||||
}
|
||||
|
||||
// Handle legacy array format
|
||||
if ( ! isset( $error_response['error']['code'] ) ) {
|
||||
return 500; // Invalid error response structure
|
||||
}
|
||||
|
||||
return self::mcp_error_to_http_status( $error_response['error']['code'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate MCP error code to appropriate HTTP status code.
|
||||
*
|
||||
* Maps JSON-RPC error codes to HTTP status codes according to best practices:
|
||||
* - Transport-level errors (malformed JSON-RPC) → HTTP 4xx
|
||||
* - Application-level errors (business logic) → HTTP 200 with JSON-RPC error
|
||||
*
|
||||
* @param int|string|float $mcp_error_code The MCP/JSON-RPC error code (integer, float, or string).
|
||||
*
|
||||
* @return int The appropriate HTTP status code.
|
||||
*/
|
||||
public static function mcp_error_to_http_status( $mcp_error_code ): int {
|
||||
// Cast to integer for comparison (handles float from DTOs)
|
||||
$code = is_numeric( $mcp_error_code ) ? (int) $mcp_error_code : 0;
|
||||
|
||||
switch ( $code ) {
|
||||
// Transport-level errors - these indicate malformed requests
|
||||
case self::PARSE_ERROR: // Invalid JSON - syntactic error
|
||||
return 400;
|
||||
|
||||
case self::INVALID_REQUEST: // Invalid JSON-RPC structure - syntactic error
|
||||
return 400;
|
||||
|
||||
// Authentication and authorization errors
|
||||
case self::UNAUTHORIZED: // Authentication required
|
||||
return 401;
|
||||
|
||||
case self::PERMISSION_DENIED: // Access forbidden
|
||||
return 403;
|
||||
|
||||
// Resource not found errors
|
||||
case self::RESOURCE_NOT_FOUND:
|
||||
case self::TOOL_NOT_FOUND:
|
||||
case self::PROMPT_NOT_FOUND:
|
||||
case self::SESSION_NOT_FOUND:
|
||||
case self::METHOD_NOT_FOUND:
|
||||
return 404;
|
||||
|
||||
// Server errors
|
||||
case self::INTERNAL_ERROR:
|
||||
case self::SERVER_ERROR:
|
||||
return 500;
|
||||
|
||||
case self::TIMEOUT_ERROR:
|
||||
return 504;
|
||||
|
||||
// Application-level errors - return 200 with JSON-RPC error
|
||||
case self::INVALID_PARAMS:
|
||||
default:
|
||||
return 200;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate JSON-RPC message structure.
|
||||
*
|
||||
* @param mixed $message The message to validate.
|
||||
*
|
||||
* @return true|\WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse Returns true if valid, or JSONRPCErrorResponse DTO if invalid.
|
||||
*/
|
||||
public static function validate_jsonrpc_message( $message ) {
|
||||
if ( ! is_array( $message ) ) {
|
||||
return self::invalid_request( null, __( 'Message must be a JSON object', 'mcp-adapter' ) );
|
||||
}
|
||||
|
||||
// Must have jsonrpc field with value "2.0".
|
||||
if ( ! isset( $message['jsonrpc'] ) || McpConstants::JSONRPC_VERSION !== $message['jsonrpc'] ) {
|
||||
return self::invalid_request(
|
||||
null,
|
||||
sprintf(
|
||||
/* translators: %s: JSON-RPC version */
|
||||
__( 'jsonrpc version must be "%s"', 'mcp-adapter' ),
|
||||
McpConstants::JSONRPC_VERSION
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Must be either a request/notification (has method) or a response (has result/error).
|
||||
$is_request_or_notification = isset( $message['method'] );
|
||||
$is_response = isset( $message['result'] ) || isset( $message['error'] );
|
||||
|
||||
if ( ! $is_request_or_notification && ! $is_response ) {
|
||||
return self::invalid_request( null, __( 'Message must have either method or result/error field', 'mcp-adapter' ) );
|
||||
}
|
||||
|
||||
// Responses must have an id field.
|
||||
if ( $is_response && ! isset( $message['id'] ) ) {
|
||||
return self::invalid_request( null, __( 'Response messages must have an id field', 'mcp-adapter' ) );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an invalid request error response.
|
||||
*
|
||||
* @param string|int|null $id The request ID.
|
||||
* @param string $details Optional additional details.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
public static function invalid_request( $id, string $details = '' ): JSONRPCErrorResponse {
|
||||
$message = __( 'Invalid Request', 'mcp-adapter' );
|
||||
if ( $details ) {
|
||||
$message .= ': ' . $details;
|
||||
}
|
||||
|
||||
return self::create_error_response( $id, self::INVALID_REQUEST, $message );
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
/**
|
||||
* NullMcpErrorHandler class for handling MCP errors without logging.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\ErrorHandling;
|
||||
|
||||
/**
|
||||
* Class NullMcpErrorHandler
|
||||
*
|
||||
* This class handles MCP errors by doing nothing. It is used when no error handling is desired.
|
||||
*
|
||||
* @package WP\MCP\ErrorHandlers
|
||||
*/
|
||||
class NullMcpErrorHandler implements Contracts\McpErrorHandlerInterface {
|
||||
|
||||
/**
|
||||
* Log with context.
|
||||
*
|
||||
* This method does nothing and is used when no error handling is desired.
|
||||
*
|
||||
* @param string $message The log message.
|
||||
* @param array $context Additional context data.
|
||||
* @param string $type The type of log (e.g., 'error', 'info', etc.). Default is 'error'.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function log( string $message, array $context = array(), string $type = 'error' ): void {
|
||||
// Do nothing.
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
/**
|
||||
* Console Observability Handler for testing and debugging.
|
||||
*
|
||||
* Outputs formatted observability events to stdout for easy testing.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\Observability;
|
||||
|
||||
use WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface;
|
||||
|
||||
/**
|
||||
* Console-based observability handler for testing.
|
||||
*
|
||||
* Outputs nicely formatted events to stdout/error_log with JSON formatting.
|
||||
*/
|
||||
class ConsoleObservabilityHandler implements McpObservabilityHandlerInterface {
|
||||
|
||||
use McpObservabilityHelperTrait;
|
||||
|
||||
/**
|
||||
* Record an event with formatted output.
|
||||
*
|
||||
* @param string $event The event name.
|
||||
* @param array $tags Tags to attach.
|
||||
* @param float|null $duration_ms Duration in milliseconds.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function record_event( string $event, array $tags = array(), ?float $duration_ms = null ): void {
|
||||
$formatted_event = self::format_metric_name( $event );
|
||||
$merged_tags = self::merge_tags( $tags );
|
||||
|
||||
// Create a structured output
|
||||
$output = array(
|
||||
'event' => $formatted_event,
|
||||
'duration_ms' => $duration_ms,
|
||||
'tags' => $merged_tags,
|
||||
'timestamp' => gmdate( 'Y-m-d H:i:s' ),
|
||||
);
|
||||
|
||||
// Pretty print JSON for readability
|
||||
$json = wp_json_encode( $output, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
|
||||
|
||||
// Output with visual separator
|
||||
$separator = str_repeat( '=', 80 );
|
||||
$message = "\n{$separator}\n[MCP OBSERVABILITY EVENT]\n{$separator}\n{$json}\n{$separator}\n";
|
||||
|
||||
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
error_log( $message );
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
/**
|
||||
* Interface for MCP observability handlers.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\Observability\Contracts;
|
||||
|
||||
/**
|
||||
* Interface for handling MCP observability metrics and tracking.
|
||||
*
|
||||
* This interface defines the contract for observability handlers that can
|
||||
* track metrics like request counts, timing, and error rates in the MCP adapter.
|
||||
* Concrete implementations can integrate with various observability systems.
|
||||
*/
|
||||
interface McpObservabilityHandlerInterface {
|
||||
|
||||
/**
|
||||
* Emit a countable event for tracking with optional timing data.
|
||||
*
|
||||
* @param string $event The event name to record.
|
||||
* @param array $tags Optional tags to attach to the event.
|
||||
* @param float|null $duration_ms Optional duration in milliseconds for timing measurements.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function record_event( string $event, array $tags = array(), ?float $duration_ms = null ): void;
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
/**
|
||||
* ErrorLogMcpObservabilityHandler class for logging MCP observability metrics to PHP error log.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\Observability;
|
||||
|
||||
/**
|
||||
* Class ErrorLogMcpObservabilityHandler
|
||||
*
|
||||
* This class handles observability tracking by writing metrics to the PHP error log.
|
||||
* This provides a simple way to track MCP metrics without external dependencies.
|
||||
*
|
||||
* @package WP\MCP\ObservabilityHandlers
|
||||
*/
|
||||
class ErrorLogMcpObservabilityHandler implements Contracts\McpObservabilityHandlerInterface {
|
||||
|
||||
use McpObservabilityHelperTrait;
|
||||
|
||||
/**
|
||||
* Emit a countable event for tracking with optional timing data.
|
||||
*
|
||||
* @param string $event The event name to record.
|
||||
* @param array $tags Optional tags to attach to the event.
|
||||
* @param float|null $duration_ms Optional duration in milliseconds for timing measurements.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function record_event( string $event, array $tags = array(), ?float $duration_ms = null ): void {
|
||||
$formatted_event = self::format_metric_name( $event );
|
||||
$merged_tags = self::merge_tags( $tags );
|
||||
$formatted_tags = self::format_tags( $merged_tags );
|
||||
|
||||
// Include timing data if provided
|
||||
if ( null !== $duration_ms ) {
|
||||
$log_message = sprintf(
|
||||
'[MCP Observability] EVENT %s %.2fms %s',
|
||||
$formatted_event,
|
||||
$duration_ms,
|
||||
$formatted_tags
|
||||
);
|
||||
} else {
|
||||
$log_message = sprintf(
|
||||
'[MCP Observability] EVENT %s %s',
|
||||
$formatted_event,
|
||||
$formatted_tags
|
||||
);
|
||||
}
|
||||
|
||||
error_log( $log_message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
}
|
||||
|
||||
/**
|
||||
* Format tags array into a readable string for logging.
|
||||
*
|
||||
* @param array $tags The tags to format.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private static function format_tags( array $tags ): string {
|
||||
if ( empty( $tags ) ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$formatted = array_map(
|
||||
static function ( $key, $value ) {
|
||||
return sprintf( '%s=%s', $key, $value );
|
||||
},
|
||||
array_keys( $tags ),
|
||||
array_values( $tags )
|
||||
);
|
||||
|
||||
return '[' . implode( ',', $formatted ) . ']';
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
/**
|
||||
* Centralized failure reason taxonomy for observability.
|
||||
*
|
||||
* This class defines a stable, documented vocabulary of failure reasons
|
||||
* used in observability events and error metadata. Using constants ensures
|
||||
* consistent categorization across all MCP adapter components.
|
||||
*
|
||||
* @package McpAdapter
|
||||
* @since 0.5.0
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\Observability;
|
||||
|
||||
/**
|
||||
* Failure reason taxonomy for observability events.
|
||||
*
|
||||
* Categories:
|
||||
* - Registration failures: Occur during component registration at boot time
|
||||
* - Permission failures: Occur when permission checks fail at execution time
|
||||
* - Execution failures: Occur during component execution
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
final class FailureReason {
|
||||
|
||||
// =========================================================================
|
||||
// Registration Failures
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* WordPress ability was not found in the registry.
|
||||
*
|
||||
* Occurs when an ability name is passed to register_tools/resources/prompts
|
||||
* but wp_get_ability() returns null.
|
||||
*/
|
||||
public const ABILITY_NOT_FOUND = 'ability_not_found';
|
||||
|
||||
/**
|
||||
* A resource with the same URI is already registered.
|
||||
*
|
||||
* MCP resources must have unique URIs. This failure occurs when
|
||||
* attempting to register a duplicate.
|
||||
*/
|
||||
public const DUPLICATE_URI = 'duplicate_uri';
|
||||
|
||||
/**
|
||||
* Prompt builder threw an exception during instantiation or build.
|
||||
*
|
||||
* Occurs when a class implementing McpPromptBuilderInterface throws
|
||||
* during construction or the build() method.
|
||||
*/
|
||||
public const BUILDER_EXCEPTION = 'builder_exception';
|
||||
|
||||
/**
|
||||
* Component was created without a permission callback.
|
||||
*
|
||||
* Domain components (McpTool, McpResource, McpPrompt) require a permission
|
||||
* callback. This failure occurs when check_permission() is called but
|
||||
* no callback was configured.
|
||||
*/
|
||||
public const NO_PERMISSION_STRATEGY = 'no_permission_strategy';
|
||||
|
||||
/**
|
||||
* Ability conversion returned a WP_Error.
|
||||
*
|
||||
* Occurs when McpTool::fromAbility(), McpResource::fromAbility(), or
|
||||
* McpPrompt::fromAbility() fails due to invalid ability configuration.
|
||||
*/
|
||||
public const ABILITY_CONVERSION_FAILED = 'ability_conversion_failed';
|
||||
|
||||
// =========================================================================
|
||||
// Permission Failures
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Generic permission denied without specific reason.
|
||||
*
|
||||
* Used when a permission callback returns false without providing
|
||||
* a WP_Error with more specific context.
|
||||
*/
|
||||
public const PERMISSION_DENIED = 'permission_denied';
|
||||
|
||||
/**
|
||||
* Permission callback returned a WP_Error.
|
||||
*
|
||||
* When the permission callback returns a WP_Error, the WP_Error code
|
||||
* is logged separately in the 'wp_error_code' tag while this failure
|
||||
* reason indicates the permission check explicitly failed.
|
||||
*/
|
||||
public const PERMISSION_CHECK_FAILED = 'permission_check_failed';
|
||||
|
||||
// =========================================================================
|
||||
// Execution Failures
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Component not found at execution time.
|
||||
*
|
||||
* Occurs when tools/call, resources/read, or prompts/get targets a
|
||||
* component that doesn't exist. Different from ABILITY_NOT_FOUND which
|
||||
* occurs at registration time.
|
||||
*/
|
||||
public const NOT_FOUND = 'not_found';
|
||||
|
||||
/**
|
||||
* Component execution returned a WP_Error.
|
||||
*
|
||||
* Occurs when the execute() or read() method returns a WP_Error.
|
||||
* The WP_Error code is logged separately in 'wp_error_code'.
|
||||
*/
|
||||
public const EXECUTION_FAILED = 'execution_failed';
|
||||
|
||||
/**
|
||||
* Component execution threw an exception.
|
||||
*
|
||||
* Occurs when execute(), read(), or handle() throws an exception.
|
||||
* The exception type is logged separately in 'exception_type'.
|
||||
*/
|
||||
public const EXECUTION_EXCEPTION = 'execution_exception';
|
||||
|
||||
// =========================================================================
|
||||
// Validation Failures
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Required parameter was missing from the request.
|
||||
*
|
||||
* JSON-RPC requests require certain parameters (e.g., 'name' for tools/call).
|
||||
*/
|
||||
public const MISSING_PARAMETER = 'missing_parameter';
|
||||
|
||||
/**
|
||||
* Parameter validation failed (wrong type, out of range, etc.).
|
||||
*
|
||||
* Occurs when input validation against schema or business rules fails.
|
||||
*/
|
||||
public const INVALID_PARAMETER = 'invalid_parameter';
|
||||
|
||||
// =========================================================================
|
||||
// Helper Methods
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Get all valid failure reason values.
|
||||
*
|
||||
* Useful for validation and documentation generation.
|
||||
*
|
||||
* @return array<string> List of all valid failure reason constants.
|
||||
*/
|
||||
public static function all(): array {
|
||||
return array(
|
||||
// Registration.
|
||||
self::ABILITY_NOT_FOUND,
|
||||
self::DUPLICATE_URI,
|
||||
self::BUILDER_EXCEPTION,
|
||||
self::NO_PERMISSION_STRATEGY,
|
||||
self::ABILITY_CONVERSION_FAILED,
|
||||
// Permission.
|
||||
self::PERMISSION_DENIED,
|
||||
self::PERMISSION_CHECK_FAILED,
|
||||
// Execution.
|
||||
self::NOT_FOUND,
|
||||
self::EXECUTION_FAILED,
|
||||
self::EXECUTION_EXCEPTION,
|
||||
// Validation.
|
||||
self::MISSING_PARAMETER,
|
||||
self::INVALID_PARAMETER,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a valid failure reason.
|
||||
*
|
||||
* @param string $value The value to check.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
*/
|
||||
public static function is_valid( string $value ): bool {
|
||||
return in_array( $value, self::all(), true );
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
<?php
|
||||
/**
|
||||
* Helper trait for MCP observability handlers providing shared utility methods.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\Observability;
|
||||
|
||||
/**
|
||||
* Trait McpObservabilityHelperTrait
|
||||
*
|
||||
* Provides shared utility methods for observability handlers including
|
||||
* tag management, metric formatting, and sanitization functionality.
|
||||
*/
|
||||
trait McpObservabilityHelperTrait {
|
||||
/**
|
||||
* Error categories keyed by throwable class name.
|
||||
*
|
||||
* @used-by ::categorize_error() method.
|
||||
*/
|
||||
private static array $error_categories = array(
|
||||
\ArgumentCountError::class => 'arguments',
|
||||
\Error::class => 'system',
|
||||
\InvalidArgumentException::class => 'validation',
|
||||
\LogicException::class => 'logic',
|
||||
\RuntimeException::class => 'execution',
|
||||
\TypeError::class => 'type',
|
||||
);
|
||||
|
||||
/**
|
||||
* Patterns that indicate sensitive data in keys or values.
|
||||
*
|
||||
* These patterns are designed to match both camelCase and snake_case variants:
|
||||
* - apiKey, api_key, API_KEY
|
||||
* - authToken, auth_token, AUTH_TOKEN
|
||||
* - secretKey, secret_key, SECRET_KEY
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
private static array $sensitive_patterns = array(
|
||||
'password',
|
||||
'passwd',
|
||||
'pwd',
|
||||
'secret',
|
||||
'token',
|
||||
'bearer',
|
||||
'credential',
|
||||
'private',
|
||||
'apikey',
|
||||
'api_key',
|
||||
'authtoken',
|
||||
'auth_token',
|
||||
'accesstoken',
|
||||
'access_token',
|
||||
'refreshtoken',
|
||||
'refresh_token',
|
||||
'clientsecret',
|
||||
'client_secret',
|
||||
'privatekey',
|
||||
'private_key',
|
||||
'secretkey',
|
||||
'secret_key',
|
||||
'authorization',
|
||||
'authenticate',
|
||||
'encryption',
|
||||
);
|
||||
|
||||
/**
|
||||
* Format metric name to follow consistent naming conventions.
|
||||
*
|
||||
* @param string $metric The raw metric name.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function format_metric_name( string $metric ): string {
|
||||
// Ensure metric starts with 'mcp.' prefix.
|
||||
if ( ! str_starts_with( $metric, 'mcp.' ) ) {
|
||||
$metric = 'mcp.' . $metric;
|
||||
}
|
||||
|
||||
// Convert to lowercase and replace spaces/special chars with dots.
|
||||
$metric = strtolower( $metric );
|
||||
$metric = (string) preg_replace( '/[^a-z0-9_\.]/', '.', $metric );
|
||||
$metric = (string) preg_replace( '/\.+/', '.', $metric ); // Remove duplicate dots.
|
||||
// Remove leading/trailing dots.
|
||||
|
||||
return trim( $metric, '.' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge default tags with provided tags.
|
||||
*
|
||||
* @param array $tags The user-provided tags.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function merge_tags( array $tags ): array {
|
||||
$default_tags = self::get_default_tags();
|
||||
$merged_tags = array_merge( $default_tags, $tags );
|
||||
|
||||
return self::sanitize_tags( $merged_tags );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default tags that should be included with all metrics.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function get_default_tags(): array {
|
||||
return array(
|
||||
'site_id' => function_exists( 'get_current_blog_id' ) ? get_current_blog_id() : 0,
|
||||
'user_id' => function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0,
|
||||
'timestamp' => time(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize tags to ensure they are safe for logging and don't contain sensitive data.
|
||||
*
|
||||
* @param array $tags The tags to sanitize.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function sanitize_tags( array $tags ): array {
|
||||
$sanitized = array();
|
||||
|
||||
foreach ( $tags as $key => $value ) {
|
||||
// Convert key to string and limit length to prevent log bloat.
|
||||
$key = substr( (string) $key, 0, 64 );
|
||||
|
||||
// Check if the key itself indicates sensitive data.
|
||||
if ( self::is_sensitive_key( $key ) ) {
|
||||
$sanitized[ $key ] = '[REDACTED]';
|
||||
continue;
|
||||
}
|
||||
|
||||
// Convert value to string, handling null specially.
|
||||
if ( null === $value ) {
|
||||
$value = '';
|
||||
} elseif ( is_scalar( $value ) ) {
|
||||
$value = (string) $value;
|
||||
} else {
|
||||
$value = wp_json_encode( $value );
|
||||
// wp_json_encode can return false on failure, ensure we have a string.
|
||||
if ( false === $value ) {
|
||||
$value = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Limit value length to prevent log bloat.
|
||||
if ( strlen( $value ) > 1024 ) {
|
||||
$value = substr( $value, 0, 1024 ) . '...[truncated]';
|
||||
}
|
||||
|
||||
// Remove potentially sensitive information patterns from values.
|
||||
$value = self::redact_sensitive_values( $value );
|
||||
|
||||
$sanitized[ $key ] = $value;
|
||||
}
|
||||
|
||||
return $sanitized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a key name indicates sensitive data.
|
||||
*
|
||||
* Matches patterns in camelCase, snake_case, and SCREAMING_CASE.
|
||||
*
|
||||
* @param string $key The key name to check.
|
||||
*
|
||||
* @return bool True if the key appears to contain sensitive data.
|
||||
*/
|
||||
public static function is_sensitive_key( string $key ): bool {
|
||||
// Normalize: lowercase and remove underscores/hyphens for pattern matching.
|
||||
$normalized = strtolower( str_replace( array( '_', '-' ), '', $key ) );
|
||||
|
||||
foreach ( self::$sensitive_patterns as $pattern ) {
|
||||
// Remove underscores from pattern for normalized comparison.
|
||||
$normalized_pattern = str_replace( '_', '', $pattern );
|
||||
|
||||
if ( str_contains( $normalized, $normalized_pattern ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redact sensitive values from a string.
|
||||
*
|
||||
* Uses a more comprehensive pattern that catches compound words.
|
||||
*
|
||||
* @param string $value The value to redact.
|
||||
*
|
||||
* @return string The value with sensitive patterns redacted.
|
||||
*/
|
||||
public static function redact_sensitive_values( string $value ): string {
|
||||
// Build a regex pattern that matches sensitive words as substrings.
|
||||
// This catches camelCase (apiKey), snake_case (api_key), and standalone words.
|
||||
$pattern = '/(?:' . implode( '|', array_map( 'preg_quote', self::$sensitive_patterns ) ) . ')/i';
|
||||
|
||||
return (string) preg_replace( $pattern, '[REDACTED]', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Categorize an exception into a general error category.
|
||||
*
|
||||
* @param \Throwable $exception The exception to categorize.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function categorize_error( \Throwable $exception ): string {
|
||||
return self::$error_categories[ get_class( $exception ) ] ?? 'unknown';
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
/**
|
||||
* NullMcpObservabilityHandler class for handling MCP observability without tracking.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Infrastructure\Observability;
|
||||
|
||||
/**
|
||||
* Class NullMcpObservabilityHandler
|
||||
*
|
||||
* This class handles MCP observability by doing nothing. It is used when no
|
||||
* observability tracking is desired, providing zero overhead.
|
||||
*
|
||||
* @package WP\MCP\ObservabilityHandlers
|
||||
*/
|
||||
class NullMcpObservabilityHandler implements Contracts\McpObservabilityHandlerInterface {
|
||||
|
||||
/**
|
||||
* Emit a countable event for tracking with optional timing data.
|
||||
*
|
||||
* This method does nothing and is used when no observability tracking is desired.
|
||||
*
|
||||
* @param string $event The event name to record.
|
||||
* @param array $tags Optional tags to attach to the event.
|
||||
* @param float|null $duration_ms Optional duration in milliseconds for timing measurements.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function record_event( string $event, array $tags = array(), ?float $duration_ms = null ): void {
|
||||
// Do nothing.
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
<?php
|
||||
/**
|
||||
* The main plugin file.
|
||||
*
|
||||
* If we evolve from a canonical plugin into WordPress core, this file would be left behind.
|
||||
*
|
||||
* @package WP\MCP
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP;
|
||||
|
||||
use WP\MCP\Core\McpAdapter;
|
||||
|
||||
/**
|
||||
* Class - Plugin
|
||||
*/
|
||||
final class Plugin {
|
||||
/**
|
||||
* The one true plugin.
|
||||
*
|
||||
* @var static
|
||||
*/
|
||||
private static self $instance;
|
||||
|
||||
/**
|
||||
* Gets the singleton instance of the plugin.
|
||||
*
|
||||
* @return self The plugin instance.
|
||||
*/
|
||||
public static function instance(): self {
|
||||
if ( ! isset( self::$instance ) ) {
|
||||
self::$instance = new self();
|
||||
self::$instance->setup();
|
||||
|
||||
/**
|
||||
* Fires after the main plugin class has been initialized.
|
||||
*
|
||||
* @since 0.1.0
|
||||
*
|
||||
* @param self $instance The main plugin class instance.
|
||||
*/
|
||||
do_action( 'wp_mcp_init', self::$instance );
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up the plugin.
|
||||
*/
|
||||
private function setup(): void {
|
||||
// Bail if dependencies are not met.
|
||||
if ( ! $this->has_dependencies() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
McpAdapter::instance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all required dependencies are available.
|
||||
*
|
||||
* Will log an admin notice if dependencies are missing.
|
||||
*
|
||||
* @return bool True if all dependencies are met, false otherwise.
|
||||
*/
|
||||
private function has_dependencies(): bool {
|
||||
// Check if Abilities API is available.
|
||||
if ( ! function_exists( 'wp_register_ability' ) ) {
|
||||
add_action(
|
||||
'admin_notices',
|
||||
static function () {
|
||||
wp_admin_notice(
|
||||
__( 'Abilities API not available (wp_register_ability function not found)', 'mcp-adapter' ),
|
||||
array(
|
||||
'type' => 'error',
|
||||
'dismiss' => false,
|
||||
),
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevents the class from being cloned.
|
||||
*/
|
||||
public function __clone() {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
sprintf(
|
||||
// translators: %s: Class name.
|
||||
esc_html__( 'The %s class should not be cloned.', 'mcp-adapter' ),
|
||||
esc_html( self::class ),
|
||||
),
|
||||
'0.1.0'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevents the class from being deserialized.
|
||||
*/
|
||||
public function __wakeup() {
|
||||
_doing_it_wrong(
|
||||
__FUNCTION__,
|
||||
sprintf(
|
||||
// translators: %s: Class name.
|
||||
esc_html__( 'De-serializing instances of %s is not allowed.', 'mcp-adapter' ),
|
||||
esc_html( self::class ),
|
||||
),
|
||||
'0.1.0'
|
||||
);
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
/**
|
||||
* Factory for creating the default WordPress MCP server.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Servers;
|
||||
|
||||
use WP\MCP\Core\McpAdapter;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\ErrorLogMcpErrorHandler;
|
||||
use WP\MCP\Infrastructure\Observability\NullMcpObservabilityHandler;
|
||||
use WP\MCP\Transport\HttpTransport;
|
||||
|
||||
/**
|
||||
* Factory for creating the default WordPress MCP server.
|
||||
*
|
||||
* This server automatically discovers and exposes abilities with mcp.public=true metadata:
|
||||
* - discover-abilities: Lists all publicly available WordPress abilities
|
||||
* - get-ability-info: Gets detailed information about specific abilities
|
||||
* - execute-ability: Executes WordPress abilities with provided parameters
|
||||
*/
|
||||
class DefaultServerFactory {
|
||||
|
||||
/**
|
||||
* Create default server for WordPress MCP Adapter with WordPress filters support.
|
||||
*
|
||||
* This method creates a server using WordPress-specific defaults and applies
|
||||
* WordPress filters for customization, making it perfect for use within
|
||||
* the McpAdapter.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function create(): void {
|
||||
|
||||
// Auto-discover resources and prompts from abilities
|
||||
$auto_discovered_resources = self::discover_abilities_by_type( 'resource' );
|
||||
$auto_discovered_prompts = self::discover_abilities_by_type( 'prompt' );
|
||||
|
||||
// WordPress-specific defaults
|
||||
$wordpress_defaults = array(
|
||||
'server_id' => 'mcp-adapter-default-server',
|
||||
'server_route_namespace' => 'mcp',
|
||||
'server_route' => 'mcp-adapter-default-server',
|
||||
'server_name' => 'MCP Adapter Default Server',
|
||||
'server_description' => 'Default MCP server for WordPress abilities discovery and execution',
|
||||
'server_version' => 'v1.0.0',
|
||||
'mcp_transports' => array( HttpTransport::class ),
|
||||
'error_handler' => ErrorLogMcpErrorHandler::class,
|
||||
'observability_handler' => NullMcpObservabilityHandler::class,
|
||||
'tools' => array(
|
||||
'mcp-adapter/discover-abilities',
|
||||
'mcp-adapter/get-ability-info',
|
||||
'mcp-adapter/execute-ability',
|
||||
),
|
||||
'resources' => $auto_discovered_resources,
|
||||
'prompts' => $auto_discovered_prompts,
|
||||
);
|
||||
|
||||
/**
|
||||
* Filters the default MCP server configuration.
|
||||
*
|
||||
* Allows customization of the default server's settings before creation.
|
||||
* The filtered array is merged with defaults, so you only need to specify
|
||||
* the values you want to override.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param array $config {
|
||||
* Default server configuration.
|
||||
*
|
||||
* @type string $server_id Server identifier. Default 'mcp-adapter-default-server'.
|
||||
* @type string $server_route_namespace REST API namespace. Default 'mcp-adapter/v1'.
|
||||
* @type string $server_route REST API route. Default 'mcp'.
|
||||
* @type string $server_name Human-readable name. Default 'WordPress MCP Server'.
|
||||
* @type string $server_description Server description.
|
||||
* @type string $server_version Server version. Default WORDPRESS_MCP_ADAPTER_VERSION.
|
||||
* @type string[] $mcp_transports Transport class names. Default [HttpTransport::class].
|
||||
* @type string $error_handler Error handler class. Default ErrorLogMcpErrorHandler::class.
|
||||
* @type string $observability_handler Observability handler class. Default NullMcpObservabilityHandler::class.
|
||||
* @type string[] $tools Tool ability names to expose.
|
||||
* @type string[] $resources Resource ability names to expose.
|
||||
* @type string[] $prompts Prompt ability names to expose.
|
||||
* }
|
||||
*/
|
||||
$config = apply_filters( 'mcp_adapter_default_server_config', $wordpress_defaults );
|
||||
|
||||
// Ensure config is an array and merge with defaults
|
||||
if ( ! is_array( $config ) ) {
|
||||
$config = $wordpress_defaults;
|
||||
}
|
||||
$config = wp_parse_args( $config, $wordpress_defaults );
|
||||
|
||||
// Use McpAdapter to create the server with full validation
|
||||
$adapter = McpAdapter::instance();
|
||||
$result = $adapter->create_server(
|
||||
$config['server_id'],
|
||||
$config['server_route_namespace'],
|
||||
$config['server_route'],
|
||||
$config['server_name'],
|
||||
$config['server_description'],
|
||||
$config['server_version'],
|
||||
$config['mcp_transports'],
|
||||
$config['error_handler'],
|
||||
$config['observability_handler'],
|
||||
$config['tools'],
|
||||
$config['resources'],
|
||||
$config['prompts']
|
||||
);
|
||||
|
||||
// Log error if server creation failed, but don't halt execution.
|
||||
// This allows other servers to be registered even if default server fails.
|
||||
if ( ! is_wp_error( $result ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
_doing_it_wrong(
|
||||
__METHOD__,
|
||||
sprintf(
|
||||
'MCP Adapter: Failed to create default server. Error: %s (Code: %s)',
|
||||
esc_html( $result->get_error_message() ),
|
||||
esc_html( (string) $result->get_error_code() )
|
||||
),
|
||||
'0.5.0'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover abilities by MCP type.
|
||||
*
|
||||
* Scans all registered abilities and returns those with the specified type
|
||||
* and public MCP exposure.
|
||||
*
|
||||
* @param string $type The MCP type to filter by ('tool', 'resource', or 'prompt').
|
||||
*
|
||||
* @return array Array of ability names matching the specified type.
|
||||
*/
|
||||
private static function discover_abilities_by_type( string $type ): array {
|
||||
$abilities = wp_get_abilities();
|
||||
$filtered = array();
|
||||
|
||||
foreach ( $abilities as $ability ) {
|
||||
$ability_name = $ability->get_name();
|
||||
$meta = $ability->get_meta();
|
||||
|
||||
// Skip if not publicly exposed
|
||||
if ( ! ( $meta['mcp']['public'] ?? false ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the type (defaults to 'tool' if not specified)
|
||||
$ability_type = $meta['mcp']['type'] ?? 'tool';
|
||||
|
||||
// Add to filtered list if type matches
|
||||
if ( $ability_type !== $type ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filtered[] = $ability_name;
|
||||
}
|
||||
|
||||
return $filtered;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
/**
|
||||
* Interface for MCP REST transport protocols.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Contracts;
|
||||
|
||||
/**
|
||||
* Interface for MCP REST transport protocols.
|
||||
*
|
||||
* This interface extends the base transport interface to provide
|
||||
* WordPress REST API specific functionality, with methods that
|
||||
* work specifically with WP_REST_Request objects.
|
||||
*/
|
||||
interface McpRestTransportInterface extends McpTransportInterface {
|
||||
|
||||
/**
|
||||
* Check if the user has permission to access the MCP API.
|
||||
*
|
||||
* @param \WP_REST_Request<array<string, mixed>> $request The WordPress REST request object.
|
||||
*
|
||||
* @return bool|\WP_Error True if allowed, WP_Error or false if not.
|
||||
*/
|
||||
public function check_permission( \WP_REST_Request $request );
|
||||
|
||||
/**
|
||||
* Handle incoming REST requests.
|
||||
*
|
||||
* @param \WP_REST_Request<array<string, mixed>> $request The WordPress REST request object.
|
||||
*
|
||||
* @return \WP_REST_Response REST API response object.
|
||||
*/
|
||||
public function handle_request( \WP_REST_Request $request ): \WP_REST_Response;
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
/**
|
||||
* Interface for MCP transport protocols.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Contracts;
|
||||
|
||||
use WP\MCP\Transport\Infrastructure\McpTransportContext;
|
||||
|
||||
/**
|
||||
* Base interface for MCP transport protocols.
|
||||
*
|
||||
* This interface defines the core contract for all MCP transport implementations,
|
||||
* providing common functionality for initialization and route registration.
|
||||
* Specific transport protocols should extend this interface with their own
|
||||
* request handling methods.
|
||||
*/
|
||||
interface McpTransportInterface {
|
||||
|
||||
/**
|
||||
* Initialize the transport with provided context.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\McpTransportContext $context Dependency injection container.
|
||||
*/
|
||||
public function __construct( McpTransportContext $context );
|
||||
|
||||
/**
|
||||
* Register transport-specific routes.
|
||||
*
|
||||
* Called during WordPress REST API initialization to register
|
||||
* endpoints for this transport.
|
||||
*/
|
||||
public function register_routes(): void;
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP HTTP Transport for WordPress (MCP 2025-11-25 baseline)
|
||||
*
|
||||
* This transport implements the MCP HTTP transport surface used by this plugin.
|
||||
* It can work both with and without the mcp-wordpress-remote proxy.
|
||||
*
|
||||
* Note: SSE (GET streaming) is not yet implemented; GET currently returns 405.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport;
|
||||
|
||||
use WP\MCP\Transport\Contracts\McpRestTransportInterface;
|
||||
use WP\MCP\Transport\Infrastructure\HttpRequestContext;
|
||||
use WP\MCP\Transport\Infrastructure\HttpRequestHandler;
|
||||
use WP\MCP\Transport\Infrastructure\McpTransportContext;
|
||||
use WP\MCP\Transport\Infrastructure\McpTransportHelperTrait;
|
||||
|
||||
/**
|
||||
* MCP HTTP Transport - Unified transport for both proxy and direct clients
|
||||
*
|
||||
* Implements the MCP 2025-11-25 HTTP transport shape used by this adapter (POST + sessions).
|
||||
*
|
||||
* Note: SSE (GET streaming) is not yet implemented; GET currently returns 405.
|
||||
*/
|
||||
class HttpTransport implements McpRestTransportInterface {
|
||||
use McpTransportHelperTrait;
|
||||
|
||||
/**
|
||||
* The HTTP request handler.
|
||||
*
|
||||
* @var \WP\MCP\Transport\Infrastructure\HttpRequestHandler
|
||||
*/
|
||||
protected HttpRequestHandler $request_handler;
|
||||
|
||||
/**
|
||||
* Initialize the class and register routes
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\McpTransportContext $transport_context The transport context.
|
||||
*/
|
||||
public function __construct( McpTransportContext $transport_context ) {
|
||||
$this->request_handler = new HttpRequestHandler( $transport_context );
|
||||
add_action( 'rest_api_init', array( $this, 'register_routes' ), 16 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register MCP HTTP routes
|
||||
*/
|
||||
public function register_routes(): void {
|
||||
// Get server info from request handler's transport context
|
||||
$server = $this->request_handler->get_transport_context()->mcp_server;
|
||||
|
||||
// Single endpoint for MCP communication (POST, GET reserved for SSE, DELETE for session termination).
|
||||
// Do not remove GET: it is part of the MCP HTTP transport shape and will be implemented (SSE) in a future iteration.
|
||||
register_rest_route(
|
||||
$server->get_server_route_namespace(),
|
||||
$server->get_server_route(),
|
||||
array(
|
||||
'methods' => array( 'POST', 'GET', 'DELETE' ),
|
||||
'callback' => array( $this, 'handle_request' ),
|
||||
'permission_callback' => array( $this, 'check_permission' ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user has permission to access the MCP API
|
||||
*
|
||||
* @param \WP_REST_Request<array<string, mixed>> $request The request object.
|
||||
*
|
||||
* @return bool True if the user has permission, false otherwise.
|
||||
*/
|
||||
public function check_permission( \WP_REST_Request $request ) {
|
||||
$context = new HttpRequestContext( $request );
|
||||
|
||||
// Check permission using callback or default
|
||||
$transport_context = $this->request_handler->get_transport_context();
|
||||
|
||||
if ( null !== $transport_context->transport_permission_callback ) {
|
||||
try {
|
||||
$result = call_user_func( $transport_context->transport_permission_callback, $context->request );
|
||||
|
||||
// Handle WP_Error returns
|
||||
if ( ! is_wp_error( $result ) ) {
|
||||
// Cast to bool to match return type while preserving truthy/falsy semantics.
|
||||
return (bool) $result;
|
||||
}
|
||||
|
||||
// Log the error and deny access (fail-closed)
|
||||
$this->request_handler->get_transport_context()->error_handler->log(
|
||||
'Permission callback returned WP_Error: ' . $result->get_error_message(),
|
||||
array( 'HttpTransport::check_permission' )
|
||||
);
|
||||
|
||||
return false;
|
||||
} catch ( \Throwable $e ) {
|
||||
// Log the error and deny access (fail-closed)
|
||||
$this->request_handler->get_transport_context()->error_handler->log( 'Error in transport permission callback: ' . $e->getMessage(), array( 'HttpTransport::check_permission' ) );
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the default user capability required for MCP transport access.
|
||||
*
|
||||
* This filter is only applied when no custom transport permission callback
|
||||
* is provided. The capability is checked using current_user_can().
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param string $capability The required capability. Default 'read'.
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*/
|
||||
$user_capability = apply_filters( 'mcp_adapter_default_transport_permission_user_capability', 'read', $context );
|
||||
|
||||
// Validate that the filtered capability is a non-empty string
|
||||
if ( ! is_string( $user_capability ) || empty( $user_capability ) ) {
|
||||
$user_capability = 'read';
|
||||
}
|
||||
|
||||
$user_has_capability = current_user_can( $user_capability ); // phpcs:ignore WordPress.WP.Capabilities.Undetermined -- Capability is filtered and defaults to 'read'
|
||||
|
||||
if ( ! $user_has_capability ) {
|
||||
$user_id = get_current_user_id();
|
||||
$this->request_handler->get_transport_context()->error_handler->log(
|
||||
sprintf( 'Permission denied for MCP API access. User ID %d does not have capability "%s"', $user_id, $user_capability ),
|
||||
array( 'HttpTransport::check_permission' )
|
||||
);
|
||||
}
|
||||
|
||||
return $user_has_capability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle HTTP requests according to MCP 2025-11-25 specification
|
||||
*
|
||||
* @param \WP_REST_Request<array<string, mixed>> $request The request object.
|
||||
*
|
||||
* @return \WP_REST_Response
|
||||
*/
|
||||
public function handle_request( \WP_REST_Request $request ): \WP_REST_Response {
|
||||
$context = new HttpRequestContext( $request );
|
||||
|
||||
return $this->request_handler->handle_request( $context );
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP HTTP Transport for WordPress - MCP 2025-11-25 Compliant
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
/**
|
||||
* A simple data carrier for HTTP request context.
|
||||
* Properties are public for easy access but should be treated as read-only after construction.
|
||||
*/
|
||||
class HttpRequestContext {
|
||||
|
||||
/**
|
||||
* The original WordPress REST request object.
|
||||
*
|
||||
* @var \WP_REST_Request<array<string, mixed>>
|
||||
*/
|
||||
public \WP_REST_Request $request;
|
||||
|
||||
/**
|
||||
* The HTTP method of the request.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public string $method;
|
||||
|
||||
|
||||
/**
|
||||
* The Mcp-Session-Id header from the request.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
public ?string $session_id;
|
||||
|
||||
/**
|
||||
* The JSON-decoded body of the request.
|
||||
*
|
||||
* @var array|null
|
||||
*/
|
||||
public ?array $body;
|
||||
|
||||
/**
|
||||
* The MCP-Protocol-Version header from the request.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
public ?string $protocol_version;
|
||||
|
||||
/**
|
||||
* The Accept header from the request.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
public ?string $accept_header;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP_REST_Request<array<string, mixed>> $request The original request object.
|
||||
*/
|
||||
public function __construct( \WP_REST_Request $request ) {
|
||||
$this->request = $request;
|
||||
$this->method = $request->get_method();
|
||||
$this->session_id = $request->get_header( 'Mcp-Session-Id' );
|
||||
$this->protocol_version = $request->get_header( 'Mcp-Protocol-Version' );
|
||||
$this->accept_header = $request->get_header( 'accept' );
|
||||
$this->body = 'POST' === $this->method ? $request->get_json_params() : null;
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
<?php
|
||||
/**
|
||||
* HTTP Request Handler for MCP Transport
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
use WP\MCP\Core\McpVersionNegotiator;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\McpErrorFactory;
|
||||
|
||||
/**
|
||||
* Handles HTTP request routing and processing for MCP transports.
|
||||
*
|
||||
* Centralizes request routing logic to eliminate duplication and provide
|
||||
* consistent request handling across transport implementations.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class HttpRequestHandler {
|
||||
|
||||
/**
|
||||
* The transport context.
|
||||
*
|
||||
* @var \WP\MCP\Transport\Infrastructure\McpTransportContext
|
||||
*/
|
||||
public McpTransportContext $transport_context;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\McpTransportContext $transport_context The transport context.
|
||||
*/
|
||||
public function __construct( McpTransportContext $transport_context ) {
|
||||
$this->transport_context = $transport_context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the transport context.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @return \WP\MCP\Transport\Infrastructure\McpTransportContext
|
||||
*/
|
||||
public function get_transport_context(): McpTransportContext {
|
||||
return $this->transport_context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route HTTP request to appropriate handler.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return \WP_REST_Response HTTP response.
|
||||
*/
|
||||
public function handle_request( HttpRequestContext $context ): \WP_REST_Response {
|
||||
// Handle POST requests (sending MCP messages to server)
|
||||
if ( 'POST' === $context->method ) {
|
||||
return $this->handle_mcp_request( $context );
|
||||
}
|
||||
|
||||
// Handle GET requests (reserved for SSE streaming; currently not implemented).
|
||||
if ( 'GET' === $context->method ) {
|
||||
return $this->handle_sse_request();
|
||||
}
|
||||
|
||||
// Handle DELETE requests (session termination)
|
||||
if ( 'DELETE' === $context->method ) {
|
||||
return $this->handle_session_termination( $context );
|
||||
}
|
||||
|
||||
// Method not allowed
|
||||
return new \WP_REST_Response(
|
||||
McpErrorFactory::invalid_request( null, 'Method not allowed' )->toArray(),
|
||||
405
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Handle MCP POST requests.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return \WP_REST_Response MCP response.
|
||||
*/
|
||||
private function handle_mcp_request( HttpRequestContext $context ): \WP_REST_Response {
|
||||
try {
|
||||
// Validate request body
|
||||
if ( null === $context->body ) {
|
||||
return new \WP_REST_Response(
|
||||
McpErrorFactory::parse_error( null, 'Invalid JSON in request body' )->toArray(),
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
return $this->process_mcp_messages( $context );
|
||||
} catch ( \Throwable $exception ) {
|
||||
$this->transport_context->mcp_server->get_error_handler()->log(
|
||||
'Unexpected error in handle_mcp_request',
|
||||
array(
|
||||
'transport' => static::class,
|
||||
'server_id' => $this->transport_context->mcp_server->get_server_id(),
|
||||
'error' => $exception->getMessage(),
|
||||
)
|
||||
);
|
||||
|
||||
return new \WP_REST_Response(
|
||||
McpErrorFactory::internal_error( null, 'Handler error occurred' )->toArray(),
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process MCP messages using JsonRpcResponseBuilder.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return \WP_REST_Response MCP response.
|
||||
*/
|
||||
private function process_mcp_messages( HttpRequestContext $context ): \WP_REST_Response {
|
||||
$is_batch_request = JsonRpcResponseBuilder::is_batch_request( $context->body );
|
||||
$messages = JsonRpcResponseBuilder::normalize_messages( $context->body );
|
||||
|
||||
$response_body = JsonRpcResponseBuilder::process_messages(
|
||||
$messages,
|
||||
$is_batch_request,
|
||||
function ( array $message ) use ( $context ) {
|
||||
return $this->process_single_message( $message, $context );
|
||||
}
|
||||
);
|
||||
|
||||
// Per MCP spec 2025-06-18: Notifications return HTTP 202 Accepted with no body.
|
||||
// A null response_body indicates only notifications were processed (no requests with IDs).
|
||||
if ( null === $response_body ) {
|
||||
return new \WP_REST_Response( null, 202 );
|
||||
}
|
||||
|
||||
// Determine HTTP status code based on error type
|
||||
if ( ! $is_batch_request && isset( $response_body['error'] ) ) {
|
||||
$http_status = McpErrorFactory::get_http_status_for_error( $response_body );
|
||||
|
||||
return new \WP_REST_Response( $response_body, $http_status );
|
||||
}
|
||||
|
||||
return new \WP_REST_Response( $response_body, 200 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a single MCP message.
|
||||
*
|
||||
* @param array $message The MCP JSON-RPC message.
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return array|null JSON-RPC response or null for notifications.
|
||||
*/
|
||||
private function process_single_message( array $message, HttpRequestContext $context ): ?array {
|
||||
// Validate JSON-RPC message format
|
||||
$validation = McpErrorFactory::validate_jsonrpc_message( $message );
|
||||
if ( true !== $validation ) {
|
||||
return $validation->toArray();
|
||||
}
|
||||
|
||||
// Handle notifications (no response required)
|
||||
if ( isset( $message['method'] ) && ! isset( $message['id'] ) ) {
|
||||
return null; // Notifications don't get a response
|
||||
}
|
||||
|
||||
// Process requests with IDs
|
||||
if ( isset( $message['method'] ) && isset( $message['id'] ) ) {
|
||||
return $this->process_jsonrpc_request( $message, $context );
|
||||
}
|
||||
|
||||
// JSON-RPC responses from client (has result/error, no method) also return null.
|
||||
// Per MCP spec: client responses get HTTP 202 Accepted with no body, same as notifications.
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a JSON-RPC request message.
|
||||
*
|
||||
* @param array $message The JSON-RPC message.
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return array JSON-RPC response.
|
||||
*/
|
||||
private function process_jsonrpc_request( array $message, HttpRequestContext $context ): array {
|
||||
$request_id = $message['id']; // Preserve original scalar ID (string, number, or null)
|
||||
$method = $message['method'];
|
||||
$params = $message['params'] ?? array();
|
||||
|
||||
// Validate session for all requests except initialize (router will handle initialize session creation)
|
||||
if ( 'initialize' !== $method ) {
|
||||
$session_validation = HttpSessionValidator::validate_session( $context );
|
||||
if ( true !== $session_validation ) {
|
||||
return JsonRpcResponseBuilder::create_error_response( $request_id, $session_validation['error'] ?? $session_validation );
|
||||
}
|
||||
|
||||
// Validate MCP-Protocol-Version header for non-initialize requests.
|
||||
$protocol_version_error = $this->validate_protocol_version_header( $context );
|
||||
if ( null !== $protocol_version_error ) {
|
||||
return JsonRpcResponseBuilder::create_error_response( $request_id, $protocol_version_error );
|
||||
}
|
||||
}
|
||||
|
||||
// Route the request through the transport context
|
||||
$result = $this->transport_context->request_router->route_request(
|
||||
$method,
|
||||
$params,
|
||||
$request_id,
|
||||
$this->get_transport_name(),
|
||||
$context
|
||||
);
|
||||
|
||||
// Handle session header if provided by router
|
||||
if ( isset( $result['_session_id'] ) ) {
|
||||
$this->add_session_header_to_response( $result['_session_id'] );
|
||||
unset( $result['_session_id'] ); // Remove from actual response data
|
||||
}
|
||||
|
||||
// Format response based on result
|
||||
if ( isset( $result['error'] ) ) {
|
||||
return JsonRpcResponseBuilder::create_error_response( $request_id, $result['error'] );
|
||||
}
|
||||
|
||||
return JsonRpcResponseBuilder::create_success_response( $request_id, $result );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get transport name for observability.
|
||||
*
|
||||
* @return string Transport name.
|
||||
*/
|
||||
private function get_transport_name(): string {
|
||||
return 'HTTP';
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the MCP-Protocol-Version header on non-initialize requests.
|
||||
*
|
||||
* A missing header is accepted (returns null). A header containing a supported
|
||||
* version is also accepted. An unsupported version returns a JSON-RPC
|
||||
* invalid-request error payload.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return array|null Null when the header is absent or valid, error payload otherwise.
|
||||
*/
|
||||
private function validate_protocol_version_header( HttpRequestContext $context ): ?array {
|
||||
if ( null === $context->protocol_version ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( McpVersionNegotiator::is_supported( $context->protocol_version ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return McpErrorFactory::create_error(
|
||||
McpErrorFactory::INVALID_REQUEST,
|
||||
sprintf(
|
||||
'Bad Request: Unsupported protocol version: %s (supported versions: %s)',
|
||||
$context->protocol_version,
|
||||
implode( ', ', McpVersionNegotiator::SUPPORTED_PROTOCOL_VERSIONS )
|
||||
)
|
||||
)->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add session header to the REST response.
|
||||
*
|
||||
* Uses a static flag to prevent multiple filters from being added
|
||||
* if this method is called multiple times during a single request
|
||||
* (e.g., during batch JSON-RPC processing).
|
||||
*
|
||||
* @param string $session_id The session ID to add to the response header.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function add_session_header_to_response( string $session_id ): void {
|
||||
static $current_session_id = null;
|
||||
|
||||
// Only add filter once per request, or if session ID changes
|
||||
if ( null !== $current_session_id && $current_session_id === $session_id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
add_filter(
|
||||
'rest_post_dispatch',
|
||||
static function ( $response ) use ( $session_id ) {
|
||||
if ( $response instanceof \WP_REST_Response ) {
|
||||
$response->header( 'Mcp-Session-Id', $session_id );
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
);
|
||||
|
||||
$current_session_id = $session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle GET requests (SSE streaming).
|
||||
*
|
||||
* @return \WP_REST_Response SSE response.
|
||||
*/
|
||||
private function handle_sse_request(): \WP_REST_Response {
|
||||
// SSE streaming not yet implemented - return HTTP 405 with no body
|
||||
return new \WP_REST_Response( null, 405 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle DELETE requests (session termination).
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return \WP_REST_Response Termination response.
|
||||
*/
|
||||
private function handle_session_termination( HttpRequestContext $context ): \WP_REST_Response {
|
||||
$result = HttpSessionValidator::terminate_session( $context );
|
||||
|
||||
if ( true !== $result ) {
|
||||
$http_status = McpErrorFactory::get_http_status_for_error( $result );
|
||||
|
||||
return new \WP_REST_Response( $result, $http_status );
|
||||
}
|
||||
|
||||
return new \WP_REST_Response( null, 200 );
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
/**
|
||||
* HTTP Session Validator for MCP Transport
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
use WP\MCP\Infrastructure\ErrorHandling\McpErrorFactory;
|
||||
|
||||
/**
|
||||
* Handles HTTP-specific session validation logic for MCP transports.
|
||||
*
|
||||
* Centralizes HTTP request context validation and session management coordination
|
||||
* to eliminate duplication across transport implementations.
|
||||
*/
|
||||
class HttpSessionValidator {
|
||||
|
||||
/**
|
||||
* Validate session for MCP HTTP requests.
|
||||
*
|
||||
* Performs complete session validation including HTTP headers, user authentication,
|
||||
* and session validity in a single method to reduce method call overhead.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return array|true Returns true if valid, error array if invalid.
|
||||
*/
|
||||
public static function validate_session( HttpRequestContext $context ) {
|
||||
// Check session header presence
|
||||
$session_id = $context->session_id;
|
||||
if ( ! $session_id ) {
|
||||
return McpErrorFactory::invalid_request( null, 'Missing Mcp-Session-Id header' )->toArray();
|
||||
}
|
||||
|
||||
// Check user authentication
|
||||
$user_id = get_current_user_id();
|
||||
if ( ! $user_id ) {
|
||||
return McpErrorFactory::unauthorized( null, 'User not authenticated' )->toArray();
|
||||
}
|
||||
|
||||
// Validate session using SessionManager
|
||||
if ( ! SessionManager::validate_session( $user_id, $session_id ) ) {
|
||||
return McpErrorFactory::session_not_found( null, 'Invalid or expired session' )->toArray();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate session header presence in HTTP request.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return string|array Session ID on success, error array on failure.
|
||||
*/
|
||||
public static function validate_session_header( HttpRequestContext $context ) {
|
||||
$session_id = $context->session_id;
|
||||
|
||||
if ( ! $session_id ) {
|
||||
return McpErrorFactory::invalid_request( null, 'Missing Mcp-Session-Id header' )->toArray();
|
||||
}
|
||||
|
||||
return $session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new session for the current user with HTTP context awareness.
|
||||
*
|
||||
* Validates user authentication and creates session, providing better error
|
||||
* context than direct SessionManager calls.
|
||||
*
|
||||
* @param array $params The client parameters from initialize request.
|
||||
*
|
||||
* @return string|array Session ID on success, error array on failure.
|
||||
*/
|
||||
public static function create_session( array $params = array() ) {
|
||||
$user_id = get_current_user_id();
|
||||
if ( ! $user_id ) {
|
||||
return McpErrorFactory::unauthorized( null, 'User authentication required for session creation' )->toArray();
|
||||
}
|
||||
|
||||
$session_id = SessionManager::create_session( $user_id, $params );
|
||||
|
||||
if ( ! $session_id ) {
|
||||
return McpErrorFactory::internal_error( null, 'Failed to create session' )->toArray();
|
||||
}
|
||||
|
||||
return $session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminate a session with full HTTP context validation.
|
||||
*
|
||||
* Performs complete validation workflow for session termination including
|
||||
* header validation, user authentication, and session cleanup.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext $context The HTTP request context.
|
||||
*
|
||||
* @return array|true Returns true on success, error array on failure.
|
||||
*/
|
||||
public static function terminate_session( HttpRequestContext $context ) {
|
||||
// Validate session header
|
||||
$session_id = $context->session_id;
|
||||
if ( ! $session_id ) {
|
||||
return McpErrorFactory::invalid_request( null, 'Missing Mcp-Session-Id header' )->toArray();
|
||||
}
|
||||
|
||||
// Validate user authentication
|
||||
$user_id = get_current_user_id();
|
||||
if ( ! $user_id ) {
|
||||
return McpErrorFactory::unauthorized( null, 'User not authenticated' )->toArray();
|
||||
}
|
||||
|
||||
// Terminate the session
|
||||
SessionManager::delete_session( $user_id, $session_id );
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
/**
|
||||
* JSON-RPC Response Builder for MCP Transport
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
use WP\McpSchema\Common\McpConstants;
|
||||
|
||||
/**
|
||||
* Builds standardized JSON-RPC 2.0 responses for MCP transport.
|
||||
*
|
||||
* Centralizes response creation logic to eliminate duplication and ensure
|
||||
* consistent response formatting across all MCP transport implementations.
|
||||
*/
|
||||
class JsonRpcResponseBuilder {
|
||||
|
||||
/**
|
||||
* Create a JSON-RPC 2.0 success response.
|
||||
*
|
||||
* @param mixed $request_id The request ID from the original JSON-RPC request (string, number, or null).
|
||||
* @param mixed $result The result data to return.
|
||||
*
|
||||
* @return array The formatted JSON-RPC response.
|
||||
*/
|
||||
public static function create_success_response( $request_id, $result ): array {
|
||||
return array(
|
||||
'jsonrpc' => McpConstants::JSONRPC_VERSION,
|
||||
'id' => $request_id,
|
||||
// Make sure the result is an object (not an array)
|
||||
'result' => (object) $result,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a JSON-RPC 2.0 error response.
|
||||
*
|
||||
* @param mixed $request_id The request ID from the original JSON-RPC request (string, number, or null).
|
||||
* @param array $error The error array with 'code', 'message', and optional 'data'.
|
||||
*
|
||||
* @return array The formatted JSON-RPC error response.
|
||||
*/
|
||||
public static function create_error_response( $request_id, array $error ): array {
|
||||
return array(
|
||||
'jsonrpc' => McpConstants::JSONRPC_VERSION,
|
||||
'id' => $request_id,
|
||||
'error' => $error,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process multiple MCP messages and format the response correctly.
|
||||
*
|
||||
* Handles both batch requests (array of messages) and single requests,
|
||||
* returning the appropriate response format per JSON-RPC 2.0 specification.
|
||||
*
|
||||
* @param array $messages Array of JSON-RPC messages to process.
|
||||
* @param bool $is_batch_request Whether the original request was a batch.
|
||||
* @param callable $processor Callback function to process each individual message.
|
||||
* Should accept (array $message) and return array $response.
|
||||
*
|
||||
* @return array|null The formatted response (array for batch, single response for non-batch).
|
||||
*/
|
||||
public static function process_messages( array $messages, bool $is_batch_request, callable $processor ): ?array {
|
||||
$results = array();
|
||||
|
||||
foreach ( $messages as $message ) {
|
||||
$response = call_user_func( $processor, $message );
|
||||
if ( null === $response ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$results[] = $response;
|
||||
}
|
||||
|
||||
// Return response format based on original request format (JSON-RPC 2.0 spec)
|
||||
// If the request was a batch, response MUST be an array, even if only one result
|
||||
return $is_batch_request ? $results : ( $results[0] ?? null );
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize request body to an array of messages.
|
||||
*
|
||||
* Converts single messages to an array for uniform processing.
|
||||
*
|
||||
* @param mixed $body The decoded request body.
|
||||
*
|
||||
* @return array Array of messages for processing.
|
||||
*/
|
||||
public static function normalize_messages( $body ): array {
|
||||
return self::is_batch_request( $body ) ? $body : array( $body );
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a request body represents a batch request.
|
||||
*
|
||||
* Per JSON-RPC 2.0 specification, a batch request is an array with at least one element.
|
||||
*
|
||||
* @param mixed $body The decoded request body.
|
||||
*
|
||||
* @return bool True if this is a batch request.
|
||||
*/
|
||||
public static function is_batch_request( $body ): bool {
|
||||
return is_array( $body ) && isset( $body[0] );
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
/**
|
||||
* Transport context object for dependency injection.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
use WP\MCP\Core\McpServer;
|
||||
use WP\MCP\Handlers\Initialize\InitializeHandler;
|
||||
use WP\MCP\Handlers\Prompts\PromptsHandler;
|
||||
use WP\MCP\Handlers\Resources\ResourcesHandler;
|
||||
use WP\MCP\Handlers\System\SystemHandler;
|
||||
use WP\MCP\Handlers\Tools\ToolsHandler;
|
||||
use WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface;
|
||||
use WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface;
|
||||
|
||||
/**
|
||||
* Transport context object for dependency injection.
|
||||
*
|
||||
* Contains all dependencies needed by transport implementations,
|
||||
* promoting loose coupling and easier testing.
|
||||
*
|
||||
* Note: The request_router parameter is optional. If not provided,
|
||||
* a RequestRouter instance will be automatically created with this
|
||||
* context as its dependency.
|
||||
*/
|
||||
class McpTransportContext {
|
||||
|
||||
/**
|
||||
* Required property keys for the constructor array.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
// phpcs:ignore SlevomatCodingStandard.Classes.DisallowMultiConstantDefinition -- False positive: sniff mistakes array() commas for multi-const commas (only handles short syntax).
|
||||
private const REQUIRED_KEYS = array(
|
||||
'mcp_server',
|
||||
'initialize_handler',
|
||||
'tools_handler',
|
||||
'resources_handler',
|
||||
'prompts_handler',
|
||||
'system_handler',
|
||||
'observability_handler',
|
||||
);
|
||||
|
||||
/**
|
||||
* Optional property keys for the constructor array.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
// phpcs:ignore SlevomatCodingStandard.Classes.DisallowMultiConstantDefinition -- False positive: sniff mistakes array() commas for multi-const commas (only handles short syntax).
|
||||
private const OPTIONAL_KEYS = array(
|
||||
'request_router',
|
||||
'transport_permission_callback',
|
||||
'error_handler',
|
||||
);
|
||||
|
||||
/**
|
||||
* The MCP server instance.
|
||||
*
|
||||
* @var \WP\MCP\Core\McpServer
|
||||
*/
|
||||
public McpServer $mcp_server;
|
||||
|
||||
/**
|
||||
* The initialize handler.
|
||||
*
|
||||
* @var \WP\MCP\Handlers\Initialize\InitializeHandler
|
||||
*/
|
||||
public InitializeHandler $initialize_handler;
|
||||
|
||||
/**
|
||||
* The tools handler.
|
||||
*
|
||||
* @var \WP\MCP\Handlers\Tools\ToolsHandler
|
||||
*/
|
||||
public ToolsHandler $tools_handler;
|
||||
|
||||
/**
|
||||
* The resources handler.
|
||||
*
|
||||
* @var \WP\MCP\Handlers\Resources\ResourcesHandler
|
||||
*/
|
||||
public ResourcesHandler $resources_handler;
|
||||
|
||||
/**
|
||||
* The prompts handler.
|
||||
*
|
||||
* @var \WP\MCP\Handlers\Prompts\PromptsHandler
|
||||
*/
|
||||
public PromptsHandler $prompts_handler;
|
||||
|
||||
/**
|
||||
* The system handler.
|
||||
*
|
||||
* @var \WP\MCP\Handlers\System\SystemHandler
|
||||
*/
|
||||
public SystemHandler $system_handler;
|
||||
|
||||
/**
|
||||
* The observability handler instance.
|
||||
*
|
||||
* @var \WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface
|
||||
*/
|
||||
public McpObservabilityHandlerInterface $observability_handler;
|
||||
|
||||
/**
|
||||
* The error handler instance.
|
||||
*
|
||||
* @var \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface
|
||||
*/
|
||||
public McpErrorHandlerInterface $error_handler;
|
||||
|
||||
/**
|
||||
* The request router service.
|
||||
*/
|
||||
public RequestRouter $request_router;
|
||||
|
||||
/**
|
||||
* Optional custom permission callback for transport-level authentication.
|
||||
*
|
||||
* @var callable|callable-string|null
|
||||
*/
|
||||
public $transport_permission_callback;
|
||||
|
||||
/**
|
||||
* Initialize the transport context.
|
||||
*
|
||||
* @param array{
|
||||
* mcp_server: \WP\MCP\Core\McpServer,
|
||||
* initialize_handler: \WP\MCP\Handlers\Initialize\InitializeHandler,
|
||||
* tools_handler: \WP\MCP\Handlers\Tools\ToolsHandler,
|
||||
* resources_handler: \WP\MCP\Handlers\Resources\ResourcesHandler,
|
||||
* prompts_handler: \WP\MCP\Handlers\Prompts\PromptsHandler,
|
||||
* system_handler: \WP\MCP\Handlers\System\SystemHandler,
|
||||
* observability_handler: \WP\MCP\Infrastructure\Observability\Contracts\McpObservabilityHandlerInterface,
|
||||
* request_router?: \WP\MCP\Transport\Infrastructure\RequestRouter,
|
||||
* transport_permission_callback?: callable|null,
|
||||
* error_handler?: \WP\MCP\Infrastructure\ErrorHandling\Contracts\McpErrorHandlerInterface
|
||||
* } $properties Properties to set on the context.
|
||||
* Note: request_router is optional and will be auto-created if not provided.
|
||||
*
|
||||
* @throws \InvalidArgumentException If required keys are missing or unknown keys are present.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
public function __construct( array $properties ) {
|
||||
$this->validate_properties( $properties );
|
||||
|
||||
// Assign required properties.
|
||||
$this->mcp_server = $properties['mcp_server'];
|
||||
$this->initialize_handler = $properties['initialize_handler'];
|
||||
$this->tools_handler = $properties['tools_handler'];
|
||||
$this->resources_handler = $properties['resources_handler'];
|
||||
$this->prompts_handler = $properties['prompts_handler'];
|
||||
$this->system_handler = $properties['system_handler'];
|
||||
$this->observability_handler = $properties['observability_handler'];
|
||||
|
||||
// Assign optional properties (error_handler defaults to the server's handler).
|
||||
$this->error_handler = $properties['error_handler'] ?? $properties['mcp_server']->get_error_handler();
|
||||
|
||||
$this->transport_permission_callback = $properties['transport_permission_callback'] ?? null;
|
||||
|
||||
// Create request_router if not provided.
|
||||
$this->request_router = $properties['request_router'] ?? new RequestRouter( $this );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that the properties array contains all required keys and no unknown keys.
|
||||
*
|
||||
* @param array<string, mixed> $properties Properties to validate.
|
||||
*
|
||||
* @throws \InvalidArgumentException If required keys are missing or unknown keys are present.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*/
|
||||
private function validate_properties( array $properties ): void {
|
||||
$provided_keys = array_keys( $properties );
|
||||
$allowed_keys = array_merge( self::REQUIRED_KEYS, self::OPTIONAL_KEYS );
|
||||
|
||||
// Check for unknown keys.
|
||||
$unknown_keys = array_diff( $provided_keys, $allowed_keys );
|
||||
if ( ! empty( $unknown_keys ) ) {
|
||||
throw new \InvalidArgumentException(
|
||||
sprintf(
|
||||
'Unknown properties provided to McpTransportContext: %1$s. Allowed properties: %2$s.',
|
||||
esc_html( implode( ', ', $unknown_keys ) ),
|
||||
esc_html( implode( ', ', $allowed_keys ) )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Check for missing required keys.
|
||||
$missing_keys = array_diff( self::REQUIRED_KEYS, $provided_keys );
|
||||
if ( ! empty( $missing_keys ) ) {
|
||||
throw new \InvalidArgumentException(
|
||||
sprintf(
|
||||
'Missing required properties for McpTransportContext: %s.',
|
||||
esc_html( implode( ', ', $missing_keys ) )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
/**
|
||||
* Helper trait for MCP transport implementations providing shared utility methods.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
/**
|
||||
* Trait McpTransportHelperTrait
|
||||
*
|
||||
* Provides shared utility methods for transport implementations including
|
||||
* naming conventions, error creation, and common operations.
|
||||
*/
|
||||
trait McpTransportHelperTrait {
|
||||
|
||||
/**
|
||||
* Get a normalized transport name for tagging purposes.
|
||||
*
|
||||
* Extracts the transport name from the class name for use in observability metrics.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function get_transport_name(): string {
|
||||
// Get the class name without namespace.
|
||||
$class_name = substr( (string) strrchr( static::class, '\\' ), 1 );
|
||||
|
||||
// Remove common suffixes and convert to lowercase.
|
||||
$transport_name = strtolower(
|
||||
str_replace( array( 'McpTransport', 'Transport' ), '', $class_name )
|
||||
);
|
||||
|
||||
// Fallback to 'unknown' if extraction fails.
|
||||
return ! empty( $transport_name ) ? $transport_name : 'unknown';
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
<?php
|
||||
/**
|
||||
* Service for routing MCP requests to appropriate handlers.
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
use WP\MCP\Infrastructure\ErrorHandling\McpErrorFactory;
|
||||
use WP\MCP\Infrastructure\Observability\McpObservabilityHelperTrait;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Content\DTO\TextContent;
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse;
|
||||
use WP\McpSchema\Server\Tools\DTO\CallToolResult;
|
||||
|
||||
/**
|
||||
* Service for routing MCP requests to appropriate handlers.
|
||||
*
|
||||
* Extracted from AbstractMcpTransport to be reusable across
|
||||
* all transport implementations via dependency injection.
|
||||
*/
|
||||
class RequestRouter {
|
||||
|
||||
/**
|
||||
* The transport context.
|
||||
*
|
||||
* @var \WP\MCP\Transport\Infrastructure\McpTransportContext
|
||||
*/
|
||||
private McpTransportContext $context;
|
||||
|
||||
/**
|
||||
* Initialize the request router.
|
||||
*
|
||||
* @param \WP\MCP\Transport\Infrastructure\McpTransportContext $context The transport context.
|
||||
*/
|
||||
public function __construct(
|
||||
McpTransportContext $context
|
||||
) {
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route a request to the appropriate handler.
|
||||
*
|
||||
* @param string $method The MCP method name.
|
||||
* @param array $params The request parameters.
|
||||
* @param mixed $request_id The request ID (for JSON-RPC) - string, number, or null.
|
||||
* @param string $transport_name Transport name for observability.
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext|null $http_context HTTP context for session management.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function route_request( string $method, array $params, $request_id = 0, string $transport_name = 'unknown', ?HttpRequestContext $http_context = null ): array {
|
||||
// Track request start time.
|
||||
$start_time = microtime( true );
|
||||
|
||||
$new_session_id = null;
|
||||
$component_tags = $this->resolve_component_observability_context( $method, $params );
|
||||
|
||||
// Common tags for all metrics.
|
||||
$common_tags = array(
|
||||
'method' => $method,
|
||||
'transport' => $transport_name,
|
||||
'server_id' => $this->context->mcp_server->get_server_id(),
|
||||
'params' => $this->sanitize_params_for_logging( $params ),
|
||||
'request_id' => $request_id,
|
||||
'session_id' => $http_context ? $http_context->session_id : null,
|
||||
);
|
||||
|
||||
$handlers = array(
|
||||
'initialize' => function () use ( $params, $request_id, $http_context, &$new_session_id ) {
|
||||
return $this->handle_initialize_with_session( $params, $request_id, $http_context, $new_session_id );
|
||||
},
|
||||
'ping' => fn() => $this->context->system_handler->ping(),
|
||||
'tools/list' => fn() => $this->context->tools_handler->list_tools(),
|
||||
'tools/list/all' => fn() => $this->context->tools_handler->list_all_tools(),
|
||||
'tools/call' => fn() => $this->context->tools_handler->call_tool( $params, $request_id ),
|
||||
'resources/list' => fn() => $this->context->resources_handler->list_resources(),
|
||||
'resources/read' => fn() => $this->context->resources_handler->read_resource( $params, $request_id ),
|
||||
'prompts/list' => fn() => $this->context->prompts_handler->list_prompts(),
|
||||
'prompts/get' => fn() => $this->context->prompts_handler->get_prompt( $params, $request_id ),
|
||||
);
|
||||
|
||||
try {
|
||||
$handler_result = isset( $handlers[ $method ] ) ? $handlers[ $method ]() : $this->create_method_not_found_error( $method, $request_id );
|
||||
|
||||
// Calculate request duration.
|
||||
$duration = ( microtime( true ) - $start_time ) * 1000; // Convert to milliseconds.
|
||||
|
||||
// Handle DTO results from migrated handlers.
|
||||
// DTOs are converted to arrays at the serialization boundary (here).
|
||||
if ( $handler_result instanceof JSONRPCErrorResponse ) {
|
||||
// Normalize to transport-level shape: only the JSON-RPC error object.
|
||||
// The JSON-RPC envelope is created by the transport boundary.
|
||||
$result = array( 'error' => $handler_result->getError()->toArray() );
|
||||
$tags = array_merge( $common_tags, $component_tags, array( 'status' => 'error' ) );
|
||||
$tags['error_code'] = $handler_result->getError()->getCode();
|
||||
$tags['failure_reason'] = $handler_result->getError()->getMessage();
|
||||
$this->context->observability_handler->record_event( 'mcp.request', $tags, $duration );
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
if ( $handler_result instanceof AbstractDataTransferObject ) {
|
||||
// Success DTO (ListToolsResult, CallToolResult, etc.) - convert to array.
|
||||
// Note: If a future schema version ever returns nested DTO objects inside `toArray()`,
|
||||
// we may need to add a deep normalizer at this boundary (before JSON serialization)
|
||||
// to prevent placeholder `{}` objects in client output.
|
||||
$raw_result = $handler_result->toArray();
|
||||
$result = $raw_result;
|
||||
|
||||
if ( null !== $new_session_id ) {
|
||||
$component_tags['new_session_id'] = $new_session_id;
|
||||
$result['_session_id'] = $new_session_id;
|
||||
}
|
||||
|
||||
$status = 'success';
|
||||
if ( $handler_result instanceof CallToolResult && true === $handler_result->getIsError() ) {
|
||||
$status = 'error';
|
||||
|
||||
if ( ! isset( $component_tags['failure_reason'] ) ) {
|
||||
$content = $handler_result->getContent();
|
||||
if ( isset( $content[0] ) && $content[0] instanceof TextContent ) {
|
||||
$component_tags['failure_reason'] = $content[0]->getText();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$tags = array_merge( $common_tags, $component_tags, array( 'status' => $status ) );
|
||||
$this->context->observability_handler->record_event( 'mcp.request', $tags, $duration );
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
// Handlers should only return schema DTOs.
|
||||
$actual_type = is_object( $handler_result ) ? get_class( $handler_result ) : gettype( $handler_result );
|
||||
$this->context->error_handler->log(
|
||||
sprintf( 'Handler for method "%s" returned unexpected type: %s', $method, $actual_type ),
|
||||
array(
|
||||
'method' => $method,
|
||||
'actual_type' => $actual_type,
|
||||
)
|
||||
);
|
||||
$unexpected_error = McpErrorFactory::internal_error( $request_id, 'Handler returned invalid response type.' );
|
||||
$result = array( 'error' => $unexpected_error->getError()->toArray() );
|
||||
$tags = array_merge( $common_tags, $component_tags, array( 'status' => 'error' ) );
|
||||
$tags['error_code'] = $unexpected_error->getError()->getCode();
|
||||
$this->context->observability_handler->record_event( 'mcp.request', $tags, $duration );
|
||||
|
||||
return $result;
|
||||
} catch ( \Throwable $exception ) {
|
||||
// Calculate request duration.
|
||||
$duration = ( microtime( true ) - $start_time ) * 1000; // Convert to milliseconds.
|
||||
|
||||
// Track exception with categorization.
|
||||
$tags = array_merge(
|
||||
$common_tags,
|
||||
$component_tags,
|
||||
array(
|
||||
'status' => 'error',
|
||||
'error_type' => get_class( $exception ),
|
||||
'error_category' => $this->categorize_error( $exception ),
|
||||
)
|
||||
);
|
||||
$this->context->observability_handler->record_event( 'mcp.request', $tags, $duration );
|
||||
|
||||
// Create error response from exception.
|
||||
$unexpected_error = McpErrorFactory::internal_error( $request_id, 'Handler error occurred' );
|
||||
|
||||
return array( 'error' => $unexpected_error->getError()->toArray() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve per-component observability tags for a request.
|
||||
*
|
||||
* This replaces legacy approaches that derived tags from DTO `_meta`.
|
||||
*
|
||||
* @param string $method MCP method name.
|
||||
* @param array $params Request parameters (root or nested under `params`).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function resolve_component_observability_context( string $method, array $params ): array {
|
||||
$request_params = $params['params'] ?? $params;
|
||||
|
||||
if ( ! is_array( $request_params ) ) {
|
||||
$request_params = array();
|
||||
}
|
||||
|
||||
switch ( $method ) {
|
||||
case 'tools/call':
|
||||
$tool_name = $request_params['name'] ?? null;
|
||||
$tool_name = is_string( $tool_name ) ? trim( $tool_name ) : null;
|
||||
|
||||
if ( null === $tool_name || '' === $tool_name ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$mcp_tool = $this->context->mcp_server->get_mcp_tool( $tool_name );
|
||||
if ( $mcp_tool ) {
|
||||
return $mcp_tool->get_observability_context();
|
||||
}
|
||||
|
||||
return array(
|
||||
'component_type' => 'tool',
|
||||
'tool_name' => $tool_name,
|
||||
);
|
||||
|
||||
case 'prompts/get':
|
||||
$prompt_name = $request_params['name'] ?? null;
|
||||
$prompt_name = is_string( $prompt_name ) ? trim( $prompt_name ) : null;
|
||||
|
||||
if ( null === $prompt_name || '' === $prompt_name ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$mcp_prompt = $this->context->mcp_server->get_mcp_prompt( $prompt_name );
|
||||
if ( $mcp_prompt ) {
|
||||
return $mcp_prompt->get_observability_context();
|
||||
}
|
||||
|
||||
return array(
|
||||
'component_type' => 'prompt',
|
||||
'prompt_name' => $prompt_name,
|
||||
);
|
||||
|
||||
case 'resources/read':
|
||||
$resource_uri = $request_params['uri'] ?? null;
|
||||
$resource_uri = is_string( $resource_uri ) ? trim( $resource_uri ) : null;
|
||||
|
||||
if ( null === $resource_uri || '' === $resource_uri ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$mcp_resource = $this->context->mcp_server->get_mcp_resource( $resource_uri );
|
||||
if ( $mcp_resource ) {
|
||||
return $mcp_resource->get_observability_context();
|
||||
}
|
||||
|
||||
return array(
|
||||
'component_type' => 'resource',
|
||||
'resource_uri' => $resource_uri,
|
||||
);
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize request params for logging to remove sensitive data and limit size.
|
||||
*
|
||||
* @param array $params The request parameters to sanitize.
|
||||
*
|
||||
* @return array Sanitized parameters safe for logging.
|
||||
*/
|
||||
private function sanitize_params_for_logging( array $params ): array {
|
||||
// Return early for empty parameters.
|
||||
if ( empty( $params ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$sanitized = array();
|
||||
|
||||
// Extract only safe, useful fields for observability
|
||||
$safe_fields = array( 'name', 'protocolVersion', 'uri' );
|
||||
|
||||
foreach ( $safe_fields as $field ) {
|
||||
if ( ! isset( $params[ $field ] ) || ! is_scalar( $params[ $field ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sanitized[ $field ] = $params[ $field ];
|
||||
}
|
||||
|
||||
// Add clientInfo name if available (useful for debugging)
|
||||
if ( isset( $params['clientInfo']['name'] ) ) {
|
||||
$sanitized['client_name'] = $params['clientInfo']['name'];
|
||||
}
|
||||
|
||||
// Add arguments count for tool calls (but not the actual arguments to avoid logging sensitive data).
|
||||
// Also filter out sensitive-looking keys to avoid leaking secret names.
|
||||
if ( isset( $params['arguments'] ) && is_array( $params['arguments'] ) ) {
|
||||
$sanitized['arguments_count'] = count( $params['arguments'] );
|
||||
|
||||
// Filter argument keys to exclude sensitive-looking ones.
|
||||
$safe_keys = array();
|
||||
foreach ( array_keys( $params['arguments'] ) as $arg_key ) {
|
||||
if ( McpObservabilityHelperTrait::is_sensitive_key( (string) $arg_key ) ) {
|
||||
$safe_keys[] = '[REDACTED]';
|
||||
} else {
|
||||
$safe_keys[] = $arg_key;
|
||||
}
|
||||
}
|
||||
$sanitized['arguments_keys'] = $safe_keys;
|
||||
}
|
||||
|
||||
return $sanitized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle initialize requests with session management.
|
||||
*
|
||||
* Converts InitializeResult DTO to array and adds session management.
|
||||
*
|
||||
* @param array $params The request parameters.
|
||||
* @param mixed $request_id The request ID.
|
||||
* @param \WP\MCP\Transport\Infrastructure\HttpRequestContext|null $http_context HTTP context for session management.
|
||||
* @param string|null $new_session_id Newly created session id, if any.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\AbstractDataTransferObject
|
||||
*/
|
||||
private function handle_initialize_with_session( array $params, $request_id, ?HttpRequestContext $http_context, ?string &$new_session_id = null ): AbstractDataTransferObject {
|
||||
// Extract client protocol version from params, defaulting to empty string if missing.
|
||||
$client_version = isset( $params['protocolVersion'] ) && is_string( $params['protocolVersion'] ) ? $params['protocolVersion'] : '';
|
||||
|
||||
// Get the initialize response from the handler (returns InitializeResult DTO).
|
||||
$init_result = $this->context->initialize_handler->handle( $client_version );
|
||||
|
||||
// Handle session creation if HTTP context is provided.
|
||||
// InitializeResult DTO never has errors - errors would be thrown as exceptions.
|
||||
if ( $http_context && ! $http_context->session_id ) {
|
||||
$session_result = HttpSessionValidator::create_session( $params );
|
||||
|
||||
if ( is_array( $session_result ) ) {
|
||||
$error = $session_result['error'] ?? array();
|
||||
|
||||
return McpErrorFactory::create_error_response(
|
||||
$request_id,
|
||||
isset( $error['code'] ) ? (int) $error['code'] : McpErrorFactory::INTERNAL_ERROR,
|
||||
(string) ( $error['message'] ?? __( 'Failed to create session', 'mcp-adapter' ) ),
|
||||
$error['data'] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
$new_session_id = $session_result;
|
||||
}
|
||||
|
||||
return $init_result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a method not found error with generic format.
|
||||
*
|
||||
* @param string $method The method that was not found.
|
||||
* @param mixed $request_id The request ID.
|
||||
*
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\JSONRPCErrorResponse
|
||||
*/
|
||||
private function create_method_not_found_error( string $method, $request_id ): JSONRPCErrorResponse {
|
||||
return McpErrorFactory::method_not_found( $request_id, $method );
|
||||
}
|
||||
|
||||
/**
|
||||
* Categorize an exception into a general error category.
|
||||
*
|
||||
* @param \Throwable $exception The exception to categorize.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function categorize_error( \Throwable $exception ): string {
|
||||
$error_categories = array(
|
||||
\ArgumentCountError::class => 'arguments',
|
||||
\TypeError::class => 'type',
|
||||
\InvalidArgumentException::class => 'validation',
|
||||
\LogicException::class => 'logic',
|
||||
\RuntimeException::class => 'execution',
|
||||
\Error::class => 'system',
|
||||
);
|
||||
|
||||
foreach ( $error_categories as $class => $category ) {
|
||||
if ( $exception instanceof $class ) {
|
||||
return $category;
|
||||
}
|
||||
}
|
||||
|
||||
return 'unknown';
|
||||
}
|
||||
}
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
<?php
|
||||
/**
|
||||
* MCP Session Manager using User Meta
|
||||
*
|
||||
*
|
||||
* @package McpAdapter
|
||||
*/
|
||||
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace WP\MCP\Transport\Infrastructure;
|
||||
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* MCP Session Manager
|
||||
*
|
||||
* Handles session creation, validation, and cleanup using user meta storage.
|
||||
* Sessions are tied to authenticated users to prevent anonymous session flooding.
|
||||
*/
|
||||
final class SessionManager {
|
||||
|
||||
/**
|
||||
* User meta key for storing sessions
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private const SESSION_META_KEY = 'mcp_adapter_sessions';
|
||||
|
||||
/**
|
||||
* Maximum sessions per user.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private const DEFAULT_MAX_SESSIONS = 32;
|
||||
|
||||
/**
|
||||
* Session inactivity timeout in seconds (24 hours).
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private const DEFAULT_INACTIVITY_TIMEOUT = DAY_IN_SECONDS;
|
||||
|
||||
/**
|
||||
* Minimum interval between last_activity writes in seconds.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private const DEFAULT_ACTIVITY_UPDATE_INTERVAL = 60;
|
||||
|
||||
/**
|
||||
* Create a new session for a user
|
||||
*
|
||||
* @param int $user_id The user ID.
|
||||
* @param array $params Client parameters from initialize request.
|
||||
*
|
||||
* @return string|false The session ID on success, false on failure.
|
||||
*/
|
||||
public static function create_session( int $user_id, array $params = array() ) {
|
||||
if ( ! $user_id || ! get_user_by( 'id', $user_id ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Cleanup inactive sessions first
|
||||
self::cleanup_expired_sessions( $user_id );
|
||||
|
||||
// Get current sessions
|
||||
$sessions = self::get_all_user_sessions( $user_id );
|
||||
|
||||
// Check session limit - remove oldest if over limit
|
||||
$config = self::get_config();
|
||||
$max_sessions = $config['max_sessions'];
|
||||
if ( count( $sessions ) >= $max_sessions ) {
|
||||
// Remove oldest session (FIFO) - sort by created_at and remove first
|
||||
uasort(
|
||||
$sessions,
|
||||
static function ( $a, $b ) {
|
||||
return $a['created_at'] <=> $b['created_at'];
|
||||
}
|
||||
);
|
||||
|
||||
array_shift( $sessions );
|
||||
}
|
||||
|
||||
// Create a new session
|
||||
$session_id = wp_generate_uuid4();
|
||||
$now = time();
|
||||
|
||||
$sessions[ $session_id ] = array(
|
||||
'created_at' => $now,
|
||||
'last_activity' => $now,
|
||||
'client_params' => $params,
|
||||
);
|
||||
|
||||
// Save sessions
|
||||
update_user_meta( $user_id, self::SESSION_META_KEY, $sessions );
|
||||
|
||||
return $session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleanup inactive sessions for a user
|
||||
*
|
||||
* @param int $user_id The user ID.
|
||||
*
|
||||
* @return int Number of sessions removed.
|
||||
*/
|
||||
public static function cleanup_expired_sessions( int $user_id ): int {
|
||||
if ( ! $user_id ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$sessions = self::get_all_user_sessions( $user_id );
|
||||
$now = time();
|
||||
$removed = 0;
|
||||
|
||||
$config = self::get_config();
|
||||
$inactivity_timeout = $config['inactivity_timeout'];
|
||||
|
||||
foreach ( $sessions as $session_id => $session ) {
|
||||
// Check if still active - skip if valid
|
||||
if ( $session['last_activity'] + $inactivity_timeout >= $now ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Session is inactive - remove it
|
||||
unset( $sessions[ $session_id ] );
|
||||
++$removed;
|
||||
}
|
||||
|
||||
if ( $removed > 0 ) {
|
||||
if ( empty( $sessions ) ) {
|
||||
delete_user_meta( $user_id, self::SESSION_META_KEY );
|
||||
} else {
|
||||
update_user_meta( $user_id, self::SESSION_META_KEY, $sessions );
|
||||
}
|
||||
}
|
||||
|
||||
return $removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all sessions for a user
|
||||
*
|
||||
* @param int $user_id The user ID.
|
||||
*
|
||||
* @return array Array of sessions.
|
||||
*/
|
||||
public static function get_all_user_sessions( int $user_id ): array {
|
||||
if ( ! $user_id ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
$sessions = get_user_meta( $user_id, self::SESSION_META_KEY, true );
|
||||
|
||||
if ( ! is_array( $sessions ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return $sessions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get configuration values.
|
||||
*
|
||||
* @return array{max_sessions: int, inactivity_timeout: int, activity_update_interval: int} Configuration array.
|
||||
*/
|
||||
private static function get_config(): array {
|
||||
/**
|
||||
* Filters the maximum number of MCP sessions allowed per user.
|
||||
*
|
||||
* When a user exceeds this limit, the oldest inactive session is
|
||||
* automatically removed to make room for new sessions.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param int $max_sessions Maximum sessions per user. Default 32.
|
||||
*/
|
||||
$max_sessions = (int) apply_filters( 'mcp_adapter_session_max_per_user', self::DEFAULT_MAX_SESSIONS );
|
||||
|
||||
/**
|
||||
* Filters the session inactivity timeout in seconds.
|
||||
*
|
||||
* Sessions that have been inactive longer than this duration are
|
||||
* considered expired and may be cleaned up automatically.
|
||||
*
|
||||
* @since 0.3.0
|
||||
*
|
||||
* @param int $timeout Inactivity timeout in seconds. Default DAY_IN_SECONDS (86400 / 24 hours).
|
||||
*/
|
||||
$inactivity_timeout = (int) apply_filters( 'mcp_adapter_session_inactivity_timeout', self::DEFAULT_INACTIVITY_TIMEOUT );
|
||||
|
||||
/**
|
||||
* Filters the minimum interval between session last_activity writes.
|
||||
*
|
||||
* To reduce write amplification, the session manager only updates
|
||||
* `last_activity` if at least this many seconds have elapsed since
|
||||
* the last write.
|
||||
*
|
||||
* @since 0.5.0
|
||||
*
|
||||
* @param int $interval Minimum seconds between writes. Default 60.
|
||||
*/
|
||||
$activity_update_interval = (int) apply_filters( 'mcp_adapter_session_activity_update_interval', self::DEFAULT_ACTIVITY_UPDATE_INTERVAL );
|
||||
|
||||
// Clamp: interval must be less than inactivity timeout to prevent
|
||||
// sessions from expiring despite active use.
|
||||
if ( $activity_update_interval >= $inactivity_timeout ) {
|
||||
$activity_update_interval = (int) ( $inactivity_timeout / 2 );
|
||||
}
|
||||
|
||||
return array(
|
||||
'max_sessions' => $max_sessions,
|
||||
'inactivity_timeout' => $inactivity_timeout,
|
||||
'activity_update_interval' => max( 0, $activity_update_interval ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific session for a user
|
||||
*
|
||||
* @param int $user_id The user ID.
|
||||
* @param string $session_id The session ID.
|
||||
*
|
||||
* @return array|\WP_Error|false Session data on success, WP_Error on invalid input, false if not found or inactive.
|
||||
*/
|
||||
public static function get_session( int $user_id, string $session_id ) {
|
||||
if ( ! $user_id || ! $session_id ) {
|
||||
return new WP_Error( 'mcp_session_invalid_input', 'Invalid user ID or session ID.' );
|
||||
}
|
||||
|
||||
$sessions = self::get_all_user_sessions( $user_id );
|
||||
|
||||
if ( ! isset( $sessions[ $session_id ] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$session = $sessions[ $session_id ];
|
||||
|
||||
// Check inactivity timeout
|
||||
$config = self::get_config();
|
||||
$inactivity_timeout = $config['inactivity_timeout'];
|
||||
if ( $session['last_activity'] + $inactivity_timeout < time() ) {
|
||||
self::clear_session( $user_id, $session_id );
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear an inactive session (internal cleanup).
|
||||
*
|
||||
* @param int $user_id The user ID.
|
||||
* @param string $session_id The session ID to clear.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function clear_session( int $user_id, string $session_id ): void {
|
||||
$sessions = self::get_all_user_sessions( $user_id );
|
||||
|
||||
if ( ! isset( $sessions[ $session_id ] ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
unset( $sessions[ $session_id ] );
|
||||
update_user_meta( $user_id, self::SESSION_META_KEY, $sessions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a session and update last activity
|
||||
*
|
||||
* @param int $user_id The user ID.
|
||||
* @param string $session_id The session ID.
|
||||
*
|
||||
* @return bool True if valid, false otherwise.
|
||||
*/
|
||||
public static function validate_session( int $user_id, string $session_id ): bool {
|
||||
if ( ! $user_id || ! $session_id ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$sessions = self::get_all_user_sessions( $user_id );
|
||||
|
||||
if ( ! isset( $sessions[ $session_id ] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$session = $sessions[ $session_id ];
|
||||
|
||||
// Check inactivity timeout
|
||||
$config = self::get_config();
|
||||
$inactivity_timeout = $config['inactivity_timeout'];
|
||||
if ( $session['last_activity'] + $inactivity_timeout < time() ) {
|
||||
self::clear_session( $user_id, $session_id );
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Throttle last_activity writes to reduce write amplification
|
||||
$activity_update_interval = $config['activity_update_interval'];
|
||||
if ( time() - $session['last_activity'] >= $activity_update_interval ) {
|
||||
$sessions[ $session_id ]['last_activity'] = time();
|
||||
update_user_meta( $user_id, self::SESSION_META_KEY, $sessions );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a specific session
|
||||
*
|
||||
* @param int $user_id The user ID.
|
||||
* @param string $session_id The session ID.
|
||||
*
|
||||
* @return bool True on success, false on failure.
|
||||
*/
|
||||
public static function delete_session( int $user_id, string $session_id ): bool {
|
||||
if ( ! $user_id || ! $session_id ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$sessions = self::get_all_user_sessions( $user_id );
|
||||
|
||||
if ( ! isset( $sessions[ $session_id ] ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
unset( $sessions[ $session_id ] );
|
||||
|
||||
if ( empty( $sessions ) ) {
|
||||
delete_user_meta( $user_id, self::SESSION_META_KEY );
|
||||
} else {
|
||||
update_user_meta( $user_id, self::SESSION_META_KEY, $sessions );
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
/**
|
||||
* WordPress MCP Adapter
|
||||
*
|
||||
* @package mcp-adapter
|
||||
* @author WordPress.org Contributors
|
||||
* @copyright 2025 Plugin Contributors
|
||||
* @license GPL-2.0-or-later
|
||||
*
|
||||
* @wordpress-plugin
|
||||
* Plugin Name: MCP Adapter
|
||||
* Plugin URI: https://github.com/WordPress/mcp-adapter
|
||||
* Description: Adapter for Abilities API, letting the abilities to be used as MCP tools, resources or prompts.
|
||||
* Requires at least: 6.8
|
||||
* Version: 0.5.0
|
||||
* Requires PHP: 7.4
|
||||
* Author: WordPress.org Contributors
|
||||
* Author URI: https://github.com/WordPress/mcp-adapter/graphs/contributors
|
||||
* License: GPLv2 or later
|
||||
* License URI: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
* Text Domain: mcp-adapter
|
||||
*/
|
||||
|
||||
declare (strict_types = 1);
|
||||
|
||||
namespace WP\MCP;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit();
|
||||
|
||||
/**
|
||||
* Define the plugin constants.
|
||||
*/
|
||||
function constants(): void {
|
||||
/**
|
||||
* Shortcut constant to the path of this file.
|
||||
*/
|
||||
define( 'WP_MCP_DIR', plugin_dir_path( __FILE__ ) );
|
||||
|
||||
/**
|
||||
* Version of the plugin.
|
||||
*/
|
||||
define( 'WP_MCP_VERSION', '0.5.0' );
|
||||
}
|
||||
|
||||
constants();
|
||||
require_once __DIR__ . '/includes/Autoloader.php';
|
||||
|
||||
// If autoloader failed, we cannot proceed.
|
||||
if ( ! Autoloader::autoload() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Load the plugin.
|
||||
if ( class_exists( Plugin::class ) ) {
|
||||
Plugin::instance();
|
||||
}
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
<https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 2 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/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Moe Ghoul>, 1 April 1989
|
||||
Moe Ghoul, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "wordpress/php-mcp-schema",
|
||||
"description": "PHP DTOs for the Model Context Protocol (MCP) specification",
|
||||
"type": "library",
|
||||
"license": "GPL-2.0-or-later",
|
||||
"keywords": [
|
||||
"mcp",
|
||||
"model-context-protocol",
|
||||
"dto",
|
||||
"schema",
|
||||
"php"
|
||||
],
|
||||
"homepage": "https://github.com/WordPress/php-mcp-schema",
|
||||
"authors": [
|
||||
{
|
||||
"name": "WordPress",
|
||||
"homepage": "https://wordpress.org"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=7.4"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpstan/phpstan": "^1.10"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"WP\\McpSchema\\": "src/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
},
|
||||
"scripts": {
|
||||
"analyse": "phpstan analyse",
|
||||
"phpstan": "@analyse"
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\PrimitiveSchemaDefinitionInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class BooleanSchema extends AbstractDataTransferObject implements PrimitiveSchemaDefinitionInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'boolean';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'type';
|
||||
public const DISCRIMINATOR_VALUE = 'boolean';
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var 'boolean'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var bool|null
|
||||
*/
|
||||
protected ?bool $default;
|
||||
|
||||
/**
|
||||
* @param string|null $title @since 2025-06-18
|
||||
* @param string|null $description @since 2025-06-18
|
||||
* @param bool|null $default @since 2025-06-18
|
||||
*/
|
||||
public function __construct(
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?bool $default = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'boolean',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* default?: bool|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asBoolOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'boolean'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool|null
|
||||
*/
|
||||
public function getDefault(): ?bool
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Factory\ElicitRequestParamsFactory;
|
||||
use WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface;
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\JSONRPCRequest;
|
||||
use WP\McpSchema\Common\Protocol\Union\ServerRequestInterface;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* A request from the server to elicit additional information from the user via the client.
|
||||
*
|
||||
* @since 2025-06-18
|
||||
* @last-updated 2025-11-25 (modified property: params)
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ElicitRequest extends JSONRPCRequest implements ServerRequestInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const METHOD = 'elicitation/create';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'method';
|
||||
public const DISCRIMINATOR_VALUE = 'elicitation/create';
|
||||
|
||||
/**
|
||||
* @var \WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface
|
||||
*/
|
||||
protected ElicitRequestParamsInterface $typedParams;
|
||||
|
||||
/**
|
||||
* @param '2.0' $jsonrpc @since 2025-11-25
|
||||
* @param string|number $id @since 2025-11-25
|
||||
* @param \WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface $params @since 2025-06-18
|
||||
*/
|
||||
public function __construct(
|
||||
string $jsonrpc,
|
||||
$id,
|
||||
ElicitRequestParamsInterface $params
|
||||
) {
|
||||
parent::__construct(self::METHOD, $jsonrpc, $id, null);
|
||||
$this->typedParams = $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* jsonrpc: '2.0',
|
||||
* id: string|number,
|
||||
* method: 'elicitation/create',
|
||||
* params: array<string, mixed>|\WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['jsonrpc', 'id', 'params']);
|
||||
|
||||
/** @var '2.0' $jsonrpc */
|
||||
$jsonrpc = self::asString($data['jsonrpc']);
|
||||
|
||||
/** @var string|number $id */
|
||||
$id = self::asStringOrNumber($data['id']);
|
||||
|
||||
/** @var \WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface $params */
|
||||
$params = is_array($data['params'])
|
||||
? ElicitRequestParamsFactory::fromArray(self::asArray($data['params']))
|
||||
: $data['params'];
|
||||
|
||||
return new self(
|
||||
$jsonrpc,
|
||||
$id,
|
||||
$params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = parent::toArray();
|
||||
|
||||
$result['params'] = $this->typedParams->toArray();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface
|
||||
*/
|
||||
public function getTypedParams(): ElicitRequestParamsInterface
|
||||
{
|
||||
return $this->typedParams;
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface;
|
||||
use WP\McpSchema\Client\Tasks\DTO\TaskMetadata;
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta;
|
||||
use WP\McpSchema\Common\Tasks\DTO\TaskAugmentedRequestParams;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* The parameters for a request to elicit non-sensitive information from the user via a form in the client.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ElicitRequestFormParams extends TaskAugmentedRequestParams implements ElicitRequestParamsInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const MODE = 'form';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'mode';
|
||||
public const DISCRIMINATOR_VALUE = 'form';
|
||||
|
||||
/**
|
||||
* The elicitation mode.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var 'form'|null
|
||||
*/
|
||||
protected ?string $mode;
|
||||
|
||||
/**
|
||||
* The message to present to the user describing what information is being requested.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $message;
|
||||
|
||||
/**
|
||||
* A restricted subset of JSON Schema.
|
||||
* Only top-level properties are allowed, without nesting.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var \WP\McpSchema\Client\Elicitation\DTO\ElicitRequestFormParamsRequestedSchema
|
||||
*/
|
||||
protected ElicitRequestFormParamsRequestedSchema $requestedSchema;
|
||||
|
||||
/**
|
||||
* @param string $message @since 2025-11-25
|
||||
* @param \WP\McpSchema\Client\Elicitation\DTO\ElicitRequestFormParamsRequestedSchema $requestedSchema @since 2025-11-25
|
||||
* @param \WP\McpSchema\Client\Tasks\DTO\TaskMetadata|null $task @since 2025-11-25
|
||||
* @param \WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta|null $_meta @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
string $message,
|
||||
ElicitRequestFormParamsRequestedSchema $requestedSchema,
|
||||
?TaskMetadata $task = null,
|
||||
?RequestParamsMeta $_meta = null
|
||||
) {
|
||||
parent::__construct($_meta, $task);
|
||||
$this->mode = self::MODE;
|
||||
$this->message = $message;
|
||||
$this->requestedSchema = $requestedSchema;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* task?: array<string, mixed>|\WP\McpSchema\Client\Tasks\DTO\TaskMetadata|null,
|
||||
* _meta?: array<string, mixed>|\WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta|null,
|
||||
* mode?: 'form'|null,
|
||||
* message: string,
|
||||
* requestedSchema: array<string, mixed>|\WP\McpSchema\Client\Elicitation\DTO\ElicitRequestFormParamsRequestedSchema
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['message', 'requestedSchema']);
|
||||
|
||||
/** @var \WP\McpSchema\Client\Elicitation\DTO\ElicitRequestFormParamsRequestedSchema $requestedSchema */
|
||||
$requestedSchema = is_array($data['requestedSchema'])
|
||||
? ElicitRequestFormParamsRequestedSchema::fromArray(self::asArray($data['requestedSchema']))
|
||||
: $data['requestedSchema'];
|
||||
|
||||
/** @var \WP\McpSchema\Client\Tasks\DTO\TaskMetadata|null $task */
|
||||
$task = isset($data['task'])
|
||||
? (is_array($data['task'])
|
||||
? TaskMetadata::fromArray(self::asArray($data['task']))
|
||||
: $data['task'])
|
||||
: null;
|
||||
|
||||
/** @var \WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta|null $_meta */
|
||||
$_meta = isset($data['_meta'])
|
||||
? (is_array($data['_meta'])
|
||||
? RequestParamsMeta::fromArray(self::asArray($data['_meta']))
|
||||
: $data['_meta'])
|
||||
: null;
|
||||
|
||||
return new self(
|
||||
self::asString($data['message']),
|
||||
$requestedSchema,
|
||||
$task,
|
||||
$_meta
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = parent::toArray();
|
||||
|
||||
if ($this->mode !== null) {
|
||||
$result['mode'] = $this->mode;
|
||||
}
|
||||
$result['message'] = $this->message;
|
||||
$result['requestedSchema'] = $this->requestedSchema->toArray();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'form'|null
|
||||
*/
|
||||
public function getMode(): ?string
|
||||
{
|
||||
return $this->mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getMessage(): string
|
||||
{
|
||||
return $this->message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Elicitation\DTO\ElicitRequestFormParamsRequestedSchema
|
||||
*/
|
||||
public function getRequestedSchema(): ElicitRequestFormParamsRequestedSchema
|
||||
{
|
||||
return $this->requestedSchema;
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* A restricted subset of JSON Schema.
|
||||
* Only top-level properties are allowed, without nesting.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ElicitRequestFormParamsRequestedSchema extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'object';
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $schema;
|
||||
|
||||
/**
|
||||
* @var 'object'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* @var array<string>|null
|
||||
*/
|
||||
protected ?array $required;
|
||||
|
||||
/**
|
||||
* @param string|null $schema
|
||||
* @param array<string>|null $required
|
||||
*/
|
||||
public function __construct(
|
||||
?string $schema = null,
|
||||
?array $required = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->schema = $schema;
|
||||
$this->required = $required;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* '$schema'?: string|null,
|
||||
* type: 'object',
|
||||
* required?: array<string>|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
self::asStringOrNull($data['$schema'] ?? null),
|
||||
self::asStringArrayOrNull($data['required'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($this->schema !== null) {
|
||||
$result['$schema'] = $this->schema;
|
||||
}
|
||||
$result['type'] = $this->type;
|
||||
if ($this->required !== null) {
|
||||
$result['required'] = $this->required;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getSchema(): ?string
|
||||
{
|
||||
return $this->schema;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'object'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>|null
|
||||
*/
|
||||
public function getRequired(): ?array
|
||||
{
|
||||
return $this->required;
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface;
|
||||
use WP\McpSchema\Client\Tasks\DTO\TaskMetadata;
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta;
|
||||
use WP\McpSchema\Common\Tasks\DTO\TaskAugmentedRequestParams;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* The parameters for a request to elicit information from the user via a URL in the client.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ElicitRequestURLParams extends TaskAugmentedRequestParams implements ElicitRequestParamsInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const MODE = 'url';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'mode';
|
||||
public const DISCRIMINATOR_VALUE = 'url';
|
||||
|
||||
/**
|
||||
* The elicitation mode.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var 'url'
|
||||
*/
|
||||
protected string $mode;
|
||||
|
||||
/**
|
||||
* The message to present to the user explaining why the interaction is needed.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $message;
|
||||
|
||||
/**
|
||||
* The ID of the elicitation, which must be unique within the context of the server.
|
||||
* The client MUST treat this ID as an opaque value.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $elicitationId;
|
||||
|
||||
/**
|
||||
* The URL that the user should navigate to.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $url;
|
||||
|
||||
/**
|
||||
* @param string $message @since 2025-11-25
|
||||
* @param string $elicitationId @since 2025-11-25
|
||||
* @param string $url @since 2025-11-25
|
||||
* @param \WP\McpSchema\Client\Tasks\DTO\TaskMetadata|null $task @since 2025-11-25
|
||||
* @param \WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta|null $_meta @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
string $message,
|
||||
string $elicitationId,
|
||||
string $url,
|
||||
?TaskMetadata $task = null,
|
||||
?RequestParamsMeta $_meta = null
|
||||
) {
|
||||
parent::__construct($_meta, $task);
|
||||
$this->mode = self::MODE;
|
||||
$this->message = $message;
|
||||
$this->elicitationId = $elicitationId;
|
||||
$this->url = $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* task?: array<string, mixed>|\WP\McpSchema\Client\Tasks\DTO\TaskMetadata|null,
|
||||
* _meta?: array<string, mixed>|\WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta|null,
|
||||
* mode: 'url',
|
||||
* message: string,
|
||||
* elicitationId: string,
|
||||
* url: string
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['message', 'elicitationId', 'url']);
|
||||
|
||||
/** @var \WP\McpSchema\Client\Tasks\DTO\TaskMetadata|null $task */
|
||||
$task = isset($data['task'])
|
||||
? (is_array($data['task'])
|
||||
? TaskMetadata::fromArray(self::asArray($data['task']))
|
||||
: $data['task'])
|
||||
: null;
|
||||
|
||||
/** @var \WP\McpSchema\Common\JsonRpc\DTO\RequestParamsMeta|null $_meta */
|
||||
$_meta = isset($data['_meta'])
|
||||
? (is_array($data['_meta'])
|
||||
? RequestParamsMeta::fromArray(self::asArray($data['_meta']))
|
||||
: $data['_meta'])
|
||||
: null;
|
||||
|
||||
return new self(
|
||||
self::asString($data['message']),
|
||||
self::asString($data['elicitationId']),
|
||||
self::asString($data['url']),
|
||||
$task,
|
||||
$_meta
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = parent::toArray();
|
||||
|
||||
$result['mode'] = $this->mode;
|
||||
$result['message'] = $this->message;
|
||||
$result['elicitationId'] = $this->elicitationId;
|
||||
$result['url'] = $this->url;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'url'
|
||||
*/
|
||||
public function getMode(): string
|
||||
{
|
||||
return $this->mode;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getMessage(): string
|
||||
{
|
||||
return $this->message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getElicitationId(): string
|
||||
{
|
||||
return $this->elicitationId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getUrl(): string
|
||||
{
|
||||
return $this->url;
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Lifecycle\Union\ClientResultInterface;
|
||||
use WP\McpSchema\Common\Protocol\DTO\Result;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* The client's response to an elicitation request.
|
||||
*
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ElicitResult extends Result implements ClientResultInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Wire keys this class models. Anything else is kept in $additionalProperties.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const KNOWN_KEYS = ['_meta', 'action', 'content'];
|
||||
|
||||
/**
|
||||
* The user action in response to the elicitation.
|
||||
* - "accept": User submitted the form/confirmed the action
|
||||
* - "decline": User explicitly decline the action
|
||||
* - "cancel": User dismissed without making an explicit choice
|
||||
*
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var 'accept'|'decline'|'cancel'
|
||||
*/
|
||||
protected string $action;
|
||||
|
||||
/**
|
||||
* The submitted form data, only present when action is "accept" and mode was "form".
|
||||
* Contains values matching the requested schema.
|
||||
* Omitted for out-of-band mode responses.
|
||||
*
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var array<string, string>|null
|
||||
*/
|
||||
protected ?array $content;
|
||||
|
||||
/**
|
||||
* @param 'accept'|'decline'|'cancel' $action @since 2025-06-18
|
||||
* @param array<string, mixed>|null $_meta @since 2025-06-18
|
||||
* @param array<string, string>|null $content @since 2025-06-18
|
||||
* @param array<string, mixed>|null $additionalProperties
|
||||
*/
|
||||
public function __construct(
|
||||
string $action,
|
||||
?array $_meta = null,
|
||||
?array $content = null,
|
||||
?array $additionalProperties = null
|
||||
) {
|
||||
parent::__construct($_meta, $additionalProperties);
|
||||
$this->action = $action;
|
||||
$this->content = $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* _meta?: array<string, mixed>|null,
|
||||
* action: 'accept'|'decline'|'cancel',
|
||||
* content?: array<string, string>|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['action']);
|
||||
|
||||
/** @var 'accept'|'decline'|'cancel' $action */
|
||||
$action = self::asString($data['action']);
|
||||
|
||||
return new self(
|
||||
$action,
|
||||
self::asArrayOrNull($data['_meta'] ?? null),
|
||||
self::asStringMapOrNull($data['content'] ?? null),
|
||||
self::additionalFields($data, self::KNOWN_KEYS)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = parent::toArray();
|
||||
|
||||
$result['action'] = $this->action;
|
||||
if ($this->content !== null) {
|
||||
$result['content'] = $this->content;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'accept'|'decline'|'cancel'
|
||||
*/
|
||||
public function getAction(): string
|
||||
{
|
||||
return $this->action;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>|null
|
||||
*/
|
||||
public function getContent(): ?array
|
||||
{
|
||||
return $this->content;
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\JSONRPCNotification;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
use WP\McpSchema\Server\Lifecycle\Union\ServerNotificationInterface;
|
||||
|
||||
/**
|
||||
* An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ElicitationCompleteNotification extends JSONRPCNotification implements ServerNotificationInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const METHOD = 'notifications/elicitation/complete';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'method';
|
||||
public const DISCRIMINATOR_VALUE = 'notifications/elicitation/complete';
|
||||
|
||||
/**
|
||||
* @var \WP\McpSchema\Client\Elicitation\DTO\ElicitationCompleteNotificationParams
|
||||
*/
|
||||
protected ElicitationCompleteNotificationParams $typedParams;
|
||||
|
||||
/**
|
||||
* @param '2.0' $jsonrpc @since 2025-11-25
|
||||
* @param \WP\McpSchema\Client\Elicitation\DTO\ElicitationCompleteNotificationParams $params @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
string $jsonrpc,
|
||||
ElicitationCompleteNotificationParams $params
|
||||
) {
|
||||
parent::__construct(self::METHOD, $jsonrpc, null);
|
||||
$this->typedParams = $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* jsonrpc: '2.0',
|
||||
* method: 'notifications/elicitation/complete',
|
||||
* params: array<string, mixed>|\WP\McpSchema\Client\Elicitation\DTO\ElicitationCompleteNotificationParams
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['jsonrpc', 'params']);
|
||||
|
||||
/** @var '2.0' $jsonrpc */
|
||||
$jsonrpc = self::asString($data['jsonrpc']);
|
||||
|
||||
/** @var \WP\McpSchema\Client\Elicitation\DTO\ElicitationCompleteNotificationParams $params */
|
||||
$params = is_array($data['params'])
|
||||
? ElicitationCompleteNotificationParams::fromArray(self::asArray($data['params']))
|
||||
: $data['params'];
|
||||
|
||||
return new self(
|
||||
$jsonrpc,
|
||||
$params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = parent::toArray();
|
||||
|
||||
$result['params'] = $this->typedParams->toArray();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Elicitation\DTO\ElicitationCompleteNotificationParams
|
||||
*/
|
||||
public function getTypedParams(): ElicitationCompleteNotificationParams
|
||||
{
|
||||
return $this->typedParams;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ElicitationCompleteNotificationParams extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* The ID of the elicitation that completed.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $elicitationId;
|
||||
|
||||
/**
|
||||
* @param string $elicitationId
|
||||
*/
|
||||
public function __construct(
|
||||
string $elicitationId
|
||||
) {
|
||||
$this->elicitationId = $elicitationId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* elicitationId: string
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['elicitationId']);
|
||||
|
||||
return new self(
|
||||
self::asString($data['elicitationId'])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['elicitationId'] = $this->elicitationId;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getElicitationId(): string
|
||||
{
|
||||
return $this->elicitationId;
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\EnumSchemaInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Use TitledSingleSelectEnumSchema instead.
|
||||
* This interface will be removed in a future version.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class LegacyTitledEnumSchema extends AbstractDataTransferObject implements EnumSchemaInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'string';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'type';
|
||||
public const DISCRIMINATOR_VALUE = 'string';
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var 'string'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $enum;
|
||||
|
||||
/**
|
||||
* (Legacy) Display names for enum values.
|
||||
* Non-standard according to JSON schema 2020-12.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var array<string>|null
|
||||
*/
|
||||
protected ?array $enumNames;
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $default;
|
||||
|
||||
/**
|
||||
* @param array<string> $enum @since 2025-11-25
|
||||
* @param string|null $title @since 2025-11-25
|
||||
* @param string|null $description @since 2025-11-25
|
||||
* @param array<string>|null $enumNames @since 2025-11-25
|
||||
* @param string|null $default @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
array $enum,
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?array $enumNames = null,
|
||||
?string $default = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->enum = $enum;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->enumNames = $enumNames;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'string',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* enum: array<string>,
|
||||
* enumNames?: array<string>|null,
|
||||
* default?: string|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['enum']);
|
||||
|
||||
return new self(
|
||||
self::asStringArray($data['enum']),
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asStringArrayOrNull($data['enumNames'] ?? null),
|
||||
self::asStringOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
$result['enum'] = $this->enum;
|
||||
if ($this->enumNames !== null) {
|
||||
$result['enumNames'] = $this->enumNames;
|
||||
}
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'string'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>
|
||||
*/
|
||||
public function getEnum(): array
|
||||
{
|
||||
return $this->enum;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>|null
|
||||
*/
|
||||
public function getEnumNames(): ?array
|
||||
{
|
||||
return $this->enumNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDefault(): ?string
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\PrimitiveSchemaDefinitionInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
* @last-updated 2025-11-25 (added properties: default)
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class NumberSchema extends AbstractDataTransferObject implements PrimitiveSchemaDefinitionInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var 'number'|'integer'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var float|null
|
||||
*/
|
||||
protected ?float $minimum;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var float|null
|
||||
*/
|
||||
protected ?float $maximum;
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var float|null
|
||||
*/
|
||||
protected ?float $default;
|
||||
|
||||
/**
|
||||
* @param 'number'|'integer' $type @since 2025-06-18
|
||||
* @param string|null $title @since 2025-06-18
|
||||
* @param string|null $description @since 2025-06-18
|
||||
* @param float|null $minimum @since 2025-06-18
|
||||
* @param float|null $maximum @since 2025-06-18
|
||||
* @param float|null $default @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
string $type,
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?float $minimum = null,
|
||||
?float $maximum = null,
|
||||
?float $default = null
|
||||
) {
|
||||
$this->type = $type;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->minimum = $minimum;
|
||||
$this->maximum = $maximum;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'number'|'integer',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* minimum?: float|null,
|
||||
* maximum?: float|null,
|
||||
* default?: float|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['type']);
|
||||
|
||||
/** @var 'number'|'integer' $type */
|
||||
$type = self::asString($data['type']);
|
||||
|
||||
return new self(
|
||||
$type,
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asFloatOrNull($data['minimum'] ?? null),
|
||||
self::asFloatOrNull($data['maximum'] ?? null),
|
||||
self::asFloatOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
if ($this->minimum !== null) {
|
||||
$result['minimum'] = $this->minimum;
|
||||
}
|
||||
if ($this->maximum !== null) {
|
||||
$result['maximum'] = $this->maximum;
|
||||
}
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'number'|'integer'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return float|null
|
||||
*/
|
||||
public function getMinimum(): ?float
|
||||
{
|
||||
return $this->minimum;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return float|null
|
||||
*/
|
||||
public function getMaximum(): ?float
|
||||
{
|
||||
return $this->maximum;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return float|null
|
||||
*/
|
||||
public function getDefault(): ?float
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\PrimitiveSchemaDefinitionInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
* @last-updated 2025-11-25 (added properties: default)
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class StringSchema extends AbstractDataTransferObject implements PrimitiveSchemaDefinitionInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'string';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'type';
|
||||
public const DISCRIMINATOR_VALUE = 'string';
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var 'string'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected ?int $minLength;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected ?int $maxLength;
|
||||
|
||||
/**
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var 'email'|'uri'|'date'|'date-time'|null
|
||||
*/
|
||||
protected ?string $format;
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $default;
|
||||
|
||||
/**
|
||||
* @param string|null $title @since 2025-06-18
|
||||
* @param string|null $description @since 2025-06-18
|
||||
* @param int|null $minLength @since 2025-06-18
|
||||
* @param int|null $maxLength @since 2025-06-18
|
||||
* @param 'email'|'uri'|'date'|'date-time'|null $format @since 2025-06-18
|
||||
* @param string|null $default @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?int $minLength = null,
|
||||
?int $maxLength = null,
|
||||
?string $format = null,
|
||||
?string $default = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->minLength = $minLength;
|
||||
$this->maxLength = $maxLength;
|
||||
$this->format = $format;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'string',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* minLength?: int|null,
|
||||
* maxLength?: int|null,
|
||||
* format?: 'email'|'uri'|'date'|'date-time'|null,
|
||||
* default?: string|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
/** @var 'email'|'uri'|'date'|'date-time'|null $format */
|
||||
$format = isset($data['format'])
|
||||
? self::asStringOrNull($data['format'])
|
||||
: null;
|
||||
|
||||
return new self(
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asIntOrNull($data['minLength'] ?? null),
|
||||
self::asIntOrNull($data['maxLength'] ?? null),
|
||||
$format,
|
||||
self::asStringOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
if ($this->minLength !== null) {
|
||||
$result['minLength'] = $this->minLength;
|
||||
}
|
||||
if ($this->maxLength !== null) {
|
||||
$result['maxLength'] = $this->maxLength;
|
||||
}
|
||||
if ($this->format !== null) {
|
||||
$result['format'] = $this->format;
|
||||
}
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'string'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
*/
|
||||
public function getMinLength(): ?int
|
||||
{
|
||||
return $this->minLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
*/
|
||||
public function getMaxLength(): ?int
|
||||
{
|
||||
return $this->maxLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'email'|'uri'|'date'|'date-time'|null
|
||||
*/
|
||||
public function getFormat(): ?string
|
||||
{
|
||||
return $this->format;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDefault(): ?string
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\MultiSelectEnumSchemaInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Schema for multiple-selection enumeration with display titles for each option.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class TitledMultiSelectEnumSchema extends AbstractDataTransferObject implements MultiSelectEnumSchemaInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'array';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'type';
|
||||
public const DISCRIMINATOR_VALUE = 'array';
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var 'array'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* Optional title for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* Optional description for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* Minimum number of items to select.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected ?int $minItems;
|
||||
|
||||
/**
|
||||
* Maximum number of items to select.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected ?int $maxItems;
|
||||
|
||||
/**
|
||||
* Schema for array items with enum options and display labels.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var \WP\McpSchema\Client\Elicitation\DTO\TitledMultiSelectEnumSchemaItems
|
||||
*/
|
||||
protected TitledMultiSelectEnumSchemaItems $items;
|
||||
|
||||
/**
|
||||
* Optional default value.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var array<string>|null
|
||||
*/
|
||||
protected ?array $default;
|
||||
|
||||
/**
|
||||
* @param \WP\McpSchema\Client\Elicitation\DTO\TitledMultiSelectEnumSchemaItems $items @since 2025-11-25
|
||||
* @param string|null $title @since 2025-11-25
|
||||
* @param string|null $description @since 2025-11-25
|
||||
* @param int|null $minItems @since 2025-11-25
|
||||
* @param int|null $maxItems @since 2025-11-25
|
||||
* @param array<string>|null $default @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
TitledMultiSelectEnumSchemaItems $items,
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?int $minItems = null,
|
||||
?int $maxItems = null,
|
||||
?array $default = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->items = $items;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->minItems = $minItems;
|
||||
$this->maxItems = $maxItems;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'array',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* minItems?: int|null,
|
||||
* maxItems?: int|null,
|
||||
* items: array<string, mixed>|\WP\McpSchema\Client\Elicitation\DTO\TitledMultiSelectEnumSchemaItems,
|
||||
* default?: array<string>|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['items']);
|
||||
|
||||
/** @var \WP\McpSchema\Client\Elicitation\DTO\TitledMultiSelectEnumSchemaItems $items */
|
||||
$items = is_array($data['items'])
|
||||
? TitledMultiSelectEnumSchemaItems::fromArray(self::asArray($data['items']))
|
||||
: $data['items'];
|
||||
|
||||
return new self(
|
||||
$items,
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asIntOrNull($data['minItems'] ?? null),
|
||||
self::asIntOrNull($data['maxItems'] ?? null),
|
||||
self::asStringArrayOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
if ($this->minItems !== null) {
|
||||
$result['minItems'] = $this->minItems;
|
||||
}
|
||||
if ($this->maxItems !== null) {
|
||||
$result['maxItems'] = $this->maxItems;
|
||||
}
|
||||
$result['items'] = $this->items->toArray();
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'array'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
*/
|
||||
public function getMinItems(): ?int
|
||||
{
|
||||
return $this->minItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
*/
|
||||
public function getMaxItems(): ?int
|
||||
{
|
||||
return $this->maxItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Elicitation\DTO\TitledMultiSelectEnumSchemaItems
|
||||
*/
|
||||
public function getItems(): TitledMultiSelectEnumSchemaItems
|
||||
{
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>|null
|
||||
*/
|
||||
public function getDefault(): ?array
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
|
||||
/**
|
||||
* Schema for array items with enum options and display labels.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class TitledMultiSelectEnumSchemaItems extends AbstractDataTransferObject
|
||||
{
|
||||
/**
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self();
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\SingleSelectEnumSchemaInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Schema for single-selection enumeration with display titles for each option.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class TitledSingleSelectEnumSchema extends AbstractDataTransferObject implements SingleSelectEnumSchemaInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'string';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'type';
|
||||
public const DISCRIMINATOR_VALUE = 'string';
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var 'string'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* Optional title for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* Optional description for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* Array of enum options with values and display labels.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var array<object>
|
||||
*/
|
||||
protected array $oneOf;
|
||||
|
||||
/**
|
||||
* Optional default value.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $default;
|
||||
|
||||
/**
|
||||
* @param array<object> $oneOf @since 2025-11-25
|
||||
* @param string|null $title @since 2025-11-25
|
||||
* @param string|null $description @since 2025-11-25
|
||||
* @param string|null $default @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
array $oneOf,
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?string $default = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->oneOf = $oneOf;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'string',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* oneOf: array<object>,
|
||||
* default?: string|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['oneOf']);
|
||||
|
||||
/** @var array<object> $oneOf */
|
||||
$oneOf = self::asArray($data['oneOf']);
|
||||
|
||||
return new self(
|
||||
$oneOf,
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asStringOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
$result['oneOf'] = $this->oneOf;
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'string'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<object>
|
||||
*/
|
||||
public function getOneOf(): array
|
||||
{
|
||||
return $this->oneOf;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDefault(): ?string
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\MultiSelectEnumSchemaInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Schema for multiple-selection enumeration without display titles for options.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class UntitledMultiSelectEnumSchema extends AbstractDataTransferObject implements MultiSelectEnumSchemaInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'array';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'type';
|
||||
public const DISCRIMINATOR_VALUE = 'array';
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var 'array'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* Optional title for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* Optional description for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* Minimum number of items to select.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected ?int $minItems;
|
||||
|
||||
/**
|
||||
* Maximum number of items to select.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var int|null
|
||||
*/
|
||||
protected ?int $maxItems;
|
||||
|
||||
/**
|
||||
* Schema for the array items.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var \WP\McpSchema\Client\Elicitation\DTO\UntitledMultiSelectEnumSchemaItems
|
||||
*/
|
||||
protected UntitledMultiSelectEnumSchemaItems $items;
|
||||
|
||||
/**
|
||||
* Optional default value.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var array<string>|null
|
||||
*/
|
||||
protected ?array $default;
|
||||
|
||||
/**
|
||||
* @param \WP\McpSchema\Client\Elicitation\DTO\UntitledMultiSelectEnumSchemaItems $items @since 2025-11-25
|
||||
* @param string|null $title @since 2025-11-25
|
||||
* @param string|null $description @since 2025-11-25
|
||||
* @param int|null $minItems @since 2025-11-25
|
||||
* @param int|null $maxItems @since 2025-11-25
|
||||
* @param array<string>|null $default @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
UntitledMultiSelectEnumSchemaItems $items,
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?int $minItems = null,
|
||||
?int $maxItems = null,
|
||||
?array $default = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->items = $items;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->minItems = $minItems;
|
||||
$this->maxItems = $maxItems;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'array',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* minItems?: int|null,
|
||||
* maxItems?: int|null,
|
||||
* items: array<string, mixed>|\WP\McpSchema\Client\Elicitation\DTO\UntitledMultiSelectEnumSchemaItems,
|
||||
* default?: array<string>|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['items']);
|
||||
|
||||
/** @var \WP\McpSchema\Client\Elicitation\DTO\UntitledMultiSelectEnumSchemaItems $items */
|
||||
$items = is_array($data['items'])
|
||||
? UntitledMultiSelectEnumSchemaItems::fromArray(self::asArray($data['items']))
|
||||
: $data['items'];
|
||||
|
||||
return new self(
|
||||
$items,
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asIntOrNull($data['minItems'] ?? null),
|
||||
self::asIntOrNull($data['maxItems'] ?? null),
|
||||
self::asStringArrayOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
if ($this->minItems !== null) {
|
||||
$result['minItems'] = $this->minItems;
|
||||
}
|
||||
if ($this->maxItems !== null) {
|
||||
$result['maxItems'] = $this->maxItems;
|
||||
}
|
||||
$result['items'] = $this->items->toArray();
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'array'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
*/
|
||||
public function getMinItems(): ?int
|
||||
{
|
||||
return $this->minItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|null
|
||||
*/
|
||||
public function getMaxItems(): ?int
|
||||
{
|
||||
return $this->maxItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Elicitation\DTO\UntitledMultiSelectEnumSchemaItems
|
||||
*/
|
||||
public function getItems(): UntitledMultiSelectEnumSchemaItems
|
||||
{
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>|null
|
||||
*/
|
||||
public function getDefault(): ?array
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Schema for the array items.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class UntitledMultiSelectEnumSchemaItems extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'string';
|
||||
|
||||
/**
|
||||
* @var 'string'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* Array of enum values to choose from.
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $enum;
|
||||
|
||||
/**
|
||||
* @param array<string> $enum
|
||||
*/
|
||||
public function __construct(
|
||||
array $enum
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->enum = $enum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'string',
|
||||
* enum: array<string>
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['enum']);
|
||||
|
||||
return new self(
|
||||
self::asStringArray($data['enum'])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
$result['enum'] = $this->enum;
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'string'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>
|
||||
*/
|
||||
public function getEnum(): array
|
||||
{
|
||||
return $this->enum;
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\SingleSelectEnumSchemaInterface;
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Schema for single-selection enumeration without display titles for options.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class UntitledSingleSelectEnumSchema extends AbstractDataTransferObject implements SingleSelectEnumSchemaInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const TYPE = 'string';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'type';
|
||||
public const DISCRIMINATOR_VALUE = 'string';
|
||||
|
||||
/**
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var 'string'
|
||||
*/
|
||||
protected string $type;
|
||||
|
||||
/**
|
||||
* Optional title for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $title;
|
||||
|
||||
/**
|
||||
* Optional description for the enum field.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $description;
|
||||
|
||||
/**
|
||||
* Array of enum values to choose from.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var array<string>
|
||||
*/
|
||||
protected array $enum;
|
||||
|
||||
/**
|
||||
* Optional default value.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $default;
|
||||
|
||||
/**
|
||||
* @param array<string> $enum @since 2025-11-25
|
||||
* @param string|null $title @since 2025-11-25
|
||||
* @param string|null $description @since 2025-11-25
|
||||
* @param string|null $default @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
array $enum,
|
||||
?string $title = null,
|
||||
?string $description = null,
|
||||
?string $default = null
|
||||
) {
|
||||
$this->type = self::TYPE;
|
||||
$this->enum = $enum;
|
||||
$this->title = $title;
|
||||
$this->description = $description;
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* type: 'string',
|
||||
* title?: string|null,
|
||||
* description?: string|null,
|
||||
* enum: array<string>,
|
||||
* default?: string|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['enum']);
|
||||
|
||||
return new self(
|
||||
self::asStringArray($data['enum']),
|
||||
self::asStringOrNull($data['title'] ?? null),
|
||||
self::asStringOrNull($data['description'] ?? null),
|
||||
self::asStringOrNull($data['default'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['type'] = $this->type;
|
||||
if ($this->title !== null) {
|
||||
$result['title'] = $this->title;
|
||||
}
|
||||
if ($this->description !== null) {
|
||||
$result['description'] = $this->description;
|
||||
}
|
||||
$result['enum'] = $this->enum;
|
||||
if ($this->default !== null) {
|
||||
$result['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return 'string'
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDescription(): ?string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string>
|
||||
*/
|
||||
public function getEnum(): array
|
||||
{
|
||||
return $this->enum;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getDefault(): ?string
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Factory;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\ElicitRequestParamsInterface;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\ElicitRequestFormParams;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\ElicitRequestURLParams;
|
||||
|
||||
/**
|
||||
* Factory for creating ElicitRequestParams union type instances.
|
||||
*
|
||||
* The parameters for a request to elicit additional information from the user via the client.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
final class ElicitRequestParamsFactory
|
||||
{
|
||||
/**
|
||||
* Registry mapping discriminator values to implementation classes.
|
||||
*
|
||||
* @var array<string, class-string<ElicitRequestParamsInterface>>
|
||||
*/
|
||||
public const REGISTRY = [
|
||||
'form' => ElicitRequestFormParams::class,
|
||||
'url' => ElicitRequestURLParams::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return ElicitRequestParamsInterface
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function fromArray(array $data): ElicitRequestParamsInterface
|
||||
{
|
||||
if (!isset($data['mode'])) {
|
||||
throw new \InvalidArgumentException('Missing discriminator field: mode');
|
||||
}
|
||||
|
||||
/** @var string $mode */
|
||||
$mode = $data['mode'];
|
||||
if (!isset(self::REGISTRY[$mode])) {
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"Unknown mode value '%s'. Valid values: %s",
|
||||
$mode,
|
||||
implode(', ', array_keys(self::REGISTRY))
|
||||
));
|
||||
}
|
||||
|
||||
$class = self::REGISTRY[$mode];
|
||||
return $class::fromArray($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a mode value is supported by this factory.
|
||||
*
|
||||
* @param string $mode
|
||||
* @return bool
|
||||
*/
|
||||
public static function supports(string $mode): bool
|
||||
{
|
||||
return isset(self::REGISTRY[$mode]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all supported mode values.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function modes(): array
|
||||
{
|
||||
return array_keys(self::REGISTRY);
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Factory;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\EnumSchemaInterface;
|
||||
use WP\McpSchema\Client\Elicitation\Factory\SingleSelectEnumSchemaFactory;
|
||||
use WP\McpSchema\Client\Elicitation\Factory\MultiSelectEnumSchemaFactory;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\LegacyTitledEnumSchema;
|
||||
|
||||
/**
|
||||
* Factory for creating EnumSchema union type instances.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
final class EnumSchemaFactory
|
||||
{
|
||||
/**
|
||||
* Registry mapping discriminator values to implementation classes.
|
||||
* Note: Some values route to other factories for nested union resolution.
|
||||
*
|
||||
* @var array<string, class-string>
|
||||
*/
|
||||
public const REGISTRY = [
|
||||
'array' => MultiSelectEnumSchemaFactory::class,
|
||||
'string' => LegacyTitledEnumSchema::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return EnumSchemaInterface
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function fromArray(array $data): EnumSchemaInterface
|
||||
{
|
||||
if (!isset($data['type'])) {
|
||||
throw new \InvalidArgumentException('Missing discriminator field: type');
|
||||
}
|
||||
|
||||
switch ($data['type']) {
|
||||
case 'array':
|
||||
return MultiSelectEnumSchemaFactory::fromArray($data);
|
||||
case 'string':
|
||||
if (isset($data['oneOf'])) {
|
||||
return SingleSelectEnumSchemaFactory::fromArray($data);
|
||||
}
|
||||
elseif (isset($data['enumNames'])) {
|
||||
return LegacyTitledEnumSchema::fromArray($data);
|
||||
}
|
||||
else {
|
||||
return LegacyTitledEnumSchema::fromArray($data);
|
||||
}
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"Unknown type value '%s'. Valid values: %s",
|
||||
is_scalar($data['type']) ? $data['type'] : gettype($data['type']),
|
||||
implode(', ', array_keys(self::REGISTRY))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a type value is supported by this factory.
|
||||
*
|
||||
* @param string $type
|
||||
* @return bool
|
||||
*/
|
||||
public static function supports(string $type): bool
|
||||
{
|
||||
return isset(self::REGISTRY[$type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all supported type values.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function types(): array
|
||||
{
|
||||
return array_keys(self::REGISTRY);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Factory;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\MultiSelectEnumSchemaInterface;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\UntitledMultiSelectEnumSchema;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\TitledMultiSelectEnumSchema;
|
||||
|
||||
/**
|
||||
* Factory for creating MultiSelectEnumSchema union type instances.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
final class MultiSelectEnumSchemaFactory
|
||||
{
|
||||
/**
|
||||
* Registry mapping discriminator values to implementation classes.
|
||||
*
|
||||
* @var array<string, class-string<MultiSelectEnumSchemaInterface>>
|
||||
*/
|
||||
public const REGISTRY = [
|
||||
'array' => UntitledMultiSelectEnumSchema::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return MultiSelectEnumSchemaInterface
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function fromArray(array $data): MultiSelectEnumSchemaInterface
|
||||
{
|
||||
if (!isset($data['type'])) {
|
||||
throw new \InvalidArgumentException('Missing discriminator field: type');
|
||||
}
|
||||
|
||||
switch ($data['type']) {
|
||||
case 'array':
|
||||
return UntitledMultiSelectEnumSchema::fromArray($data);
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"Unknown type value '%s'. Valid values: %s",
|
||||
is_scalar($data['type']) ? $data['type'] : gettype($data['type']),
|
||||
implode(', ', array_keys(self::REGISTRY))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a type value is supported by this factory.
|
||||
*
|
||||
* @param string $type
|
||||
* @return bool
|
||||
*/
|
||||
public static function supports(string $type): bool
|
||||
{
|
||||
return isset(self::REGISTRY[$type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all supported type values.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function types(): array
|
||||
{
|
||||
return array_keys(self::REGISTRY);
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Factory;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\PrimitiveSchemaDefinitionInterface;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\StringSchema;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\NumberSchema;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\BooleanSchema;
|
||||
use WP\McpSchema\Client\Elicitation\Factory\EnumSchemaFactory;
|
||||
|
||||
/**
|
||||
* Factory for creating PrimitiveSchemaDefinition union type instances.
|
||||
*
|
||||
* Restricted schema definitions that only allow primitive types
|
||||
* without nested objects or arrays.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
final class PrimitiveSchemaDefinitionFactory
|
||||
{
|
||||
/**
|
||||
* Registry mapping discriminator values to implementation classes.
|
||||
* Note: Some values route to other factories for nested union resolution.
|
||||
*
|
||||
* @var array<string, class-string>
|
||||
*/
|
||||
public const REGISTRY = [
|
||||
'number' => NumberSchema::class,
|
||||
'integer' => NumberSchema::class,
|
||||
'boolean' => BooleanSchema::class,
|
||||
'array' => EnumSchemaFactory::class,
|
||||
'string' => StringSchema::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return PrimitiveSchemaDefinitionInterface
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function fromArray(array $data): PrimitiveSchemaDefinitionInterface
|
||||
{
|
||||
if (!isset($data['type'])) {
|
||||
throw new \InvalidArgumentException('Missing discriminator field: type');
|
||||
}
|
||||
|
||||
switch ($data['type']) {
|
||||
case 'number':
|
||||
return NumberSchema::fromArray($data);
|
||||
case 'integer':
|
||||
return NumberSchema::fromArray($data);
|
||||
case 'boolean':
|
||||
return BooleanSchema::fromArray($data);
|
||||
case 'array':
|
||||
return EnumSchemaFactory::fromArray($data);
|
||||
case 'string':
|
||||
if (isset($data['minLength'])) {
|
||||
return StringSchema::fromArray($data);
|
||||
}
|
||||
elseif (isset($data['enum'])) {
|
||||
return EnumSchemaFactory::fromArray($data);
|
||||
}
|
||||
else {
|
||||
return StringSchema::fromArray($data);
|
||||
}
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"Unknown type value '%s'. Valid values: %s",
|
||||
is_scalar($data['type']) ? $data['type'] : gettype($data['type']),
|
||||
implode(', ', array_keys(self::REGISTRY))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a type value is supported by this factory.
|
||||
*
|
||||
* @param string $type
|
||||
* @return bool
|
||||
*/
|
||||
public static function supports(string $type): bool
|
||||
{
|
||||
return isset(self::REGISTRY[$type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all supported type values.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function types(): array
|
||||
{
|
||||
return array_keys(self::REGISTRY);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Factory;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\SingleSelectEnumSchemaInterface;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\UntitledSingleSelectEnumSchema;
|
||||
use WP\McpSchema\Client\Elicitation\DTO\TitledSingleSelectEnumSchema;
|
||||
|
||||
/**
|
||||
* Factory for creating SingleSelectEnumSchema union type instances.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
final class SingleSelectEnumSchemaFactory
|
||||
{
|
||||
/**
|
||||
* Registry mapping discriminator values to implementation classes.
|
||||
*
|
||||
* @var array<string, class-string<SingleSelectEnumSchemaInterface>>
|
||||
*/
|
||||
public const REGISTRY = [
|
||||
'string' => UntitledSingleSelectEnumSchema::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return SingleSelectEnumSchemaInterface
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function fromArray(array $data): SingleSelectEnumSchemaInterface
|
||||
{
|
||||
if (!isset($data['type'])) {
|
||||
throw new \InvalidArgumentException('Missing discriminator field: type');
|
||||
}
|
||||
|
||||
switch ($data['type']) {
|
||||
case 'string':
|
||||
if (isset($data['enum'])) {
|
||||
return UntitledSingleSelectEnumSchema::fromArray($data);
|
||||
}
|
||||
elseif (isset($data['oneOf'])) {
|
||||
return TitledSingleSelectEnumSchema::fromArray($data);
|
||||
}
|
||||
else {
|
||||
return UntitledSingleSelectEnumSchema::fromArray($data);
|
||||
}
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"Unknown type value '%s'. Valid values: %s",
|
||||
is_scalar($data['type']) ? $data['type'] : gettype($data['type']),
|
||||
implode(', ', array_keys(self::REGISTRY))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a type value is supported by this factory.
|
||||
*
|
||||
* @param string $type
|
||||
* @return bool
|
||||
*/
|
||||
public static function supports(string $type): bool
|
||||
{
|
||||
return isset(self::REGISTRY[$type]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all supported type values.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public static function types(): array
|
||||
{
|
||||
return array_keys(self::REGISTRY);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Union;
|
||||
|
||||
/**
|
||||
* The parameters for a request to elicit additional information from the user via the client.
|
||||
*
|
||||
* Union type members:
|
||||
* - ElicitRequestFormParams
|
||||
* - ElicitRequestURLParams
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
interface ElicitRequestParamsInterface
|
||||
{
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Union;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\PrimitiveSchemaDefinitionInterface;
|
||||
|
||||
/**
|
||||
* Union type members:
|
||||
* - SingleSelectEnumSchema
|
||||
* - MultiSelectEnumSchema
|
||||
* - LegacyTitledEnumSchema
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
interface EnumSchemaInterface extends PrimitiveSchemaDefinitionInterface
|
||||
{
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Union;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\EnumSchemaInterface;
|
||||
|
||||
/**
|
||||
* Union type members:
|
||||
* - UntitledMultiSelectEnumSchema
|
||||
* - TitledMultiSelectEnumSchema
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
interface MultiSelectEnumSchemaInterface extends EnumSchemaInterface
|
||||
{
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Union;
|
||||
|
||||
/**
|
||||
* Restricted schema definitions that only allow primitive types
|
||||
* without nested objects or arrays.
|
||||
*
|
||||
* Union type members:
|
||||
* - StringSchema
|
||||
* - NumberSchema
|
||||
* - BooleanSchema
|
||||
* - EnumSchema
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
interface PrimitiveSchemaDefinitionInterface
|
||||
{
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Elicitation\Union;
|
||||
|
||||
use WP\McpSchema\Client\Elicitation\Union\EnumSchemaInterface;
|
||||
|
||||
/**
|
||||
* Union type members:
|
||||
* - UntitledSingleSelectEnumSchema
|
||||
* - TitledSingleSelectEnumSchema
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Elicitation
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
interface SingleSelectEnumSchemaInterface extends EnumSchemaInterface
|
||||
{
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Lifecycle\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
* @last-updated 2025-11-25 (added properties: tasks)
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Lifecycle
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ClientCapabilities extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Experimental, non-standard capabilities that the client supports.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
*
|
||||
* @var array<string, object>|null
|
||||
*/
|
||||
protected ?array $experimental;
|
||||
|
||||
/**
|
||||
* Present if the client supports listing roots.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
*
|
||||
* @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesRoots|null
|
||||
*/
|
||||
protected ?ClientCapabilitiesRoots $roots;
|
||||
|
||||
/**
|
||||
* Present if the client supports sampling from an LLM.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
*
|
||||
* @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesSampling|null
|
||||
*/
|
||||
protected ?ClientCapabilitiesSampling $sampling;
|
||||
|
||||
/**
|
||||
* Present if the client supports elicitation from the server.
|
||||
*
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesElicitation|null
|
||||
*/
|
||||
protected ?ClientCapabilitiesElicitation $elicitation;
|
||||
|
||||
/**
|
||||
* Present if the client supports task-augmented requests.
|
||||
*
|
||||
* @since 2025-11-25
|
||||
*
|
||||
* @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesTasks|null
|
||||
*/
|
||||
protected ?ClientCapabilitiesTasks $tasks;
|
||||
|
||||
/**
|
||||
* @param array<string, object>|null $experimental @since 2024-11-05
|
||||
* @param \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesRoots|null $roots @since 2024-11-05
|
||||
* @param \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesSampling|null $sampling @since 2024-11-05
|
||||
* @param \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesElicitation|null $elicitation @since 2025-06-18
|
||||
* @param \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesTasks|null $tasks @since 2025-11-25
|
||||
*/
|
||||
public function __construct(
|
||||
?array $experimental = null,
|
||||
?ClientCapabilitiesRoots $roots = null,
|
||||
?ClientCapabilitiesSampling $sampling = null,
|
||||
?ClientCapabilitiesElicitation $elicitation = null,
|
||||
?ClientCapabilitiesTasks $tasks = null
|
||||
) {
|
||||
$this->experimental = $experimental;
|
||||
$this->roots = $roots;
|
||||
$this->sampling = $sampling;
|
||||
$this->elicitation = $elicitation;
|
||||
$this->tasks = $tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* experimental?: array<string, object>|null,
|
||||
* roots?: array<string, mixed>|\WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesRoots|null,
|
||||
* sampling?: array<string, mixed>|\WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesSampling|null,
|
||||
* elicitation?: array<string, mixed>|\WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesElicitation|null,
|
||||
* tasks?: array<string, mixed>|\WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesTasks|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
/** @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesRoots|null $roots */
|
||||
$roots = isset($data['roots'])
|
||||
? (is_array($data['roots'])
|
||||
? ClientCapabilitiesRoots::fromArray(self::asArray($data['roots']))
|
||||
: $data['roots'])
|
||||
: null;
|
||||
|
||||
/** @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesSampling|null $sampling */
|
||||
$sampling = isset($data['sampling'])
|
||||
? (is_array($data['sampling'])
|
||||
? ClientCapabilitiesSampling::fromArray(self::asArray($data['sampling']))
|
||||
: $data['sampling'])
|
||||
: null;
|
||||
|
||||
/** @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesElicitation|null $elicitation */
|
||||
$elicitation = isset($data['elicitation'])
|
||||
? (is_array($data['elicitation'])
|
||||
? ClientCapabilitiesElicitation::fromArray(self::asArray($data['elicitation']))
|
||||
: $data['elicitation'])
|
||||
: null;
|
||||
|
||||
/** @var \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesTasks|null $tasks */
|
||||
$tasks = isset($data['tasks'])
|
||||
? (is_array($data['tasks'])
|
||||
? ClientCapabilitiesTasks::fromArray(self::asArray($data['tasks']))
|
||||
: $data['tasks'])
|
||||
: null;
|
||||
|
||||
return new self(
|
||||
self::asObjectMapOrNull($data['experimental'] ?? null),
|
||||
$roots,
|
||||
$sampling,
|
||||
$elicitation,
|
||||
$tasks
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($this->experimental !== null) {
|
||||
$result['experimental'] = $this->experimental;
|
||||
}
|
||||
if ($this->roots !== null) {
|
||||
$result['roots'] = $this->roots->toArray();
|
||||
}
|
||||
if ($this->sampling !== null) {
|
||||
$result['sampling'] = $this->sampling->toArray();
|
||||
}
|
||||
if ($this->elicitation !== null) {
|
||||
$result['elicitation'] = $this->elicitation->toArray();
|
||||
}
|
||||
if ($this->tasks !== null) {
|
||||
$result['tasks'] = $this->tasks->toArray();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, object>|null
|
||||
*/
|
||||
public function getExperimental(): ?array
|
||||
{
|
||||
return $this->experimental;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesRoots|null
|
||||
*/
|
||||
public function getRoots(): ?ClientCapabilitiesRoots
|
||||
{
|
||||
return $this->roots;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesSampling|null
|
||||
*/
|
||||
public function getSampling(): ?ClientCapabilitiesSampling
|
||||
{
|
||||
return $this->sampling;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesElicitation|null
|
||||
*/
|
||||
public function getElicitation(): ?ClientCapabilitiesElicitation
|
||||
{
|
||||
return $this->elicitation;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Client\Lifecycle\DTO\ClientCapabilitiesTasks|null
|
||||
*/
|
||||
public function getTasks(): ?ClientCapabilitiesTasks
|
||||
{
|
||||
return $this->tasks;
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Lifecycle\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Present if the client supports elicitation from the server.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Lifecycle
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ClientCapabilitiesElicitation extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* @var object|null
|
||||
*/
|
||||
protected ?object $form;
|
||||
|
||||
/**
|
||||
* @var object|null
|
||||
*/
|
||||
protected ?object $url;
|
||||
|
||||
/**
|
||||
* @param object|null $form
|
||||
* @param object|null $url
|
||||
*/
|
||||
public function __construct(
|
||||
?object $form = null,
|
||||
?object $url = null
|
||||
) {
|
||||
$this->form = $form;
|
||||
$this->url = $url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* form?: object|null,
|
||||
* url?: object|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
self::asObjectOrNull($data['form'] ?? null),
|
||||
self::asObjectOrNull($data['url'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($this->form !== null) {
|
||||
$result['form'] = $this->form;
|
||||
}
|
||||
if ($this->url !== null) {
|
||||
$result['url'] = $this->url;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return object|null
|
||||
*/
|
||||
public function getForm(): ?object
|
||||
{
|
||||
return $this->form;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return object|null
|
||||
*/
|
||||
public function getUrl(): ?object
|
||||
{
|
||||
return $this->url;
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Lifecycle\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Present if the client supports listing roots.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Lifecycle
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ClientCapabilitiesRoots extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Whether the client supports notifications for changes to the roots list.
|
||||
*
|
||||
* @var bool|null
|
||||
*/
|
||||
protected ?bool $listChanged;
|
||||
|
||||
/**
|
||||
* @param bool|null $listChanged
|
||||
*/
|
||||
public function __construct(
|
||||
?bool $listChanged = null
|
||||
) {
|
||||
$this->listChanged = $listChanged;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* listChanged?: bool|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
self::asBoolOrNull($data['listChanged'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($this->listChanged !== null) {
|
||||
$result['listChanged'] = $this->listChanged;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool|null
|
||||
*/
|
||||
public function getListChanged(): ?bool
|
||||
{
|
||||
return $this->listChanged;
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Lifecycle\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Present if the client supports sampling from an LLM.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Lifecycle
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ClientCapabilitiesSampling extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Whether the client supports context inclusion via includeContext parameter. If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
|
||||
*
|
||||
* @var object|null
|
||||
*/
|
||||
protected ?object $context;
|
||||
|
||||
/**
|
||||
* Whether the client supports tool use via tools and toolChoice parameters.
|
||||
*
|
||||
* @var object|null
|
||||
*/
|
||||
protected ?object $tools;
|
||||
|
||||
/**
|
||||
* @param object|null $context
|
||||
* @param object|null $tools
|
||||
*/
|
||||
public function __construct(
|
||||
?object $context = null,
|
||||
?object $tools = null
|
||||
) {
|
||||
$this->context = $context;
|
||||
$this->tools = $tools;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* context?: object|null,
|
||||
* tools?: object|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
self::asObjectOrNull($data['context'] ?? null),
|
||||
self::asObjectOrNull($data['tools'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($this->context !== null) {
|
||||
$result['context'] = $this->context;
|
||||
}
|
||||
if ($this->tools !== null) {
|
||||
$result['tools'] = $this->tools;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return object|null
|
||||
*/
|
||||
public function getContext(): ?object
|
||||
{
|
||||
return $this->context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return object|null
|
||||
*/
|
||||
public function getTools(): ?object
|
||||
{
|
||||
return $this->tools;
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Lifecycle\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Present if the client supports task-augmented requests.
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Lifecycle
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ClientCapabilitiesTasks extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Whether this client supports tasks/list.
|
||||
*
|
||||
* @var object|null
|
||||
*/
|
||||
protected ?object $list;
|
||||
|
||||
/**
|
||||
* Whether this client supports tasks/cancel.
|
||||
*
|
||||
* @var object|null
|
||||
*/
|
||||
protected ?object $cancel;
|
||||
|
||||
/**
|
||||
* @param object|null $list
|
||||
* @param object|null $cancel
|
||||
*/
|
||||
public function __construct(
|
||||
?object $list = null,
|
||||
?object $cancel = null
|
||||
) {
|
||||
$this->list = $list;
|
||||
$this->cancel = $cancel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* list?: object|null,
|
||||
* cancel?: object|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
return new self(
|
||||
self::asObjectOrNull($data['list'] ?? null),
|
||||
self::asObjectOrNull($data['cancel'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($this->list !== null) {
|
||||
$result['list'] = $this->list;
|
||||
}
|
||||
if ($this->cancel !== null) {
|
||||
$result['cancel'] = $this->cancel;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return object|null
|
||||
*/
|
||||
public function getList(): ?object
|
||||
{
|
||||
return $this->list;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return object|null
|
||||
*/
|
||||
public function getCancel(): ?object
|
||||
{
|
||||
return $this->cancel;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Lifecycle\Union;
|
||||
|
||||
/**
|
||||
* Union type members:
|
||||
* - EmptyResult
|
||||
* - CreateMessageResult
|
||||
* - ListRootsResult
|
||||
* - ElicitResult
|
||||
* - GetTaskResult
|
||||
* - GetTaskPayloadResult
|
||||
* - ListTasksResult
|
||||
* - CancelTaskResult
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Lifecycle
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
interface ClientResultInterface
|
||||
{
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array;
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Roots\DTO;
|
||||
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\JSONRPCRequest;
|
||||
use WP\McpSchema\Common\JsonRpc\DTO\RequestParams;
|
||||
use WP\McpSchema\Common\Protocol\Union\ServerRequestInterface;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Sent from the server to request a list of root URIs from the client. Roots allow
|
||||
* servers to ask for specific directories or files to operate on. A common example
|
||||
* for roots is providing a set of repositories or directories a server should operate
|
||||
* on.
|
||||
*
|
||||
* This request is typically used when the server needs to understand the file system
|
||||
* structure or access specific locations that the client has permission to read from.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
* @last-updated 2025-11-25 (modified property: params)
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Roots
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ListRootsRequest extends JSONRPCRequest implements ServerRequestInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
public const METHOD = 'roots/list';
|
||||
|
||||
public const DISCRIMINATOR_FIELD = 'method';
|
||||
public const DISCRIMINATOR_VALUE = 'roots/list';
|
||||
|
||||
/**
|
||||
* @var \WP\McpSchema\Common\JsonRpc\DTO\RequestParams|null
|
||||
*/
|
||||
protected ?RequestParams $typedParams;
|
||||
|
||||
/**
|
||||
* @param '2.0' $jsonrpc @since 2025-11-25
|
||||
* @param string|number $id @since 2025-11-25
|
||||
* @param \WP\McpSchema\Common\JsonRpc\DTO\RequestParams|null $params @since 2024-11-05
|
||||
*/
|
||||
public function __construct(
|
||||
string $jsonrpc,
|
||||
$id,
|
||||
?RequestParams $params = null
|
||||
) {
|
||||
parent::__construct(self::METHOD, $jsonrpc, $id, null);
|
||||
$this->typedParams = $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* jsonrpc: '2.0',
|
||||
* id: string|number,
|
||||
* method: 'roots/list',
|
||||
* params?: array<string, mixed>|\WP\McpSchema\Common\JsonRpc\DTO\RequestParams|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['jsonrpc', 'id']);
|
||||
|
||||
/** @var '2.0' $jsonrpc */
|
||||
$jsonrpc = self::asString($data['jsonrpc']);
|
||||
|
||||
/** @var string|number $id */
|
||||
$id = self::asStringOrNumber($data['id']);
|
||||
|
||||
/** @var \WP\McpSchema\Common\JsonRpc\DTO\RequestParams|null $params */
|
||||
$params = isset($data['params'])
|
||||
? (is_array($data['params'])
|
||||
? RequestParams::fromArray(self::asArray($data['params']))
|
||||
: $data['params'])
|
||||
: null;
|
||||
|
||||
return new self(
|
||||
$jsonrpc,
|
||||
$id,
|
||||
$params
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = parent::toArray();
|
||||
|
||||
if ($this->typedParams !== null) {
|
||||
$result['params'] = $this->typedParams->toArray();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \WP\McpSchema\Common\JsonRpc\DTO\RequestParams|null
|
||||
*/
|
||||
public function getTypedParams(): ?RequestParams
|
||||
{
|
||||
return $this->typedParams;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Roots\DTO;
|
||||
|
||||
use WP\McpSchema\Client\Lifecycle\Union\ClientResultInterface;
|
||||
use WP\McpSchema\Common\Protocol\DTO\Result;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* The client's response to a roots/list request from the server.
|
||||
* This result contains an array of Root objects, each representing a root directory
|
||||
* or file that the server can operate on.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
* @last-updated 2025-11-25 (modified property: roots)
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Roots
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class ListRootsResult extends Result implements ClientResultInterface
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Wire keys this class models. Anything else is kept in $additionalProperties.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const KNOWN_KEYS = ['_meta', 'roots'];
|
||||
|
||||
/**
|
||||
* @since 2024-11-05
|
||||
*
|
||||
* @var array<\WP\McpSchema\Client\Roots\DTO\Root>
|
||||
*/
|
||||
protected array $roots;
|
||||
|
||||
/**
|
||||
* @param array<\WP\McpSchema\Client\Roots\DTO\Root> $roots @since 2024-11-05
|
||||
* @param array<string, mixed>|null $_meta @since 2024-11-05
|
||||
* @param array<string, mixed>|null $additionalProperties
|
||||
*/
|
||||
public function __construct(
|
||||
array $roots,
|
||||
?array $_meta = null,
|
||||
?array $additionalProperties = null
|
||||
) {
|
||||
parent::__construct($_meta, $additionalProperties);
|
||||
$this->roots = $roots;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* _meta?: array<string, mixed>|null,
|
||||
* roots: array<array<string, mixed>|\WP\McpSchema\Client\Roots\DTO\Root>
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['roots']);
|
||||
|
||||
/** @var array<\WP\McpSchema\Client\Roots\DTO\Root> $roots */
|
||||
$roots = array_map(
|
||||
static fn($item) => is_array($item)
|
||||
? Root::fromArray($item)
|
||||
: $item,
|
||||
self::asArray($data['roots'])
|
||||
);
|
||||
|
||||
return new self(
|
||||
$roots,
|
||||
self::asArrayOrNull($data['_meta'] ?? null),
|
||||
self::additionalFields($data, self::KNOWN_KEYS)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = parent::toArray();
|
||||
|
||||
$result['roots'] = array_map(static fn($item) => $item->toArray(), $this->roots);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<\WP\McpSchema\Client\Roots\DTO\Root>
|
||||
*/
|
||||
public function getRoots(): array
|
||||
{
|
||||
return $this->roots;
|
||||
}
|
||||
}
|
||||
Vendored
+135
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace WP\McpSchema\Client\Roots\DTO;
|
||||
|
||||
use WP\McpSchema\Common\AbstractDataTransferObject;
|
||||
use WP\McpSchema\Common\Traits\ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* Represents a root directory or file that the server can operate on.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
* @last-updated 2025-06-18 (added properties: _meta)
|
||||
*
|
||||
* @mcp-domain Client
|
||||
* @mcp-subdomain Roots
|
||||
* @mcp-version 2025-11-25
|
||||
*/
|
||||
class Root extends AbstractDataTransferObject
|
||||
{
|
||||
use ValidatesRequiredFields;
|
||||
|
||||
/**
|
||||
* The URI identifying the root. This *must* start with file:// for now.
|
||||
* This restriction may be relaxed in future versions of the protocol to allow
|
||||
* other URI schemes.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $uri;
|
||||
|
||||
/**
|
||||
* An optional name for the root. This can be used to provide a human-readable
|
||||
* identifier for the root, which may be useful for display purposes or for
|
||||
* referencing the root in other parts of the application.
|
||||
*
|
||||
* @since 2024-11-05
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected ?string $name;
|
||||
|
||||
/**
|
||||
* See [General fields: `_meta`](/specification/2025-11-25/basic/index#meta) for notes on `_meta` usage.
|
||||
*
|
||||
* @since 2025-06-18
|
||||
*
|
||||
* @var array<string, mixed>|null
|
||||
*/
|
||||
protected ?array $_meta;
|
||||
|
||||
/**
|
||||
* @param string $uri @since 2024-11-05
|
||||
* @param string|null $name @since 2024-11-05
|
||||
* @param array<string, mixed>|null $_meta @since 2025-06-18
|
||||
*/
|
||||
public function __construct(
|
||||
string $uri,
|
||||
?string $name = null,
|
||||
?array $_meta = null
|
||||
) {
|
||||
$this->uri = $uri;
|
||||
$this->name = $name;
|
||||
$this->_meta = $_meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance from an array.
|
||||
*
|
||||
* @param array{
|
||||
* uri: string,
|
||||
* name?: string|null,
|
||||
* _meta?: array<string, mixed>|null
|
||||
* } $data
|
||||
* @phpstan-param array<string, mixed> $data
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::assertRequired($data, ['uri']);
|
||||
|
||||
return new self(
|
||||
self::asString($data['uri']),
|
||||
self::asStringOrNull($data['name'] ?? null),
|
||||
self::asArrayOrNull($data['_meta'] ?? null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the instance to an array.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
$result['uri'] = $this->uri;
|
||||
if ($this->name !== null) {
|
||||
$result['name'] = $this->name;
|
||||
}
|
||||
if ($this->_meta !== null) {
|
||||
$result['_meta'] = $this->_meta;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getUri(): string
|
||||
{
|
||||
return $this->uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function get_meta(): ?array
|
||||
{
|
||||
return $this->_meta;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user