feat: MCP tools for events (list/get/create/update/delete/done/ack); EventRules shared by /api and manual

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCrwHHnGCB5XH968Nxokqw
This commit is contained in:
nikita.hohlov
2026-09-05 06:10:41 -03:00
parent 450c165fce
commit ed45a1d516
18 changed files with 711 additions and 56 deletions

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Mcp\Tools;
use App\Ingest\ManualEvents;
use App\Models\Event;
use App\Models\User;
use Closure;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Tool;
/** Общее для тулов агента: пользователь токена и его события. */
abstract class AgentTool extends Tool
{
/** Пользователь, которого положил AuthenticateAgent — тот же атрибут, что у RemoteUser. */
protected function user(): User
{
return request()->attributes->get('user');
}
/** Событие по `id` из аргументов; чужое или несуществующее — ошибка для модели, а не 500. */
protected function withEvent(Request $request, Closure $then): Response|ResponseFactory
{
$id = (int) $request->validate(['id' => ['required', 'integer']])['id'];
try {
$event = $this->user()->ownEvent($id);
} catch (ModelNotFoundException) {
return Response::error('Событие не найдено');
}
return $then($event);
}
/** То же, но только своё (manual) событие — для правки и снятия. */
protected function withOwnEvent(Request $request, Closure $then): Response|ResponseFactory
{
return $this->withEvent($request, fn (Event $event) => ManualEvents::owns($event)
? $then($event)
: Response::error("Это событие источника {$event->source->name}: правит и снимает его только источник. Можно закрыть через mark_done."));
}
/** @param array<string,mixed> $data */
protected function respond(array $data): ResponseFactory
{
return Response::structured($data);
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace App\Mcp\Tools;
use App\Ingest\ManualEvents;
use App\Presenters\EventPresenter;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\ResponseFactory;
class CreateEvent extends AgentTool
{
protected string $name = 'create_event';
protected string $description = 'Поставить пользователю напоминание (источник manual — как кнопка «Добавить» в инбоксе). `due_at`: `YYYY-MM-DD` (весь день), `YYYY-MM-DDTHH:MM` (по поясу пользователя) или со смещением `+02:00` — только если событие привязано к месту. `fire_at` — день, с которого начинать напоминать; по умолчанию за 30 дней до срока. `after_due`: `keep` — после срока долбить, пока не закроют (по умолчанию), `expire` — тихо истечь. Повторяющееся — отдельное событие на каждое вхождение.';
public function __construct(private readonly ManualEvents $manual) {}
public function schema(JsonSchema $schema): array
{
return self::fields($schema, required: true);
}
public function handle(Request $request): ResponseFactory
{
$fields = $request->validate(self::shape(required: true));
return $this->respond(EventPresenter::forUser($this->manual->create($this->user(), $fields)));
}
/**
* Поля события общие для create_event и update_event. Форматы и смысл
* (fire_at не позже срока, deep_link путь или ссылка) проверяет ManualEvents.
*
* @return array<string,mixed>
*/
public static function fields(JsonSchema $schema, bool $required): array
{
$title = $schema->string()->max(200)->description('Заголовок напоминания');
$dueAt = $schema->string()->description('Срок: YYYY-MM-DD, YYYY-MM-DDTHH:MM или со смещением');
return [
'title' => $required ? $title->required() : $title,
'due_at' => $required ? $dueAt->required() : $dueAt,
'subtitle' => $schema->string()->max(200)->description('Подзаголовок'),
'fire_at' => $schema->string()->description('YYYY-MM-DD, день начала подготовки; не позже дня срока'),
'after_due' => $schema->string()->enum(['keep', 'expire'])->description('Что после срока: keep (по умолчанию) или expire'),
'done_label' => $schema->string()->max(64)->description('Подпись кнопки закрытия, по умолчанию «Сделано»'),
'deep_link' => $schema->string()->description('Куда вести из напоминания: относительный путь или http(s)-ссылка'),
];
}
/**
* Форма аргументов: что передано и какого типа. Остальное EventRules через ManualEvents.
*
* @return array<string,list<string>>
*/
public static function shape(bool $required): array
{
$presence = $required ? 'required' : 'sometimes';
return [
'title' => [$presence, 'string', 'max:200'],
'due_at' => [$presence, 'string'],
'subtitle' => ['sometimes', 'nullable', 'string', 'max:200'],
'fire_at' => ['sometimes', 'nullable', 'string'],
'after_due' => ['sometimes', 'string'],
'done_label' => ['sometimes', 'nullable', 'string'],
'deep_link' => ['sometimes', 'nullable', 'string'],
];
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Mcp\Tools;
use App\Ingest\ManualEvents;
use App\Models\Event;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
#[IsDestructive]
class DeleteEvent extends AgentTool
{
protected string $name = 'delete_event';
protected string $description = 'Снять своё событие (editable: true): оно уходит в withdrawn и больше не напоминает. Это не «Сделано» — для закрытия любого события есть mark_done.';
public function __construct(private readonly ManualEvents $manual) {}
public function schema(JsonSchema $schema): array
{
return ['id' => $schema->integer()->required()];
}
public function handle(Request $request): Response|ResponseFactory
{
return $this->withOwnEvent($request, function (Event $event) {
$this->manual->withdraw($event);
return $this->respond(['id' => $event->id, 'state' => $event->fresh()->state->value]);
});
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Mcp\Tools;
use App\Models\Event;
use App\Presenters\EventPresenter;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class GetEvent extends AgentTool
{
protected string $name = 'get_event';
protected string $description = 'Одно событие пользователя целиком по id.';
public function schema(JsonSchema $schema): array
{
return ['id' => $schema->integer()->required()];
}
public function handle(Request $request): Response|ResponseFactory
{
return $this->withEvent($request, fn (Event $event) => $this->respond(EventPresenter::forUser($event)));
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Mcp\Tools;
use App\Enums\EventState;
use App\Models\Event;
use App\Presenters\EventPresenter;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Validation\Rule;
use Laravel\Mcp\Request;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class ListEvents extends AgentTool
{
protected string $name = 'list_events';
protected string $description = 'Инбокс пользователя: активные события всех источников по сроку. `state` — фильтр по одному состоянию, `archive: true` — вместо активных закрытые (done, expired), последние 100. У каждого события `editable` говорит, можно ли его править и снимать (только свои, источник manual).';
public function schema(JsonSchema $schema): array
{
return [
'state' => $schema->string()->enum(EventState::nonTerminalValues())->description('Только события в этом состоянии'),
'archive' => $schema->boolean()->description('Закрытые события вместо активных'),
];
}
public function handle(Request $request): ResponseFactory
{
$args = $request->validate([
'state' => ['sometimes', Rule::in(EventState::nonTerminalValues())],
'archive' => ['sometimes', 'boolean'],
]);
$user = $this->user();
if ($args['archive'] ?? false) {
return $this->respond(['events' => $user->archive()->get()
->map(fn (Event $e) => EventPresenter::forUser($e) + ['closed_as' => EventPresenter::closedAs($e)])->values()->all()]);
}
$states = isset($args['state']) ? [$args['state']] : EventState::nonTerminalValues();
return $this->respond(['events' => $user->liveEvents($states)->get()->map(EventPresenter::forUser(...))->values()->all()]);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Mcp\Tools;
use App\Delivery\EventActions;
use App\Models\Event;
use App\Presenters\EventPresenter;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
class MarkAck extends AgentTool
{
protected string $name = 'mark_ack';
protected string $description = '«Помню»: заглушить текущее напоминание до следующей контрольной точки, событие остаётся открытым. Работает для события любого источника; на закрытом ничего не делает.';
public function __construct(private readonly EventActions $actions) {}
public function schema(JsonSchema $schema): array
{
return ['id' => $schema->integer()->required()];
}
public function handle(Request $request): Response|ResponseFactory
{
return $this->withEvent($request, function (Event $event) {
$this->actions->ack($event);
return $this->respond(EventPresenter::forUser($event->fresh('source')));
});
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Mcp\Tools;
use App\Delivery\EventActions;
use App\Models\Event;
use App\Presenters\EventPresenter;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
class MarkDone extends AgentTool
{
protected string $name = 'mark_done';
protected string $description = '«Сделано»: закрыть событие любого источника — как кнопка в инбоксе. Уже закрытое не трогается.';
public function __construct(private readonly EventActions $actions) {}
public function schema(JsonSchema $schema): array
{
return ['id' => $schema->integer()->required()];
}
public function handle(Request $request): Response|ResponseFactory
{
return $this->withEvent($request, function (Event $event) {
$this->actions->done($event);
return $this->respond(EventPresenter::forUser($event->fresh('source')));
});
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Mcp\Tools;
use App\Ingest\ManualEvents;
use App\Models\Event;
use App\Presenters\EventPresenter;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
class UpdateEvent extends AgentTool
{
protected string $name = 'update_event';
protected string $description = 'Поправить своё событие (editable: true) — любое подмножество полей create_event, остальное не меняется. Новый `due_at` — это перенос: состояние пересчитывается от новой даты даже у закрытого события, «Помню» сбрасывается, `fire_at` без явного значения считается заново (за 30 дней до нового срока). События других источников не правятся — их закрывают через mark_done.';
public function __construct(private readonly ManualEvents $manual) {}
public function schema(JsonSchema $schema): array
{
return ['id' => $schema->integer()->required()] + CreateEvent::fields($schema, required: false);
}
public function handle(Request $request): Response|ResponseFactory
{
$fields = $request->validate(CreateEvent::shape(required: false));
return $this->withOwnEvent($request, fn (Event $event) => $this->respond(EventPresenter::forUser($this->manual->update($event, $fields))));
}
}