Fastmcphp
注:
- 根据anthropic的说法,sse已被弃用:https://code.claude.com/docs/en/mcp#option-2%3A-添加远程服务器
- 改用http
PHP 8.2+实现 模型上下文协议(MCP).
受...启发 FastMCP 对于Python。
需求
- PHP 8.2+
- Swoole 5.0+或OpenSwoole 4.0+(可选,建议用于生产HTTP/SSE)
安装
composer require fastmcphp/fastmcphp快速开始
tool(
callable: fn(string $text) => $text,
name: 'echo',
description: 'Echo the input text',
);
// Register a resource
$mcp->resource(
uri: 'config://app',
callable: fn() => ['version' => '1.0.0'],
name: 'config',
);
// Run with stdio transport
$mcp->run();特性
工具
定义可由MCP客户端调用的可调用函数:
// Simple tool
$mcp->tool(
callable: fn(int $a, int $b) => $a + $b,
name: 'add',
description: 'Add two numbers',
);
// Tool with context injection
$mcp->tool(
callable: function(string $query, Context $ctx): array {
$ctx->info("Searching for: {$query}");
return ['results' => []];
},
name: 'search',
);资源
通过基于URI的资源公开数据:
// Static resource
$mcp->resource(
uri: 'config://database',
callable: fn() => ['host' => 'localhost', 'port' => 5432],
);
// Parameterized resource (template)
$mcp->resource(
uri: 'users://{id}',
callable: fn(int $id) => getUserById($id),
);提示
定义可重用的提示模板:
use Fastmcphp\Prompts\Message;
$mcp->prompt(
callable: fn(string $topic) => [
Message::user("Explain {$topic} in simple terms"),
],
name: 'explain',
);运输
支持三种运输方式:
// Stdio (default) - for subprocess communication
$mcp->run(transport: 'stdio');
// HTTP - JSON-RPC over HTTP (falls back to built-in PHP server without Swoole)
$mcp->run(transport: 'http', host: '0.0.0.0', port: 8080);
// SSE - Server-Sent Events (deprecated, use HTTP instead)
$mcp->run(transport: 'sse', host: '0.0.0.0', port: 8080);HTTP传输会自动检测是否安装了Swoole/OpenSwoole。使用Swoole,它运行一个具有多个worker的高性能异步服务器。没有Swoole,它使用ReactPHP的基于事件循环的HTTP服务器(异步、单进程)。建议将Swoole用于生产部署。
认证
为承载令牌、API密钥或任何身份验证系统实现自定义身份验证提供程序:
use Fastmcphp\Server\Auth\AuthProviderInterface;
use Fastmcphp\Server\Auth\AuthRequest;
use Fastmcphp\Server\Auth\AuthResult;
use Fastmcphp\Server\Auth\AuthenticatedUser;
class MyAuthProvider implements AuthProviderInterface
{
public function authenticate(AuthRequest $request): AuthResult
{
$token = $request->getBearerToken();
if (!$token) {
return AuthResult::unauthenticated();
}
// Validate token against your auth system
$user = $this->validateToken($token);
if (!$user) {
return AuthResult::failed('Invalid token');
}
return AuthResult::success(new AuthenticatedUser(
id: $user['id'],
name: $user['name'],
level: $user['level'],
scopes: $user['scopes'],
workspace: $user['workspace'],
));
}
}
// Use the auth provider
$mcp->setAuth(new MyAuthProvider(), required: true);身份验证请求
AuthRequest 是传输和身份验证之间的抽象层。它规范了来自任何传输(Swoole HTTP、内置PHP HTTP、SSE)的请求数据,因此身份验证提供者不需要知道传输细节。
令牌提取 --使用 getToken() 对于基于优先级的自动查找:
X-API-TOKEN标题(通过getApiToken())Authorization: Bearer标题(通过getBearerToken())?key=查询参数(通过getApiKeyFromQuery())
可用方法:
| 方法 | 说明 |
|---|---|
getToken() | 从任何来源获取令牌(优先级顺序如上) |
getHeader(string $name) | 获取任何标头值(不区分大小写) |
getBearerToken() | 从中提取令牌 Authorization: Bearer 头球 |
getApiToken() | 获取 X-API-TOKEN 标题值 |
getApiKeyFromQuery(string $param = 'key') | 从查询参数中获取令牌 |
getQuery(string $key) | 获取任何查询参数 |
从客户端发送令牌:
# Using Authorization header (recommended)
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-token-here" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
# Using X-API-TOKEN header
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-H "X-API-TOKEN: your-token-here" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
# Using query parameter
curl -X POST "http://localhost:8080/mcp?key=your-token-here" \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'按工具授权
控制对单个工具、资源或提示的访问:
use Fastmcphp\Server\Auth\AuthorizationContext;
// Admin-only tool
$mcp->tool(
callable: fn() => 'sensitive data',
name: 'admin_tool',
auth: fn(AuthorizationContext $ctx) => $ctx->user->hasLevel(50), // ADMIN level
);
// Scope-based authorization
$mcp->tool(
callable: fn(string $query) => search($query),
name: 'search',
auth: fn(AuthorizationContext $ctx) => $ctx->user->hasScope('tools:search'),
);中间件
拦截和修改请求/响应:
use Fastmcphp\Server\Middleware\Middleware;
use Fastmcphp\Server\Middleware\MiddlewareContext;
class LoggingMiddleware extends Middleware
{
public function onCallTool(MiddlewareContext $ctx, callable $next): mixed
{
$toolName = $ctx->getToolName();
$user = $ctx->user?->name ?? 'anonymous';
echo "[{$user}] Calling tool: {$toolName}\n";
$start = microtime(true);
$result = $next($ctx);
$elapsed = microtime(true) - $start;
echo "[{$user}] Tool completed in {$elapsed}s\n";
return $result;
}
}
$mcp->addMiddleware(new LoggingMiddleware());多租户工作区支持
Fastmcphp通过身份验证系统支持多租户架构:
// Auth provider returns workspace context
return AuthResult::success($user, workspace: 'tenant-123');
// Workspace is available in middleware and authorization
$mcp->tool(
callable: fn() => getWorkspaceData(),
name: 'get_data',
auth: fn(AuthorizationContext $ctx) => $ctx->workspace === 'allowed-tenant',
);使用Claude代码
将您的MCP服务器添加到 .mcp.json 在项目根目录中(或 ~/.claude/.mcp.json 全球访问):
标准运输 (子流程——Claude Code管理该流程):
{
"mcpServers": {
"my-server": {
"command": "php",
"args": ["path/to/your/server.php"]
}
}
}HTTP传输 (remote--单独启动服务器):
{
"mcpServers": {
"my-server": {
"type": "http",
"url": "http://localhost:8080/mcp"
}
}
}带身份验证的HTTP:
{
"mcpServers": {
"my-server": {
"type": "http",
"url": "http://localhost:8080/mcp",
"headers": {
"Authorization": "Bearer your-token-here"
}
}
}
}测试
# Test stdio transport
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | php examples/echo_server.php
# Test tools/list
echo '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' | php examples/echo_server.php
# Test tools/call
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"Hello!"}}}' | php examples/echo_server.php
# Test authenticated HTTP server
php examples/authenticated_server.php &
curl -X POST http://localhost:8080/mcp \
-H "Content-Type: application/json" \
-H "Authorization: Bearer user-token-123" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'MCP协议支持
| 功能 | 状态 |
|---|---|
| 工具 | ✅ |
| 资源 | ✅ |
| 资源模板 | ✅ |
| 提示 | ✅ |
| 标准运输 | ✅ |
| HTTP传输 | ✅ |
| 苏格兰和南方能源公司运输✅ | |
| 身份验证 | ✅ |
| 中间件 | ✅ |
| 每个组件授权 | ✅ |
| 范围 | ✅ |
| 多租户 | ✅ |
| 分页 | ❌ |
许可证
麻省理工学院
