feat: MCP profile tools; ProfileUpdater/ProfilePresenter shared with /me; docs and Caddy snippet for /mcp

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:14:31 -03:00
parent ed45a1d516
commit 8ee8a30fb5
12 changed files with 220 additions and 50 deletions

View File

@@ -4,11 +4,11 @@ namespace App\Http\Controllers;
use App\Enums\EventState;
use App\Http\Controllers\Me\ChannelsController;
use App\Http\Controllers\Me\ProfileController;
use App\Ingest\ManualEvents;
use App\Models\Event;
use App\Models\User;
use App\Presenters\EventPresenter;
use App\Presenters\ProfilePresenter;
use App\Scheduling\DueResolver;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\View\View;
@@ -45,7 +45,7 @@ class InboxController extends Controller
'closed_as' => EventPresenter::closedAs($e),
])->values()->all();
$profile = ProfileController::present($user);
$profile = ProfilePresenter::present($user);
return view('inbox', [
'profile' => $profile,

View File

@@ -2,21 +2,22 @@
namespace App\Http\Controllers\Me;
use App\Enums\EventState;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Presenters\ProfilePresenter;
use App\Users\ProfileUpdater;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
class ProfileController extends Controller
{
public function __construct(private readonly ProfileUpdater $profile) {}
public function show(Request $request): JsonResponse
{
return response()->json(self::present($request->attributes->get('user')));
return response()->json(ProfilePresenter::present($request->attributes->get('user')));
}
public function update(Request $request): JsonResponse
@@ -24,27 +25,7 @@ class ProfileController extends Controller
/** @var User $user */
$user = $request->attributes->get('user');
$data = $request->validate([
'tz' => ['sometimes', 'string', Rule::in(\DateTimeZone::listIdentifiers())],
'quiet_start' => ['sometimes', 'date_format:H:i'],
'quiet_end' => ['sometimes', 'date_format:H:i'],
]);
$start = $data['quiet_start'] ?? substr($user->quiet_start, 0, 5);
$end = $data['quiet_end'] ?? substr($user->quiet_end, 0, 5);
if ($end >= $start) {
throw ValidationException::withMessages([
'quiet_end' => 'Тихие часы должны переходить через полночь: quiet_end раньше quiet_start',
]);
}
$user->fill([
'tz' => $data['tz'] ?? $user->tz,
'quiet_start' => $start.':00',
'quiet_end' => $end.':00',
])->save();
return response()->json(self::present($user));
return response()->json(ProfilePresenter::present($this->profile->update($user, $request->all())));
}
public function heartbeat(Request $request): Response
@@ -55,16 +36,4 @@ class ProfileController extends Controller
return response()->noContent();
}
/** @return array<string,mixed> */
public static function present(User $user): array
{
return [
'login' => $user->login,
'tz' => $user->tz,
'quiet_start' => substr($user->quiet_start, 0, 5),
'quiet_end' => substr($user->quiet_end, 0, 5),
'badge' => $user->events()->whereIn('state', EventState::badgeValues())->count(),
];
}
}

View File

@@ -36,5 +36,7 @@ class HadoServer extends Server
Tools\DeleteEvent::class,
Tools\MarkDone::class,
Tools\MarkAck::class,
Tools\GetProfile::class,
Tools\UpdateProfile::class,
];
}

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Mcp\Tools;
use App\Presenters\ProfilePresenter;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class GetProfile extends AgentTool
{
protected string $name = 'get_profile';
protected string $description = 'Профиль пользователя: логин, часовой пояс, тихие часы (quiet_startquiet_end, через полночь) и бейдж — сколько событий в today и overdue.';
public function handle(): ResponseFactory
{
return $this->respond(ProfilePresenter::present($this->user()));
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Mcp\Tools;
use App\Presenters\ProfilePresenter;
use App\Users\ProfileUpdater;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\ResponseFactory;
class UpdateProfile extends AgentTool
{
protected string $name = 'update_profile';
protected string $description = 'Поменять часовой пояс и/или тихие часы пользователя — любое подмножество полей. Тихие часы должны переходить через полночь: quiet_end раньше quiet_start.';
public function __construct(private readonly ProfileUpdater $profile) {}
public function schema(JsonSchema $schema): array
{
return [
'tz' => $schema->string()->description('Идентификатор зоны, напр. Europe/Belgrade'),
'quiet_start' => $schema->string()->description('HH:MM, начало тихих часов'),
'quiet_end' => $schema->string()->description('HH:MM, конец тихих часов'),
];
}
public function handle(Request $request): ResponseFactory
{
return $this->respond(ProfilePresenter::present($this->profile->update($this->user(), $request->all())));
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace App\Presenters;
use App\Enums\EventState;
use App\Models\User;
/** Профиль для инбокса и агента: пояс, тихие часы, бейдж. */
final class ProfilePresenter
{
/** @return array<string,mixed> */
public static function present(User $user): array
{
return [
'login' => $user->login,
'tz' => $user->tz,
'quiet_start' => substr($user->quiet_start, 0, 5),
'quiet_end' => substr($user->quiet_end, 0, 5),
'badge' => $user->events()->whereIn('state', EventState::badgeValues())->count(),
];
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Users;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
/** Правка профиля — пояс и тихие часы; правила одни для инбокса и агента. */
final class ProfileUpdater
{
/**
* @param array<string,mixed> $input любое подмножество tz, quiet_start, quiet_end (HH:MM)
*
* @throws ValidationException
*/
public function update(User $user, array $input): User
{
$data = Validator::validate($input, [
'tz' => ['sometimes', 'string', Rule::in(\DateTimeZone::listIdentifiers())],
'quiet_start' => ['sometimes', 'date_format:H:i'],
'quiet_end' => ['sometimes', 'date_format:H:i'],
]);
$start = $data['quiet_start'] ?? substr($user->quiet_start, 0, 5);
$end = $data['quiet_end'] ?? substr($user->quiet_end, 0, 5);
if ($end >= $start) {
throw ValidationException::withMessages([
'quiet_end' => 'Тихие часы должны переходить через полночь: quiet_end раньше quiet_start',
]);
}
$user->fill([
'tz' => $data['tz'] ?? $user->tz,
'quiet_start' => $start.':00',
'quiet_end' => $end.':00',
])->save();
return $user;
}
}

View File

@@ -36,4 +36,18 @@ class McpAuthTest extends TestCase
->assertOk()
->assertJsonPath('result.serverInfo.name', 'Hado');
}
public function test_lists_all_tools_over_http(): void
{
$user = User::create(['login' => 'nikita', 'tz' => 'UTC']);
AgentToken::create(['user_id' => $user->id, 'token_hash' => hash('sha256', 'secret')]);
$names = collect($this->postJson('/mcp', ['jsonrpc' => '2.0', 'id' => 2, 'method' => 'tools/list'], ['Authorization' => 'Bearer secret'])
->assertOk()->json('result.tools'))->pluck('name')->all();
$this->assertSame([
'list_events', 'get_event', 'create_event', 'update_event', 'delete_event',
'mark_done', 'mark_ack', 'get_profile', 'update_profile',
], $names);
}
}

View File

@@ -36,7 +36,7 @@ class McpToolsTest extends TestCase
parent::setUp();
config(['hado.default_tz' => 'UTC']);
CarbonImmutable::setTestNow('2026-09-05T12:00:00Z');
$this->user = User::create(['login' => 'nikita', 'tz' => 'UTC']);
$this->user = User::create(['login' => 'nikita', 'tz' => 'UTC'])->fresh(); // дефолты тихих часов — из БД
$this->docs = Source::create(['name' => 'docs', 'token_hash' => hash('sha256', 'x')]);
// Как AuthenticateAgent: пользователь токена лежит в атрибутах текущего запроса
$this->app['request']->attributes->set('user', $this->user);
@@ -168,6 +168,48 @@ class McpToolsTest extends TestCase
$this->assertSame(EventState::Today, $docs->fresh()->state);
}
// --- действия пользователя: любой источник ---
public function test_mark_done_closes_foreign_event_like_the_inbox_button(): void
{
$docs = $this->docsEvent($this->user);
HadoServer::tool(MarkDone::class, ['id' => $docs->id])->assertOk()
->assertStructuredContent(fn (AssertableJson $j) => $j->where('state', 'done')->where('editable', false)->etc());
$this->assertNotNull($docs->fresh()->done_at);
// повторно — no-op, без ошибки
HadoServer::tool(MarkDone::class, ['id' => $docs->id])->assertOk();
}
public function test_mark_ack_silences_until_next_checkpoint(): void
{
$docs = $this->docsEvent($this->user);
$before = $docs->quiet_until;
HadoServer::tool(MarkAck::class, ['id' => $docs->id])->assertOk()
->assertStructuredContent(fn (AssertableJson $j) => $j->where('state', 'today')->etc());
$this->assertTrue($docs->fresh()->quiet_until->gt($before));
$other = User::create(['login' => 'other', 'tz' => 'UTC']);
HadoServer::tool(MarkAck::class, ['id' => $this->docsEvent($other, EventState::Today, 'f')->id])->assertHasErrors(['не найдено']);
}
// --- профиль ---
public function test_profile_is_readable_and_editable_with_inbox_rules(): void
{
HadoServer::tool(GetProfile::class)->assertOk()
->assertStructuredContent(fn (AssertableJson $j) => $j->where('login', 'nikita')->where('tz', 'UTC')->where('quiet_start', '22:00')->where('quiet_end', '09:00')->etc());
HadoServer::tool(UpdateProfile::class, ['tz' => 'America/Montevideo', 'quiet_start' => '23:30'])->assertOk()
->assertStructuredContent(fn (AssertableJson $j) => $j->where('tz', 'America/Montevideo')->where('quiet_start', '23:30')->where('quiet_end', '09:00')->etc());
$this->assertSame('America/Montevideo', $this->user->fresh()->tz);
HadoServer::tool(UpdateProfile::class, ['tz' => 'Mars/Olympus'])->assertHasErrors(['tz']);
HadoServer::tool(UpdateProfile::class, ['quiet_end' => '23:45'])->assertHasErrors(['полночь']);
}
public function test_delete_event_withdraws_own_event(): void
{
$id = $this->createOwn();