PHP MCP模式
PHP表示 模型上下文协议(MCP) 模式类型。
此包提供了数据传输对象(DTO)、枚举和联合,它们反映了官方的MCP TypeScript模式。 它是 不 SDK、客户端或服务器实现; 在PHP中构建自己的MCP兼容应用程序的类型定义。
安装
composer require wordpress/php-mcp-schema需要PHP 7.4或更高版本。
用法
创建工具定义
use WP\McpSchema\Server\Tools\DTO\Tool;
$tool = Tool::fromArray([
'name' => 'get_weather',
'description' => 'Get current weather for a location',
'inputSchema' => [
'type' => 'object',
'properties' => [
'location' => ['type' => 'string', 'description' => 'City name'],
],
'required' => ['location'],
],
]);序列化(toArray)
将DTO转换为JSON编码的纯数组:
use WP\McpSchema\Server\Tools\DTO\Tool;
$tool = Tool::fromArray([
'name' => 'get_weather',
'description' => 'Get current weather for a location',
'inputSchema' => ['type' => 'object', 'properties' => []],
]);
$array = $tool->toArray();
$json = json_encode($array); // Ready to send over the wire反序列化(from Array)
将传入的JSON解码为完全类型的DTO:
use WP\McpSchema\Server\Tools\DTO\CallToolRequest;
$json = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_weather","arguments":{"location":"Paris"}}}';
$data = json_decode($json, true);
$request = CallToolRequest::fromArray($data);
$tool_name = $request->getTypedParams()->getName(); // "get_weather"
$arguments = $request->getTypedParams()->getArguments(); // ['location' => 'Paris']工厂/工会类型
使用工厂来解析多态内容块,而无需预先知道具体类型:
use WP\McpSchema\Common\Protocol\Factory\ContentBlockFactory;
use WP\McpSchema\Common\Content\DTO\TextContent;
$block = ContentBlockFactory::fromArray(['type' => 'text', 'text' => 'Hello, world!']);
// $block implements ContentBlockInterface; cast when you need the concrete API
if ($block instanceof TextContent) {
echo $block->getText(); // "Hello, world!"
}JSON-RPC消息
为任何MCP方法构造一个通用JSON-RPC请求:
use WP\McpSchema\Common\JsonRpc\DTO\JSONRPCRequest;
$request = JSONRPCRequest::fromArray([
'jsonrpc' => '2.0',
'id' => 1,
'method' => 'tools/list',
]);
$json = json_encode($request->toArray());可用类型
服务器类型(WP\McpSchema\Server\)
- 工具 -
Tool,CallToolRequest,CallToolResult,ListToolsRequest,ListToolsResult - 资源 -
Resource,ResourceTemplate,ReadResourceRequest,ReadResourceResult - 提示 -
Prompt,PromptMessage,GetPromptRequest,GetPromptResult - 日志记录 -
LoggingMessageNotification,SetLevelRequest
客户类型(WP\McpSchema\Client\)
- 采样 -
CreateMessageRequest,CreateMessageResult,SamplingMessage - 引出 -
ElicitRequest,ElicitResult - 根 -
ListRootsRequest,ListRootsResult,Root
常见类型(WP\McpSchema\Common\)
- 协议 -
InitializeRequest,InitializeResult,PingRequest - 内容 -
TextContent,ImageContent,AudioContent - JSON-RPC -
JSONRPCRequest,JSONRPCNotification,JSONRPCResultResponse,JSONRPCErrorResponse
发电机
PHP代码在 src/ 是从官方的MCP TypeScript模式自动生成的。发电机位于 generator/ 目录,并且不包含在Composer包中。
看 生成器/README.md 有关设置和使用说明。
许可证
GPL-2.0或更高版本-请参阅 许可证.md 了解详情。
链接
-
