Files
laysite/app/Controller/McpController.php
T

218 lines
10 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Controller;
use App\Config\Environment;
use App\Content\BlockTemplates;
use App\Content\Database;
use App\Content\DesignLibrary;
use App\Content\PageDraft;
use App\Content\PageTemplates;
use App\Content\Repository;
use App\Content\View;
use PDOException;
use RuntimeException;
use support\Request;
use support\Response;
final class McpController
{
private const PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26'];
public function endpoint(Request $request): Response
{
$origin = $request->header('origin');
if ($origin !== null && $origin !== '' && $origin !== rtrim(View::absolute(''), '/')) {
return new Response(403, ['Cache-Control' => 'no-store']);
}
$secret = Environment::get('LAYSITE_MCP_TOKEN');
$header = $request->header('authorization', '');
if (!is_string($secret) || strlen($secret) < 32 || !is_string($header) || !hash_equals('Bearer ' . $secret, $header)) {
return new Response(401, ['WWW-Authenticate' => 'Bearer realm="LaySite MCP"', 'Cache-Control' => 'no-store']);
}
if ($request->method() !== 'POST') {
return new Response(405, ['Allow' => 'POST', 'Cache-Control' => 'no-store']);
}
if (!preg_match('~^application/json(?:\s*;|$)~i', $request->header('content-type', ''))) {
return new Response(415, ['Cache-Control' => 'no-store']);
}
$protocol = $request->header('mcp-protocol-version');
if ($protocol !== null && $protocol !== '' && !in_array($protocol, self::PROTOCOLS, true)) {
return new Response(400, ['Cache-Control' => 'no-store']);
}
$body = $request->rawBody();
if (strlen($body) > 1048576) {
return new Response(413, ['Cache-Control' => 'no-store']);
}
$message = json_decode($body, true, 48);
if (json_last_error() !== JSON_ERROR_NONE) {
return $this->error(null, -32700, 'Invalid JSON');
}
$id = $message['id'] ?? null;
$method = $message['method'] ?? null;
if (!is_array($message) || ($message['jsonrpc'] ?? '') !== '2.0' || !is_string($method)
|| (array_key_exists('id', $message) && !is_int($id) && !is_string($id))) {
return $this->error(null, -32600, 'Invalid request');
}
if (!array_key_exists('id', $message)) {
return new Response(202, ['Cache-Control' => 'no-store']);
}
$params = $message['params'] ?? [];
if (!is_array($params)) {
return $this->error($id, -32602, 'Invalid params');
}
return match ($method) {
'initialize' => $this->result($id, [
'protocolVersion' => in_array($params['protocolVersion'] ?? null, self::PROTOCOLS, true) ? $params['protocolVersion'] : self::PROTOCOLS[0],
'capabilities' => ['tools' => (object) []], 'serverInfo' => ['name' => 'laysite', 'version' => trim(file_get_contents(dirname(__DIR__, 2) . '/VERSION'))],
'instructions' => 'Create or revise draft pages. A human can open the editor URL to review, refine and publish.',
]),
'ping' => $this->result($id, (object) []),
'tools/list' => $this->result($id, ['tools' => $this->tools()]),
'tools/call' => $this->invoke($id, $params),
default => $this->error($id, -32601, 'Method not found'),
};
}
private function tools(): array
{
$string = ['type' => 'string'];
$object = static fn (array $properties, array $required = []): array => [
'type' => 'object', 'properties' => (object) $properties, 'required' => $required, 'additionalProperties' => false,
];
$optional = [
'name' => $string, 'title' => $string, 'heading' => $string, 'description' => $string, 'lead' => $string,
'accent' => $string, 'image' => $string, 'alt' => $string,
'header_id' => ['type' => ['integer', 'null']], 'footer_id' => ['type' => ['integer', 'null']], 'palette_id' => ['type' => ['integer', 'null']],
'visibility' => $object(['hero' => ['type' => 'boolean'], 'header' => ['type' => 'boolean'], 'footer' => ['type' => 'boolean']]),
'actions' => ['type' => 'array', 'maxItems' => 8, 'items' => ['type' => 'array', 'description' => '[URL, label, style, boolean opensNewTab]. Style: solid, outline, underline, plain.']],
'sections' => ['type' => 'array', 'maxItems' => 50, 'items' => $object([
'key' => $string, 'title' => $string, 'lead' => $string, 'body' => $string,
'style' => ['enum' => ['plain', 'tinted']], 'preset' => $string,
], ['key'])],
];
$definitions = [
'list_pages' => ['List pages and their current revisions.', $object([])],
'get_page' => ['Read a page and its editable sections.', $object(['slug' => $string], ['slug'])],
'list_templates' => ['List whole-page templates and reusable components.', $object([])],
'list_designs' => ['List saved header, footer and palette IDs. Authentication settings are private.', $object([])],
'create_draft' => ['Create a draft from content or a template. Returns the editor URL.', $object(['slug' => $string, 'template' => $string] + $optional, ['slug', 'name'])],
'save_draft' => ['Save a draft at the supplied version. A supplied sections array replaces the section list. Omitted fields are preserved.',
$object(['slug' => $string, 'version' => ['type' => 'integer', 'minimum' => 0]] + $optional, ['slug', 'version'])],
];
$tools = [];
foreach ($definitions as $name => [$description, $inputSchema]) {
$tools[] = compact('name', 'description', 'inputSchema');
}
return $tools;
}
private function invoke(int|string $id, array $params): Response
{
$name = $params['name'] ?? null;
$args = $params['arguments'] ?? [];
if (!is_string($name) || !is_array($args)) {
return $this->error($id, -32602, 'Invalid tool call');
}
$repo = new Repository();
try {
$data = match ($name) {
'list_pages' => $repo->pages(),
'get_page' => $this->read($repo, PageDraft::slug($args['slug'] ?? null, [])),
'list_templates' => $this->templates(),
'list_designs' => DesignLibrary::all(),
'create_draft' => $this->create($repo, $args),
'save_draft' => $this->save($repo, $args),
default => throw new RuntimeException('Unknown tool'),
};
return $this->result($id, ['content' => [['type' => 'text', 'text' => Database::json($data)]]]);
} catch (RuntimeException $error) {
$message = $error instanceof PDOException ? 'Could not save the requested change.' : $error->getMessage();
return $this->result($id, ['isError' => true, 'content' => [['type' => 'text', 'text' => $message]]]);
}
}
private function read(Repository $repo, string $slug): array
{
$page = $repo->page($slug);
if (!$page) {
throw new RuntimeException('页面不存在。');
}
return $page;
}
private function create(Repository $repo, array $args): array
{
$slug = PageDraft::slug($args['slug'] ?? null);
$key = $args['template'] ?? '';
$template = $key === '' ? [] : (is_string($key) ? PageTemplates::find($key) : null);
if ($template === null) {
throw new RuntimeException('整页模板不存在。');
}
if (!isset($args['name'])) {
throw new RuntimeException('请填写页面名称。');
}
$page = PageDraft::content($args, $template);
$repo->createPage($slug, $page['name'], $page);
return $this->summary($repo, $slug);
}
private function save(Repository $repo, array $args): array
{
$slug = PageDraft::slug($args['slug'] ?? null);
$page = $this->read($repo, $slug);
$version = $args['version'] ?? null;
if ($page['status'] !== 'draft' || !is_int($version) || $version !== $page['version']) {
throw new RuntimeException('只能编辑匹配当前版本的草稿。请重新读取页面。');
}
$page = PageDraft::content($args, $page);
$replace = array_key_exists('sections', $args);
$repo->savePage($slug, $page, $version, $replace ? $page['sections'] : [], replaceDraftSections: $replace);
return $this->summary($repo, $slug);
}
private function summary(Repository $repo, string $slug): array
{
return ['slug' => $slug, 'version' => $this->read($repo, $slug)['version'],
'editor' => View::absolute('/admin/pages/' . $slug), 'preview' => View::absolute('/admin/pages/' . $slug . '/preview')];
}
private function templates(): array
{
$pages = [];
foreach (PageTemplates::groups() as $theme => $group) {
foreach ($group['pages'] as $key => $page) {
$pages[$key] = ['name' => $page['name'], 'theme' => $theme, 'description' => $page['description']];
}
}
$blocks = [];
foreach (BlockTemplates::groups() as [, $group]) {
foreach ($group as $key => $block) {
$blocks[$key] = $block[0];
}
}
return compact('pages', 'blocks');
}
private function error(int|string|null $id, int $code, string $message): Response
{
return $this->json(['jsonrpc' => '2.0', 'id' => $id, 'error' => compact('code', 'message')]);
}
private function result(int|string $id, array|object $result): Response
{
return $this->json(['jsonrpc' => '2.0', 'id' => $id, 'result' => $result]);
}
private function json(array $payload): Response
{
return new Response(200, ['Content-Type' => 'application/json', 'Cache-Control' => 'no-store', 'X-Content-Type-Options' => 'nosniff'], Database::json($payload));
}
}