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:
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Enums\EventState;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\UpsertEventsRequest;
|
||||
use App\Ingest\EventUpserter;
|
||||
@@ -34,8 +33,7 @@ class EventsController extends Controller
|
||||
|
||||
public function destroy(Request $request): Response
|
||||
{
|
||||
$event = $this->lookup($request);
|
||||
$event->update(['state' => EventState::Withdrawn]);
|
||||
$this->upserter->withdraw($this->lookup($request));
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
@@ -28,9 +28,7 @@ class EventsController extends Controller
|
||||
? [$request->query('state')]
|
||||
: EventState::nonTerminalValues();
|
||||
|
||||
$events = $user->events()->with('source')->whereIn('state', $states)->orderBy('due_date')->orderBy('due_instant')->get();
|
||||
|
||||
return response()->json(['events' => $events->map(EventPresenter::forUser(...))->values()]);
|
||||
return response()->json(['events' => $user->liveEvents($states)->get()->map(EventPresenter::forUser(...))->values()]);
|
||||
}
|
||||
|
||||
public function ack(Request $request, int $event): JsonResponse
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Ingest\DueAtParser;
|
||||
use App\Ingest\EventRules;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Validator;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class UpsertEventsRequest extends FormRequest
|
||||
{
|
||||
@@ -21,42 +20,25 @@ class UpsertEventsRequest extends FormRequest
|
||||
'events.*.user' => ['required', 'string', 'max:255'],
|
||||
'events.*.source_ref' => ['required', 'string', 'max:255'],
|
||||
'events.*.topic' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||
'events.*.due_at' => ['required', 'string'],
|
||||
'events.*.fire_at' => ['required', 'date_format:Y-m-d'],
|
||||
'events.*.after_due' => ['required', 'in:keep,expire'],
|
||||
'events.*.payload' => ['required', 'array'],
|
||||
'events.*.payload.title' => ['required', 'string'],
|
||||
'events.*.payload.subtitle' => ['sometimes', 'nullable', 'string'],
|
||||
'events.*.payload.deep_link' => ['sometimes', 'nullable', 'string', 'max:2048', 'regex:#^(/(?![/\\\\])|https?://)#i'],
|
||||
'events.*.payload.done_label' => ['sometimes', 'nullable', 'string', 'max:64'],
|
||||
];
|
||||
] + EventRules::itemPrefixed('events.*.');
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'events.*.payload.deep_link.regex' => 'deep_link должен быть относительным путём или http(s)-ссылкой',
|
||||
];
|
||||
return EventRules::messages('events.*.');
|
||||
}
|
||||
|
||||
public function after(): array
|
||||
{
|
||||
return [function (Validator $v) {
|
||||
foreach ((array) $this->input('events', []) as $i => $item) {
|
||||
if (! is_array($item) || ! isset($item['due_at'], $item['fire_at']) || ! is_string($item['due_at'])) {
|
||||
if (! is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$due = DueAtParser::parse($item['due_at']);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$v->errors()->add("events.$i.due_at", $e->getMessage());
|
||||
|
||||
continue;
|
||||
}
|
||||
// Проверка fire_at <= день срока — по поясу по умолчанию; для fixed это
|
||||
// приближение, точный день пользователя известен только при upsert.
|
||||
if ($v->errors()->missing("events.$i.fire_at") && $item['fire_at'] > $due->dayFor(config('hado.default_tz'))) {
|
||||
$v->errors()->add("events.$i.fire_at", 'fire_at не может быть позже дня срока');
|
||||
foreach (EventRules::check($item) as $field => $error) {
|
||||
if ($v->errors()->missing("events.$i.$field")) {
|
||||
$v->errors()->add("events.$i.$field", $error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}];
|
||||
|
||||
97
core/app/Ingest/EventRules.php
Normal file
97
core/app/Ingest/EventRules.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Ingest;
|
||||
|
||||
use Illuminate\Support\Facades\Validator as ValidatorFactory;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\Validation\Validator;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Правила одного события в форме upsert-элемента (§5 спеки). Один источник правды
|
||||
* для клиентов (/api, пачкой) и для manual-событий из инбокса и от агента.
|
||||
*/
|
||||
final class EventRules
|
||||
{
|
||||
/** @return array<string,list<string>> */
|
||||
public static function item(): array
|
||||
{
|
||||
return [
|
||||
'due_at' => ['required', 'string'],
|
||||
'fire_at' => ['required', 'date_format:Y-m-d'],
|
||||
'after_due' => ['required', 'in:keep,expire'],
|
||||
'payload' => ['required', 'array'],
|
||||
'payload.title' => ['required', 'string'],
|
||||
'payload.subtitle' => ['sometimes', 'nullable', 'string'],
|
||||
'payload.deep_link' => ['sometimes', 'nullable', 'string', 'max:2048', 'regex:#^(/(?![/\\\\])|https?://)#i'],
|
||||
'payload.done_label' => ['sometimes', 'nullable', 'string', 'max:64'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Те же правила с префиксом ключа — для пачки `events.*.`.
|
||||
*
|
||||
* @return array<string,list<string>>
|
||||
*/
|
||||
public static function itemPrefixed(string $prefix): array
|
||||
{
|
||||
$rules = [];
|
||||
foreach (self::item() as $key => $rule) {
|
||||
$rules[$prefix.$key] = $rule;
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
public static function messages(string $prefix = ''): array
|
||||
{
|
||||
return [$prefix.'payload.deep_link.regex' => 'deep_link должен быть относительным путём или http(s)-ссылкой'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверки после правил: due_at разбирается, fire_at не позже дня срока.
|
||||
* Возвращает ошибки как поле => текст; пусто — всё хорошо.
|
||||
*
|
||||
* @param array<string,mixed> $item
|
||||
* @return array<string,string>
|
||||
*/
|
||||
public static function check(array $item): array
|
||||
{
|
||||
if (! isset($item['due_at'], $item['fire_at']) || ! is_string($item['due_at'])) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
$due = DueAtParser::parse($item['due_at']);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
return ['due_at' => $e->getMessage()];
|
||||
}
|
||||
// Проверка fire_at <= день срока — по поясу по умолчанию; для fixed это
|
||||
// приближение, точный день пользователя известен только при upsert.
|
||||
if ($item['fire_at'] > $due->dayFor(config('hado.default_tz'))) {
|
||||
return ['fire_at' => 'fire_at не может быть позже дня срока'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверить один элемент целиком.
|
||||
*
|
||||
* @param array<string,mixed> $item
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function validate(array $item): void
|
||||
{
|
||||
ValidatorFactory::make($item, self::item(), self::messages())
|
||||
->after(function (Validator $v) use ($item) {
|
||||
foreach (self::check($item) as $field => $error) {
|
||||
if ($v->errors()->missing($field)) {
|
||||
$v->errors()->add($field, $error);
|
||||
}
|
||||
}
|
||||
})
|
||||
->validate();
|
||||
}
|
||||
}
|
||||
@@ -38,15 +38,10 @@ final class EventUpserter
|
||||
});
|
||||
}
|
||||
|
||||
public function withdraw(Source $source, string $sourceRef, string $topic): bool
|
||||
/** Снять событие: withdrawn — терминальное, ядро больше не напоминает. */
|
||||
public function withdraw(Event $event): void
|
||||
{
|
||||
$event = $this->find($source, $sourceRef, $topic);
|
||||
if ($event === null) {
|
||||
return false;
|
||||
}
|
||||
$event->update(['state' => EventState::Withdrawn]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function find(Source $source, string $sourceRef, string $topic): ?Event
|
||||
|
||||
@@ -5,8 +5,10 @@ namespace App\Ingest;
|
||||
use App\Models\Event;
|
||||
use App\Models\Source;
|
||||
use App\Models\User;
|
||||
use App\Presenters\EventPresenter;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Str;
|
||||
use LogicException;
|
||||
|
||||
/**
|
||||
* События, которые пользователь заводит сам — кнопкой в инбоксе или через агента.
|
||||
@@ -32,25 +34,76 @@ final class ManualEvents
|
||||
*/
|
||||
public function create(User $user, array $fields): Event
|
||||
{
|
||||
return $this->upsert($user, 'manual:'.Str::ulid(), $fields);
|
||||
return $this->upsert($user, 'manual:'.Str::ulid(), self::item($fields));
|
||||
}
|
||||
|
||||
private function upsert(User $user, string $sourceRef, array $fields): Event
|
||||
/**
|
||||
* Частичная правка своего события: не переданные поля берутся из него. Новый `due_at` —
|
||||
* это перенос (§5): состояние пересчитывается даже из терминального, а `fire_at`,
|
||||
* если не задан явно, считается заново от нового срока.
|
||||
*
|
||||
* @param array<string,mixed> $fields
|
||||
*/
|
||||
public function update(Event $event, array $fields): Event
|
||||
{
|
||||
[$result] = $this->upserter->upsert($this->source(), [[
|
||||
'user' => $user->login,
|
||||
'source_ref' => $sourceRef,
|
||||
'topic' => '',
|
||||
'due_at' => $fields['due_at'],
|
||||
'fire_at' => $fields['fire_at'] ?? self::defaultFireAt($fields['due_at']),
|
||||
if (! self::owns($event)) {
|
||||
throw new LogicException("Событие источника «{$event->source->name}» правит только его источник");
|
||||
}
|
||||
$current = EventPresenter::forClient($event);
|
||||
$merged = [
|
||||
'title' => $current['payload']['title'],
|
||||
'subtitle' => $current['payload']['subtitle'] ?? null,
|
||||
'done_label' => $current['payload']['done_label'] ?? null,
|
||||
'deep_link' => $current['payload']['deep_link'] ?? null,
|
||||
'due_at' => $current['due_at'],
|
||||
'fire_at' => isset($fields['due_at']) ? null : $current['fire_at'],
|
||||
'after_due' => $current['after_due'],
|
||||
];
|
||||
foreach ($fields as $key => $value) {
|
||||
$merged[$key] = $value;
|
||||
}
|
||||
|
||||
return $this->upsert($event->user, $event->source_ref, self::item($merged));
|
||||
}
|
||||
|
||||
public function withdraw(Event $event): void
|
||||
{
|
||||
if (! self::owns($event)) {
|
||||
throw new LogicException("Событие источника «{$event->source->name}» снимает только его источник");
|
||||
}
|
||||
$this->upserter->withdraw($event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Плоские поля → upsert-элемент с дефолтами кнопки инбокса. Проверяется теми же
|
||||
* правилами, что и события клиентов.
|
||||
*
|
||||
* @param array<string,mixed> $fields
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private static function item(array $fields): array
|
||||
{
|
||||
$dueAt = (string) ($fields['due_at'] ?? '');
|
||||
$item = [
|
||||
'due_at' => $dueAt,
|
||||
'fire_at' => $fields['fire_at'] ?? self::defaultFireAt($dueAt),
|
||||
'after_due' => $fields['after_due'] ?? 'keep',
|
||||
'payload' => array_filter([
|
||||
'title' => $fields['title'],
|
||||
'title' => $fields['title'] ?? null,
|
||||
'subtitle' => $fields['subtitle'] ?? null,
|
||||
'done_label' => $fields['done_label'] ?? 'Сделано',
|
||||
'deep_link' => $fields['deep_link'] ?? null,
|
||||
], fn ($v) => $v !== null && $v !== ''),
|
||||
]]);
|
||||
];
|
||||
EventRules::validate($item);
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $item */
|
||||
private function upsert(User $user, string $sourceRef, array $item): Event
|
||||
{
|
||||
[$result] = $this->upserter->upsert($this->source(), [['user' => $user->login, 'source_ref' => $sourceRef, 'topic' => ''] + $item]);
|
||||
|
||||
return Event::with('source')->findOrFail($result['id']);
|
||||
}
|
||||
@@ -60,9 +113,11 @@ final class ManualEvents
|
||||
return Source::firstOrCreate(['name' => self::SOURCE], ['token_hash' => hash('sha256', Str::random(64))]);
|
||||
}
|
||||
|
||||
/** День срока минус DEFAULT_LEAD_DAYS; из due_at берётся только дата. */
|
||||
private static function defaultFireAt(string $dueAt): string
|
||||
/** День срока минус DEFAULT_LEAD_DAYS; из due_at берётся только дата. Кривой due_at отдаём правилам как есть. */
|
||||
private static function defaultFireAt(string $dueAt): ?string
|
||||
{
|
||||
return CarbonImmutable::createFromFormat('Y-m-d', substr($dueAt, 0, 10))->subDays(self::DEFAULT_LEAD_DAYS)->format('Y-m-d');
|
||||
$day = CarbonImmutable::createFromFormat('Y-m-d', substr($dueAt, 0, 10));
|
||||
|
||||
return $day === false ? null : $day->subDays(self::DEFAULT_LEAD_DAYS)->format('Y-m-d');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,5 +28,13 @@ class HadoServer extends Server
|
||||
Повторяющееся — отдельные события на каждое вхождение, не одно с переносом даты.
|
||||
MD;
|
||||
|
||||
protected array $tools = [];
|
||||
protected array $tools = [
|
||||
Tools\ListEvents::class,
|
||||
Tools\GetEvent::class,
|
||||
Tools\CreateEvent::class,
|
||||
Tools\UpdateEvent::class,
|
||||
Tools\DeleteEvent::class,
|
||||
Tools\MarkDone::class,
|
||||
Tools\MarkAck::class,
|
||||
];
|
||||
}
|
||||
|
||||
50
core/app/Mcp/Tools/AgentTool.php
Normal file
50
core/app/Mcp/Tools/AgentTool.php
Normal 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);
|
||||
}
|
||||
}
|
||||
72
core/app/Mcp/Tools/CreateEvent.php
Normal file
72
core/app/Mcp/Tools/CreateEvent.php
Normal 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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
35
core/app/Mcp/Tools/DeleteEvent.php
Normal file
35
core/app/Mcp/Tools/DeleteEvent.php
Normal 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]);
|
||||
});
|
||||
}
|
||||
}
|
||||
29
core/app/Mcp/Tools/GetEvent.php
Normal file
29
core/app/Mcp/Tools/GetEvent.php
Normal 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)));
|
||||
}
|
||||
}
|
||||
46
core/app/Mcp/Tools/ListEvents.php
Normal file
46
core/app/Mcp/Tools/ListEvents.php
Normal 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()]);
|
||||
}
|
||||
}
|
||||
34
core/app/Mcp/Tools/MarkAck.php
Normal file
34
core/app/Mcp/Tools/MarkAck.php
Normal 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')));
|
||||
});
|
||||
}
|
||||
}
|
||||
34
core/app/Mcp/Tools/MarkDone.php
Normal file
34
core/app/Mcp/Tools/MarkDone.php
Normal 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')));
|
||||
});
|
||||
}
|
||||
}
|
||||
32
core/app/Mcp/Tools/UpdateEvent.php
Normal file
32
core/app/Mcp/Tools/UpdateEvent.php
Normal 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))));
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,16 @@ class User extends Model
|
||||
return $this->events()->with('source')->whereKey($id)->firstOrFail();
|
||||
}
|
||||
|
||||
/**
|
||||
* Живые события в этих состояниях, по сроку.
|
||||
*
|
||||
* @param list<string> $states
|
||||
*/
|
||||
public function liveEvents(array $states): HasMany
|
||||
{
|
||||
return $this->events()->with('source')->whereIn('state', $states)->orderBy('due_date')->orderBy('due_instant');
|
||||
}
|
||||
|
||||
/** Закрытые события для архива: done и expired, свежие первыми, не больше 100. */
|
||||
public function archive(): HasMany
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user