Files
advanced-mcp-plugin/includes/MCP/Server.php
T

233 lines
8.8 KiB
PHP

<?php
namespace AskTamMCP\MCP;
defined('ABSPATH') || exit;
/**
* MCP Server — Streamable HTTP transport (2025-03-26 spec).
*
* Claude.ai uses POST /sse for all communication (not GET SSE stream).
* Each POST carries a JSON-RPC message and gets a direct JSON response.
* We also keep GET /sse for legacy clients that expect SSE streams.
*
* POST /sse — Claude.ai sends JSON-RPC, gets JSON-RPC response
* GET /sse — legacy SSE stream for other MCP clients
* POST /message — explicit message endpoint (also supported)
*/
class Server {
private Registry $registry;
public function __construct() {
$this->registry = new Registry();
}
public function registerRoutes(): void {
// SSE endpoint — GET for legacy stream, POST for Claude.ai streamable HTTP
register_rest_route('asktam-mcp/v1', '/sse', [
[
'methods' => 'GET',
'callback' => [$this, 'handleSseGet'],
'permission_callback' => '__return_true',
],
[
'methods' => 'POST',
'callback' => [$this, 'handleSsePost'],
'permission_callback' => '__return_true',
],
]);
// Explicit message endpoint
register_rest_route('asktam-mcp/v1', '/message', [
'methods' => 'POST',
'callback' => [$this, 'handleMessage'],
'permission_callback' => '__return_true',
]);
register_rest_route('asktam-mcp/v1', '/info', [
'methods' => 'GET',
'callback' => [$this, 'handleInfo'],
'permission_callback' => '__return_true',
]);
}
// -------------------------------------------------------------------------
// POST /sse — Streamable HTTP transport (Claude.ai 2025+)
// Each request is a JSON-RPC message, response is JSON-RPC
// -------------------------------------------------------------------------
public function handleSsePost(\WP_REST_Request $request): \WP_REST_Response|\WP_Error {
$auth = \AskTamMCP\Core\Auth::validate($request, \AskTamMCP\Core\Auth::SCOPE_READ);
if (is_wp_error($auth)) {
return $auth;
}
return $this->dispatchJsonRpc($request, $auth);
}
// -------------------------------------------------------------------------
// GET /sse — Legacy SSE stream for non-Claude.ai clients
// -------------------------------------------------------------------------
public function handleSseGet(\WP_REST_Request $request): void {
$auth = \AskTamMCP\Core\Auth::validate($request, \AskTamMCP\Core\Auth::SCOPE_READ);
if (is_wp_error($auth)) {
status_header($auth->get_error_data()['status'] ?? 401);
header('Content-Type: application/json');
echo wp_json_encode(['error' => $auth->get_error_message()]);
exit;
}
@set_time_limit(0);
@ini_set('max_execution_time', 0);
while (ob_get_level()) ob_end_clean();
header('Content-Type: text/event-stream; charset=UTF-8');
header('Cache-Control: no-cache, no-store');
header('X-Accel-Buffering: no');
header('Connection: keep-alive');
header('Access-Control-Allow-Origin: *');
$messageEndpoint = rest_url('asktam-mcp/v1/message');
$this->sseEvent('endpoint', $messageEndpoint);
$this->sseEvent('message', wp_json_encode([
'jsonrpc' => '2.0',
'id' => null,
'result' => [
'protocolVersion' => '2024-11-05',
'capabilities' => ['tools' => ['listChanged' => false]],
'serverInfo' => ['name' => 'advanced-mcp-plugin', 'version' => ASKTAM_MCP_VERSION],
],
]));
$start = time();
while (!connection_aborted() && (time() - $start) < 270) {
$this->sseEvent('ping', (string) time());
for ($i = 0; $i < 15; $i++) {
if (connection_aborted()) break 2;
sleep(1);
}
}
echo "retry: 1000\n\n";
flush();
exit;
}
// -------------------------------------------------------------------------
// POST /message — explicit endpoint (same as POST /sse)
// -------------------------------------------------------------------------
public function handleMessage(\WP_REST_Request $request): \WP_REST_Response|\WP_Error {
$auth = \AskTamMCP\Core\Auth::validate($request, \AskTamMCP\Core\Auth::SCOPE_READ);
if (is_wp_error($auth)) {
return $auth;
}
return $this->dispatchJsonRpc($request, $auth);
}
public function handleInfo(): \WP_REST_Response {
return new \WP_REST_Response([
'name' => 'Advanced MCP Plugin by AskTam',
'version' => ASKTAM_MCP_VERSION,
'endpoint' => rest_url('asktam-mcp/v1/sse'),
'transport' => 'streamable-http',
'mcp_version' => '2025-03-26',
]);
}
// -------------------------------------------------------------------------
// Shared JSON-RPC dispatcher
// -------------------------------------------------------------------------
private function dispatchJsonRpc(\WP_REST_Request $request, array $auth): \WP_REST_Response {
$body = $request->get_json_params();
if (empty($body)) {
// Claude.ai sometimes sends empty POST to initialize connection
// Return capabilities immediately
return $this->rpcResult(null, [
'protocolVersion' => '2024-11-05',
'capabilities' => ['tools' => ['listChanged' => false]],
'serverInfo' => ['name' => 'advanced-mcp-plugin', 'version' => ASKTAM_MCP_VERSION],
]);
}
if (empty($body['method'])) {
return $this->rpcError(null, -32600, 'Invalid Request: missing method');
}
$id = $body['id'] ?? null;
$method = $body['method'];
$params = $body['params'] ?? [];
switch ($method) {
case 'initialize':
return $this->rpcResult($id, [
'protocolVersion' => '2024-11-05',
'capabilities' => ['tools' => ['listChanged' => false]],
'serverInfo' => ['name' => 'advanced-mcp-plugin', 'version' => ASKTAM_MCP_VERSION],
]);
case 'tools/list':
return $this->rpcResult($id, ['tools' => $this->registry->getToolDefinitions()]);
case 'tools/call':
return $this->handleToolCall($id, $params, $auth);
case 'notifications/initialized':
case 'notifications/cancelled':
return new \WP_REST_Response(null, 204);
default:
return $this->rpcError($id, -32601, "Method not found: {$method}");
}
}
private function handleToolCall(mixed $id, array $params, array $authRow): \WP_REST_Response {
$toolName = $params['name'] ?? '';
$arguments = $params['arguments'] ?? [];
if (empty($toolName)) {
return $this->rpcError($id, -32602, 'Missing tool name');
}
$handler = $this->registry->getHandler($toolName);
if (!$handler) {
return $this->rpcError($id, -32601, "Unknown tool: {$toolName}");
}
$tool = $this->registry->getTool($toolName);
$required = $tool['scope'] ?? 'read';
if ($required !== 'read') {
$keyScopes = array_map('trim', explode(',', $authRow['scopes']));
if (!in_array($required, $keyScopes, true) && !in_array('admin', $keyScopes, true)) {
return $this->rpcError($id, -32000, "Insufficient scope. Required: {$required}");
}
}
try {
$result = $handler($arguments);
return $this->rpcResult($id, [
'content' => [
['type' => 'text', 'text' => is_string($result) ? $result : wp_json_encode($result)],
],
]);
} catch (\Throwable $e) {
return $this->rpcError($id, -32000, $e->getMessage());
}
}
private function rpcResult(mixed $id, mixed $result): \WP_REST_Response {
return new \WP_REST_Response(['jsonrpc' => '2.0', 'id' => $id, 'result' => $result]);
}
private function rpcError(mixed $id, int $code, string $message): \WP_REST_Response {
return new \WP_REST_Response(['jsonrpc' => '2.0', 'id' => $id, 'error' => ['code' => $code, 'message' => $message]], 200);
}
private function sseEvent(string $event, string $data): void {
echo "event: {$event}\ndata: {$data}\n\n";
flush();
}
}