PHP code example of huangdijia / mcp-sdk-php
1. Go to this page and download the library: Download huangdijia/mcp-sdk-php library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
huangdijia / mcp-sdk-php example snippets
use ModelContextProtocol\SDK\Server\McpServer;
use ModelContextProtocol\SDK\Server\Transport\StdioServerTransport;
use ModelContextProtocol\SDK\Shared\ResourceTemplate;
// Create an MCP server
$server = new McpServer([
'name' => 'Demo',
'version' => '1.0.0'
]);
// Add an addition tool
$server->tool('add', function (array $params) {
$a = $params['a'] ?? 0;
$b = $params['b'] ?? 0;
return [
'content' => [
['type' => 'text', 'text' => (string)($a + $b)]
]
];
});
// 示例:添加更多计算工具
$server->tool('multiply', function (array $params) {
$a = $params['a'] ?? 0;
$b = $params['b'] ?? 0;
return [
'content' => [
['type' => 'text', 'text' => (string)($a * $b)]
]
];
}, '将两个数字相乘', [
'a' => ['type' => 'number', 'description' => '第一个数字'],
'b' => ['type' => 'number', 'description' => '第二个数字'],
]);
// 示例:添加文本处理工具
$server->tool('textProcess', function (array $params) {
$text = $params['text'] ?? '';
$operation = $params['operation'] ?? 'none';
switch ($operation) {
case 'uppercase':
$result = strtoupper($text);
break;
case 'lowercase':
$result = strtolower($text);
break;
case 'capitalize':
$result = ucwords($text);
break;
case 'reverse':
$result = strrev($text);
break;
default:
$result = $text;
}
return [
'content' => [
['type' => 'text', 'text' => $result],
],
];
}, '处理文本字符串', [
'text' => ['type' => 'string', 'description' => '要处理的文本'],
'operation' => [
'type' => 'string',
'description' => '要执行的操作',
'enum' => ['uppercase', 'lowercase', 'capitalize', 'reverse', 'none'],
],
]);
// Add a dynamic greeting resource
$server->resource(
'greeting',
new ResourceTemplate('greeting://{name}', ['list' => null]),
function (string $uri, array $params) {
return [
'contents' => [[
'uri' => $uri,
'text' => "Hello, {$params['name']}!"
]]
];
}
);
// 示例:添加更多资源类型
$server->resource(
'time',
new ResourceTemplate('time://', ['list' => []]),
function (string $uri, array $params) {
$timezone = $params['timezone'] ?? 'Asia/Shanghai';
$format = $params['format'] ?? 'Y-m-d H:i:s';
try {
$dateTime = new DateTime('now', new DateTimeZone($timezone));
return [
'contents' => [[
'uri' => $uri,
'text' => '当前时间: ' . $dateTime->format($format),
]],
];
} catch (Exception $e) {
return [
'contents' => [[
'uri' => $uri,
'text' => '时间获取失败: ' . $e->getMessage(),
]],
];
}
}
);
// Start receiving messages on stdin and sending messages on stdout
$transport = new StdioServerTransport();
$server->connect($transport);
bash
composer
json
{
"servers": {
"test-mcp": {
"command": "php",
"args": [
"[your-path]/mcp-php/examples/stdio-server.php",
],
"env": {}
}
}
}