关于 PHP Model Context Protocol Server SDK
用于构建 PHP MCP 服务的 SDK,可向大模型提供工具和资源。支持标准输入输出与 HTTP 传输,并可通过 PHP 属性定义服务能力。
主要功能
- 01构建 MCP 服务
- 02提供工具和资源
- 03支持 STDIO 与 HTTP 传输
- 04处理 JSON-RPC 请求
- 05基于属性定义能力
适用场景
- 01通过 STDIO 构建本地 MCP 服务
- 02通过 HTTP 响应 MCP 请求
- 03使用 PHP 属性定义工具和资源
MCP 相关
它实现 MCP 服务端,支持通过 STDIO 或 HTTP 向 MCP 客户端提供工具和资源。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
PHP Model Context Protocol 服务端 SDK
本项目提供 Model Context Protocol(MCP)的 PHP 实现,让你能够构建可向大模型(LLM)提供上下文(数据和工具)的服务端。
MCP 是一种开放协议,用于规范应用与大模型的交互方式。如需了解更多 MCP 信息,请访问官方网站:https://modelcontextprotocol.io
功能
此 PHP MCP SDK 提供以下核心功能:
- 服务端实现:轻松创建符合 MCP 规范的服务端。
- 功能:
Tools:向大模型公开可供其执行的功能。Resources:向大模型提供数据和内容。
- 传输方式:
StdioTransport:用于基于命令行的 MCP 服务端。HttpTransport:通过 HTTP 公开 MCP 服务端(兼容标准 PHP Web 服务端环境,例如使用 PHP-FPM/mod_php 的 Apache/Nginx)。
- JSON-RPC 处理:负责解析请求并格式化响应。
- 基于属性的配置:使用 PHP 属性定义工具、资源及其参数。
快速开始
本指南将介绍如何使用此 SDK 创建简单的 MCP 服务端。
前置条件
- PHP 8.1 或更高版本
- 用于依赖管理的 Composer
安装
使用 Composer 安装依赖:
composer require james2037/mcp-php-server
创建 STDIO 服务端
STDIO 服务端通过标准输入和标准输出进行通信,常用于本地工具或开发用途。
以下示例展示了一个包含以下内容的服务端:
- 一个
EchoTool:接收字符串并返回该字符串。 - 一个
GreetingResource:提供静态问候消息。
此示例的完整代码请参见 examples/stdio_server.php。
examples/stdio_server.php 的关键部分:
<?php
// Autoload dependencies
require_once __DIR__ . '/../vendor/autoload.php';
// Required MCP SDK classes
use MCP\Server\Server;
use MCP\Server\Transport\StdioTransport;
use MCP\Server\Capability\ToolsCapability;
use MCP\Server\Capability\ResourcesCapability;
// For defining the tool
use MCP\Server\Tool\Tool as BaseTool;
use MCP\Server\Tool\Attribute\Tool as ToolAttribute;
use MCP\Server\Tool\Attribute\Parameter;
// For defining the resource
use MCP\Server\Resource\Resource as BaseResource;
use MCP\Server\Resource\Attribute\ResourceUri;
use MCP\Server\Resource\ResourceContents;
// 1. Define a Tool
#[ToolAttribute(name: "echo", description: "Echoes back the provided message.")]
class EchoTool extends BaseTool
{
protected function doExecute(array $arguments): array {
// Access parameters from the $arguments array
$message = $arguments['message'] ?? 'Default message if not provided';
return [$this->createTextContent("Echo: " . $message)];
}
}
// 2. Define a Resource
#[ResourceUri(uri: "greeting://welcome", description: "Provides a welcome greeting.")]
class GreetingResource extends BaseResource
{
public function __construct()
{
parent::__construct("Welcome Greeting", "text/plain");
}
public function read(array $parameters = []): ResourceContents
{
return $this->text("Hello from your MCP server!");
}
}
// 3. Instantiate the Server
$server = new Server('MySimpleServer (STDIO)', '1.0.0');
// 4. Setup and Add Tools Capability
$toolsCapability = new ToolsCapability();
$toolsCapability->addTool(new EchoTool());
$server->addCapability($toolsCapability);
// 5. Setup and Add Resources Capability
$resourcesCapability = new ResourcesCapability();
$resourcesCapability->addResource(new GreetingResource());
$server->addCapability($resourcesCapability);
// 6. Connect StdioTransport
$transport = new StdioTransport();
$server->connect($transport);
// 7. Run the Server
fwrite(STDERR, "STDIO Server listening...\n"); // Optional: message to stderr
$server->run();
(注意:EchoTool::doExecute 方法使用 array $arguments 作为参数。这是因为基类 Tool 会将所有参数作为关联数组传递给此方法。随后,你的工具逻辑应从该数组中获取特定参数,例如 $arguments['message']。)
运行 STDIO 服务端:
在终端中执行脚本:
php examples/stdio_server.php
服务端将通过标准输入接收 JSON-RPC 消息。
创建 HTTP 服务端
你也可以使用 HttpTransport 通过 HTTP 公开 MCP 服务端。此示例使用相同的 EchoTool 和 GreetingResource。
此示例的完整代码位于 examples/http_server.php。此脚本需要 PSR-7 和 PSR-17 HTTP 消息实现(例如 nyholm/psr7 和 nyholm/psr7-server,它们已包含在 composer.json 中)。
examples/http_server.php 的关键部分:
<?php
// Autoload dependencies
require_once __DIR__ . '/../vendor/autoload.php';
// Required MCP SDK classes & PSR implementations
use MCP\Server\Server;
use MCP\Server\Transport\HttpTransport;
use MCP\Server\Capability\ToolsCapability;
use MCP\Server\Capability\ResourcesCapability;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7Server\ServerRequestCreator;
// Tool and Resource definitions (e.g., EchoTool, GreetingResource)
// would be included here, same as in the STDIO example.
// For brevity, they are omitted from this snippet but are in the actual file.
// --- Assume EchoTool is defined as in the STDIO example ---
use MCP\Server\Tool\Tool as BaseTool;
use MCP\Server\Tool\Attribute\Tool as ToolAttribute;
// Parameter attribute is on the actual class, not repeated in every snippet.
// use MCP\Server\Tool\Attribute\Parameter;
#[ToolAttribute(name: "echo", description: "Echoes back the provided message.")]
class EchoTool extends BaseTool {
protected function doExecute(array $arguments): array { // Changed signature
$message = $arguments['message'] ?? 'Default message if not provided'; // Added logic
return [$this->createTextContent("Echo: " . $message)];
}
}
// --- Assume GreetingResource is defined as in the STDIO example ---
use MCP\Server\Resource\Resource as BaseResource;
use MCP\Server\Resource\Attribute\ResourceUri;
use MCP\Server\Resource\ResourceContents;
#[ResourceUri(uri: "greeting://welcome", description: "Provides a welcome greeting.")]
class GreetingResource extends BaseResource {
public function __construct() { parent::__construct("Welcome Greeting", "text/plain"); }
public function read(array $parameters = []): ResourceContents {
return $this->text("Hello from your MCP server!");
}
}
// 1. Create PSR-7 request and factories
$psr17Factory = new Psr17Factory();
$requestCreator = new ServerRequestCreator(
$psr17Factory, // ServerRequestFactory
$psr17Factory, // UriFactory
$psr17Factory, // UploadedFileFactory
$psr17Factory // StreamFactory
);
$request = $requestCreator->fromGlobals();
// 2. Instantiate the Server
$server = new Server('MySimpleServer (HTTP)', '1.0.0');
// 3. Setup and Add Capabilities (Tools, Resources)
// Similar to STDIO example:
$toolsCapability = new ToolsCapability();
$toolsCapability->addTool(new EchoTool());
$server->addCapability($toolsCapability);
$resourcesCapability = new ResourcesCapability();
$resourcesCapability->addResource(new GreetingResource());
$server->addCapability($resourcesCapability);
// 4. Instantiate and connect HttpTransport
$transport = new HttpTransport($request, $psr17Factory, $psr17Factory);
$server->connect($transport);
// 5. Run the Server
// For HTTP, run() processes the current request and sends the response.
$server->run();
运行 HTTP 服务端:
开发时可使用 PHP 内置 Web 服务端:
php -S localhost:8000 examples/http_server.php
然后,使用 curl 等 HTTP 客户端发送 MCP 请求。
echo 工具的 curl 请求示例:
curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","method":"tools/call","params":{"name":"echo","arguments":{"message":"Hello HTTP"}},"id":1}' http://localhost:8000/
预期的 JSON-RPC 响应:
{"jsonrpc":"2.0","result":{"content":[{"type":"text","text":"Echo: Hello HTTP"}],"isError":false},"id":1}
使用 PHP-FPM 或 mod_php
examples/http_server.php 脚本旨在兼容常见的 PHP Web 服务器配置,例如使用 PHP-FPM 或 mod_php 的 Apache 或 Nginx。
要点:
- 处理单个请求: 该脚本,尤其是
(new HttpTransport(...))->run(),会处理单个 HTTP 请求,然后退出。这种模式与 PHP-FPM 和mod_php处理 PHP 请求的方式完美契合。每个路由到此脚本的 Web 服务器传入 HTTP 请求都会触发一次全新的执行。 - PSR-7
fromGlobals(): 使用ServerRequestCreator::fromGlobals(),可根据 PHP 的全局变量(例如$_SERVER、$_POST)正确填充 PSR-7 请求对象,这些变量由 Web 服务器填充。 - 输出处理: SDK 的
HttpTransport在内部使用 SAPI 发射器(例如Laminas\HttpHandlerRunner\Emitter\SapiEmitter),可正确地将标头和正文内容发送到 Web 服务器,再由其传输给客户端。
Web 服务器配置示例:
你需要配置 Web 服务器(例如 Nginx 或 Apache),将请求传递给 http_server.php 脚本。
-
Nginx 示例(概念性):
server { listen 80; server_name your-mcp-server.example.com; root /path/to/your/project/examples; # Or wherever http_server.php is location / { try_files $uri /http_server.php$is_args$args; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # Adjust to your PHP-FPM version/socket fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } -
Apache 示例(概念性;如果启用了
AllowOverride,可在examples目录中使用.htaccess):RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ http_server.php [L,QSA]确保已启用
mod_rewrite。还需要配置 Apache VirtualHost,以便执行 PHP 脚本。
运行服务:
与 php -S localhost:8000 examples/http_server.php 命令(运行 PHP 内置开发服务器)不同,在 PHP-FPM/mod_php 配置中,由主 Web 服务器(Nginx/Apache)负责接收请求并将其传递给 PHP 解释器。你无需像启动内置服务器那样运行单独的 PHP 命令来“启动”服务。
前面用于测试 HTTP 服务的 curl 命令保持不变,目标 URL 应为 Web 服务器中配置的地址(例如 http://your-mcp-server.example.com/)。
更多信息
如需详细了解 MCP 概念、功能和高级用法,请参阅源代码和官方的 Model Context Protocol 文档。
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。