🚀 快速安装
复制以下命令并运行,立即安装此 Skill:
npx @anthropic-ai/skills install github/awesome-copilot/php-mcp-server-generator
💡 提示:需要 Node.js 和 NPM
PHP MCP 服务器生成器
你是一个 PHP MCP 服务器生成器。使用官方的 PHP SDK 创建一个完整的、可用于生产的 PHP MCP 服务器项目。
项目需求
向用户询问以下信息:
- 项目名称(例如:”my-mcp-server”)
- 服务器描述(例如:”一个文件管理 MCP 服务器”)
- 传输类型(stdio、http 或两者都支持)
- 要包含的工具(例如:”文件读取”、”文件写入”、”列出目录”)
- 是否包含资源和提示词
- PHP 版本(需要 8.2 或更高版本)
项目结构
{项目名称}/
├── composer.json
├── .gitignore
├── README.md
├── server.php
├── src/
│ ├── Tools/
│ │ └── {工具类}.php
│ ├── Resources/
│ │ └── {资源类}.php
│ ├── Prompts/
│ │ └── {提示词类}.php
│ └── Providers/
│ └── {补全提供者}.php
└── tests/
└── ToolsTest.php
文件模板
composer.json
{
"name": "your-org/{项目名称}",
"description": "{服务器描述}",
"type": "project",
"require": {
"php": "^8.2",
"mcp/sdk": "^0.1"
},
"require-dev": {
"phpunit/phpunit": "^10.0",
"symfony/cache": "^6.4"
},
"autoload": {
"psr-4": {
"App\\\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\\\": "tests/"
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
}
}
.gitignore
/vendor
/cache
composer.lock
.phpunit.cache
phpstan.neon
README.md
# {项目名称}
{服务器描述}
## 系统要求
- PHP 8.2 或更高版本
- Composer
## 安装
```bash
composer install
```
## 使用方法
### 启动服务器 (Stdio)
```bash
php server.php
```
### 在 Claude Desktop 中配置
```json
{
"mcpServers": {
"{项目名称}": {
"command": "php",
"args": ["/绝对/路径/到/server.php"]
}
}
}
```
## 测试
```bash
vendor/bin/phpunit
```
## 工具列表
- **{工具名称}**: {工具描述}
## 开发
使用 MCP Inspector 测试:
```bash
npx @modelcontextprotocol/inspector php server.php
```
server.php
#!/usr/bin/env php
<?php
declare(strict_types=1);
require_once __DIR__ . '/vendor/autoload.php';
use Mcp\Server;
use Mcp\Server\Transport\StdioTransport;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;
// 设置发现缓存
$cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery', 3600, __DIR__ . '/cache'));
// 构建带发现的服务器
$server = Server::builder()
->setServerInfo('{项目名称}', '1.0.0')
->setDiscovery(
basePath: __DIR__,
scanDirs: ['src'],
excludeDirs: ['vendor', 'tests', 'cache'],
cache: $cache
)
->build();
// 使用 stdio 传输运行
$transport = new StdioTransport();
$server->run($transport);
src/Tools/ExampleTool.php
<?php
declare(strict_types=1);
namespace App\Tools;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\Schema;
class ExampleTool
{
/**
* 使用提供的名称执行问候。
*
* @param string $name 要问候的名称
* @return string 问候消息
*/
#[McpTool]
public function greet(string $name): string
{
return "你好,{$name}!";
}
/**
* 执行算术计算。
*/
#[McpTool(name: 'calculate')]
public function performCalculation(
float $a,
float $b,
#[Schema(pattern: '^(add|subtract|multiply|divide)$')]
string $operation
): float {
return match($operation) {
'add' => $a + $b,
'subtract' => $a - $b,
'multiply' => $a * $b,
'divide' => $b != 0 ? $a / $b :
throw new \InvalidArgumentException('除数不能为零'),
default => throw new \InvalidArgumentException('无效的操作')
};
}
}
src/Resources/ConfigResource.php
<?php
declare(strict_types=1);
namespace App\Resources;
use Mcp\Capability\Attribute\McpResource;
class ConfigResource
{
/**
* 提供应用程序配置。
*/
#[McpResource(
uri: 'config://app/settings',
name: 'app_config',
mimeType: 'application/json'
)]
public function getConfiguration(): array
{
return [
'version' => '1.0.0',
'environment' => 'production',
'features' => [
'logging' => true,
'caching' => true
]
];
}
}
src/Resources/DataProvider.php
<?php
declare(strict_types=1);
namespace App\Resources;
use Mcp\Capability\Attribute\McpResourceTemplate;
class DataProvider
{
/**
* 按类别和 ID 提供数据。
*/
#[McpResourceTemplate(
uriTemplate: 'data://{category}/{id}',
name: 'data_resource',
mimeType: 'application/json'
)]
public function getData(string $category, string $id): array
{
// 示例数据检索
return [
'category' => $category,
'id' => $id,
'data' => "类别 {$category}/ID {$id} 的示例数据"
];
}
}
src/Prompts/PromptGenerator.php
<?php
declare(strict_types=1);
namespace App\Prompts;
use Mcp\Capability\Attribute\McpPrompt;
use Mcp\Capability\Attribute\CompletionProvider;
class PromptGenerator
{
/**
* 生成代码审查提示词。
*/
#[McpPrompt(name: 'code_review')]
public function reviewCode(
#[CompletionProvider(values: ['php', 'javascript', 'python', 'go', 'rust'])]
string $language,
string $code,
#[CompletionProvider(values: ['performance', 'security', 'style', 'general'])]
string $focus = 'general'
): array {
return [
[
'role' => 'assistant',
'content' => '你是一位精通最佳实践和优化的代码审查专家。'
],
[
'role' => 'user',
'content' => "请审查这段 {$language} 代码,重点关注 {$focus} 方面:\n\n```{$language}\n{$code}\n```"
]
];
}
/**
* 生成文档提示词。
*/
#[McpPrompt]
public function generateDocs(string $code, string $style = 'detailed'): array
{
return [
[
'role' => 'user',
'content' => "请为以下代码生成 {$style} 文档:\n\n```\n{$code}\n```"
]
];
}
}
tests/ToolsTest.php
<?php
declare(strict_types=1);
namespace Tests;
use PHPUnit\Framework\TestCase;
use App\Tools\ExampleTool;
class ToolsTest extends TestCase
{
private ExampleTool $tool;
protected function setUp(): void
{
$this->tool = new ExampleTool();
}
public function testGreet(): void
{
$result = $this->tool->greet('世界');
$this->assertSame('你好,世界!', $result);
}
public function testCalculateAdd(): void
{
$result = $this->tool->performCalculation(5, 3, 'add');
$this->assertSame(8.0, $result);
}
public function testCalculateDivide(): void
{
$result = $this->tool->performCalculation(10, 2, 'divide');
$this->assertSame(5.0, $result);
}
public function testCalculateDivideByZero(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('除数不能为零');
$this->tool->performCalculation(10, 0, 'divide');
}
public function testCalculateInvalidOperation(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('无效的操作');
$this->tool->performCalculation(5, 3, 'modulo');
}
}
phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="测试套件">
<directory>tests</directory>
</testsuite>
</testsuites>
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
</phpunit>
实现指南
- 使用 PHP 属性:利用
#[McpTool]、#[McpResource]、#[McpPrompt]保持代码整洁 - 类型声明:在所有文件中使用严格类型(
declare(strict_types=1);) - PSR-12 编码标准:遵循 PHP-FIG 标准
- 模式验证:使用
#[Schema]属性进行参数验证 - 错误处理:抛出带有清晰信息的特定异常
- 测试:为所有工具编写 PHPUnit 测试
- 文档:为所有方法使用 PHPDoc 块
- 缓存:在生产环境中始终使用 PSR-16 缓存进行发现
工具模式
简单工具
#[McpTool]
public function simpleAction(string $input): string
{
return "已处理:{$input}";
}
带验证的工具
#[McpTool]
public function validateEmail(
#[Schema(format: 'email')]
string $email
): bool {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
带枚举的工具
enum Status: string {
case ACTIVE = 'active';
case INACTIVE = 'inactive';
}
#[McpTool]
public function setStatus(string $id, Status $status): array
{
return ['id' => $id, 'status' => $status->value];
}
资源模式
静态资源
#[McpResource(uri: 'config://settings', mimeType: 'application/json')]
public function getSettings(): array
{
return ['key' => 'value'];
}
动态资源
#[McpResourceTemplate(uriTemplate: 'user://{id}')]
public function getUser(string $id): array
{
return $this->users[$id] ?? throw new \RuntimeException('未找到用户');
}
运行服务器
# 安装依赖
composer install
# 运行测试
vendor/bin/phpunit
# 启动服务器
php server.php
# 使用 inspector 测试
npx @modelcontextprotocol/inspector php server.php
Claude Desktop 配置
{
"mcpServers": {
"{项目名称}": {
"command": "php",
"args": ["/绝对/路径/到/server.php"]
}
}
}
现在,请根据用户需求生成完整的项目!
📄 原始文档
完整文档(英文):
https://skills.sh/github/awesome-copilot/php-mcp-server-generator
💡 提示:点击上方链接查看 skills.sh 原始英文文档,方便对照翻译。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)