Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
MCP: workspace settings, viewer read access, and token access (#241)
Paulo Castellano4d8353d75802
diff --git a/.agents/skills/infer-conventions/SKILL.md b/.agents/skills/infer-conventions/SKILL.mdnew file mode 100644index 000000000..11a932753--- /dev/null+++ b/.agents/skills/infer-conventions/SKILL.md@@ -0,0 +1,104 @@+---+name: infer-conventions+description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."+license: MIT+metadata:+ author: laravel+---++# Infer Conventions++Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it.++## Ground Rules (read before you start)++- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer.+- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record.+- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule.+- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering.+- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped.+- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar.+- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details.++## Process++Each step ends on a checkable completion criterion. Do not advance until it holds.++Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output.++### Step 0: Orient++Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2.++This app ships a frontend stack, so the frontend checklist group applies. Sweep it.++Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents.++### Step 1: Predefined sweep++Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:++- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files.+- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled.+- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention.+- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most).+- Tooling-owned or Already-recorded. Skip per the ground rules.++Done when: every applicable dimension carries exactly one of those verdicts.++### Step 2: Open-ended pass++First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude.++Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal.++Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none).++### Step 3: Confirm++Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style.++Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo.++Done when: every candidate is approved, rejected, or (conflicts) decided.++### Step 4: Record++Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand.++Record this:++> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models.++Not this:++> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models.++Done when: every approved item has a successful tool response, and any failure is reported with its rule text.++### Step 5: Summarize++List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions.++## Glob mapping++Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path.++Examples:++- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.+- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer.+- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses.+- Tests: `tests/**`.+- Migrations and database: `database/migrations/**`.+- Truly app-wide (rare, e.g. auth retrieval): `app/**`.++`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there.++## Edge cases++- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4.+- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing.+- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything.+- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface.+- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths.diff --git a/.agents/skills/infer-conventions/references/checklist.md b/.agents/skills/infer-conventions/references/checklist.mdnew file mode 100644index 000000000..f8d1b1441--- /dev/null+++ b/.agents/skills/infer-conventions/references/checklist.md@@ -0,0 +1,137 @@+# Detection Checklist++Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`).++Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence.++---++## A. Validation & HTTP input++1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.+ - Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`.+2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal.+ - Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`.+3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties.+ - Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.+4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.+ - Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`.++## B. Controllers & routing++5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.+ - Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes.+6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.+ - Hint: read a few controller methods; `ls app/Actions app/Services`.+7. Route handler style: closures in `routes/*.php` vs controller classes.+ - Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.+8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.+ - Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.+9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`.+ - Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`.+10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.+ - Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.++## C. Authorization++11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.+ - Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`.+12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade.+ - Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.++## D. Eloquent & models++13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.+ - Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.+14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain.+ - Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.+15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.+ - Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`.+16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings.+ - Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models.+17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`).+ - Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built.+18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.+ - Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`.+19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.+ - Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`.+20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture.+ - Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.++## E. Architecture & organization++21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked.+ - Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find.+22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.+ - Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`.+23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.+ - Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.+24. Decoupling: events + listeners vs direct service calls.+ - Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`.+25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).+ - Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.+26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).+ - Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.+27. Enums: backed vs pure; case naming; where they live.+ - Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`.++## F. Frontend & views++This app ships a frontend stack, so the items below apply.++28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA.+ - Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`.+29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.+ - Hint: `ls app/View/Components`; grep `<x-`, `@include` in `resources/views`.+32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).+ - Hint: `ls lang`; grep dotted `__('` vs sentence keys.++## G. Database & migrations++33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.+ - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.+34. `down()` methods: real reverse logic vs omitted / one-way migrations.+ - Hint: grep `function down` vs the migration count.+35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.+ - Hint: grep `->enum(` in migrations vs string columns cast to enums.+36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.+ - Hint: grep `DB::transaction`, `beginTransaction` in `app/`.+37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.+ - Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`.++## H. Testing++38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.+ - Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`.+39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.+ - Hint: grep those trait names in `tests/`.+40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories.+ - Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide.+41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery.+ - Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`.+42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.+ - Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.++## I. Responses & API resources++43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.+ - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.+44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately.+ - Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`.+45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority.+ - Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them.+46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`.+ - Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views.++## J. Strings, collections & dates++47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.+ - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.+48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).+ - Hint: grep `Str::of(` vs `Str::` vs native string funcs.+49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting.+ - Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy.++---++Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from.diff --git a/.agents/skills/laravel-best-practices/SKILL.md b/.agents/skills/laravel-best-practices/SKILL.mdindex 965e267e1..d136d7556 100644--- a/.agents/skills/laravel-best-practices/SKILL.md+++ b/.agents/skills/laravel-best-practices/SKILL.md@@ -8,183 +8,52 @@ metadata:# Laravel Best Practices-Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with `search-docs`.+Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.## Consistency First-Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.+Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.-Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.--## Quick Reference--### 1. Database Performance → `rules/db-performance.md`--- Eager load with `with()` to prevent N+1 queries-- Enable `Model::preventLazyLoading()` in development-- Select only needed columns, avoid `SELECT *`-- `chunk()` / `chunkById()` for large datasets-- Index columns used in `WHERE`, `ORDER BY`, `JOIN`-- `withCount()` instead of loading relations to count-- `cursor()` for memory-efficient read-only iteration-- Never query in Blade templates--### 2. Advanced Query Patterns → `rules/advanced-queries.md`--- `addSelect()` subqueries over eager-loading entire has-many for a single value-- Dynamic relationships via subquery FK + `belongsTo`-- Conditional aggregates (`CASE WHEN` in `selectRaw`) over multiple count queries-- `setRelation()` to prevent circular N+1 queries-- `whereIn` + `pluck()` over `whereHas` for better index usage-- Two simple queries can beat one complex query-- Compound indexes matching `orderBy` column order-- Correlated subqueries in `orderBy` for has-many sorting (avoid joins)--### 3. Security → `rules/security.md`--- Define `$fillable` or `$guarded` on every model, authorize every action via policies or gates-- No raw SQL with user input — use Eloquent or query builder-- `{{ }}` for output escaping, `@csrf` on all POST/PUT/DELETE forms, `throttle` on auth and API routes-- Validate MIME type, extension, and size for file uploads-- Never commit `.env`, use `config()` for secrets, `encrypted` cast for sensitive DB fields--### 4. Caching → `rules/caching.md`--- `Cache::remember()` over manual get/put-- `Cache::flexible()` for stale-while-revalidate on high-traffic data-- `Cache::memo()` to avoid redundant cache hits within a request-- Cache tags to invalidate related groups-- `Cache::add()` for atomic conditional writes-- `once()` to memoize per-request or per-object lifetime-- `Cache::lock()` / `lockForUpdate()` for race conditions-- Failover cache stores in production--### 5. Eloquent Patterns → `rules/eloquent.md`--- Correct relationship types with return type hints-- Local scopes for reusable query constraints-- Global scopes sparingly — document their existence-- Attribute casts in the `casts()` method-- Cast date columns, use Carbon instances in templates-- `whereBelongsTo($model)` for cleaner queries-- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries--### 6. Validation & Forms → `rules/validation.md`--- Form Request classes, not inline validation-- Array notation `['required', 'email']` for new code; follow existing convention-- `$request->validated()` only — never `$request->all()`-- `Rule::when()` for conditional validation-- `after()` instead of `withValidator()`--### 7. Configuration → `rules/config.md`--- `env()` only inside config files-- `App::environment()` or `app()->isProduction()`-- Config, lang files, and constants over hardcoded text--### 8. Testing Patterns → `rules/testing.md`--- `LazilyRefreshDatabase` over `RefreshDatabase` for speed-- `assertModelExists()` over raw `assertDatabaseHas()`-- Factory states and sequences over manual overrides-- Use fakes (`Event::fake()`, `Exceptions::fake()`, etc.) — but always after factory setup, not before-- `recycle()` to share relationship instances across factories--### 9. Queue & Job Patterns → `rules/queue-jobs.md`--- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`-- `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release-- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`-- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs-- Horizon for complex multi-queue scenarios--### 10. Routing & Controllers → `rules/routing.md`--- Implicit route model binding-- Scoped bindings for nested resources-- `Route::resource()` or `apiResource()`-- Methods under 10 lines — extract to actions/services-- Type-hint Form Requests for auto-validation--### 11. HTTP Client → `rules/http-client.md`--- Explicit `timeout` and `connectTimeout` on every request-- `retry()` with exponential backoff for external APIs-- Check response status or use `throw()`-- `Http::pool()` for concurrent independent requests-- `Http::fake()` and `preventStrayRequests()` in tests--### 12. Events, Notifications & Mail → `rules/events-notifications.md`, `rules/mail.md`--- Event discovery over manual registration; `event:cache` in production-- `ShouldDispatchAfterCommit` / `afterCommit()` inside transactions-- Queue notifications and mailables with `ShouldQueue`-- On-demand notifications for non-user recipients-- `HasLocalePreference` on notifiable models-- `assertQueued()` not `assertSent()` for queued mailables-- Markdown mailables for transactional emails--### 13. Error Handling → `rules/error-handling.md`--- `report()`/`render()` on exception classes or in `bootstrap/app.php` — follow existing pattern-- `ShouldntReport` for exceptions that should never log-- Throttle high-volume exceptions to protect log sinks-- `dontReportDuplicates()` for multi-catch scenarios-- Force JSON rendering for API routes-- Structured context via `context()` on exception classes--### 14. Task Scheduling → `rules/scheduling.md`--- `withoutOverlapping()` on variable-duration tasks-- `onOneServer()` on multi-server deployments-- `runInBackground()` for concurrent long tasks-- `environments()` to restrict to appropriate environments-- `takeUntilTimeout()` for time-bounded processing-- Schedule groups for shared configuration--### 15. Architecture → `rules/architecture.md`--- Single-purpose Action classes; dependency injection over `app()` helper-- Prefer official Laravel packages and follow conventions, don't override defaults-- Default to `ORDER BY id DESC` or `created_at DESC`; `mb_*` for UTF-8 safety-- `defer()` for post-response work; `Context` for request-scoped data; `Concurrency::run()` for parallel execution--### 16. Migrations → `rules/migrations.md`--- Generate migrations with `php artisan make:migration`-- `constrained()` for foreign keys-- Never modify migrations that have run in production-- Add indexes in the migration, not as an afterthought-- Mirror column defaults in model `$attributes`-- Reversible `down()` by default; forward-fix migrations for intentionally irreversible changes-- One concern per migration — never mix DDL and DML--### 17. Collections → `rules/collections.md`--- Higher-order messages for simple collection operations-- `cursor()` vs. `lazy()` — choose based on relationship needs-- `lazyById()` when updating records while iterating-- `toQuery()` for bulk operations on collections--### 18. Blade & Views → `rules/blade-views.md`--- `$attributes->merge()` in component templates-- Blade components over `@include`; `@pushOnce` for per-component scripts-- View Composers for shared view data-- `@aware` for deeply nested component props--### 19. Conventions & Style → `rules/style.md`--- Follow Laravel naming conventions for all entities-- Prefer Laravel helpers (`Str`, `Arr`, `Number`, `Uri`, `Str::of()`, `$request->string()`) over raw PHP functions-- No JS/CSS in Blade, no HTML in PHP classes-- Code should be readable; comments only for config files+Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.## How to Apply-Always use a sub-agent to read rule files and explore this skill's content.--1. Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)-2. Check sibling files for existing patterns — follow those first per Consistency First-3. Verify API syntax with `search-docs` for the installed Laravel version+1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.+2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.+3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.+4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable.+5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.+6. Re-read the diff against every mapped rule before finishing.++## Rule Index++Cross-cutting changes often need more than one rule file.++| Concern | Read |+| --- | --- |+| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) |+| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) |+| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) |+| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) |+| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) |+| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) |+| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) |+| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) |+| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) |+| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) |+| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) |+| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) |+| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) |+| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) |+| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) |+| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) |+| Environment values and application configuration | [`rules/config.md`](rules/config.md) |+| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) |+| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |+| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |++## Decision Rules++- Prefer framework features and existing application abstractions over new helpers or dependencies.+- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.+- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization.diff --git a/.agents/skills/laravel-best-practices/rules/architecture.md b/.agents/skills/laravel-best-practices/rules/architecture.mdindex 51c6e65dc..138d5a48d 100644--- a/.agents/skills/laravel-best-practices/rules/architecture.md+++ b/.agents/skills/laravel-best-practices/rules/architecture.md@@ -9,7 +9,7 @@ class CreateOrderAction{public function __construct(private InventoryService $inventory) {}- public function execute(array $data): Order+ public function handle(array $data): Order{$order = Order::create($data);$this->inventory->reserve($order);diff --git a/.agents/skills/laravel-best-practices/rules/eloquent.md b/.agents/skills/laravel-best-practices/rules/eloquent.mdindex 413d5da42..bd2cfca08 100644--- a/.agents/skills/laravel-best-practices/rules/eloquent.md+++ b/.agents/skills/laravel-best-practices/rules/eloquent.md@@ -30,7 +30,8 @@ $articles = Article::whereHas('user', function ($q) {Correct:```php-public function scopeActive(Builder $query): Builder+#[Scope]+protected function active(Builder $query): Builder{return $query->where('verified', true)->whereNotNull('activated_at');}@@ -58,7 +59,8 @@ class PublishedScope implements ScopeCorrect (local scope you opt into):```php-public function scopePublished(Builder $query): Builder+#[Scope]+protected function published(Builder $query): Builder{return $query->where('published', true);}diff --git a/.agents/skills/laravel-best-practices/rules/style.md b/.agents/skills/laravel-best-practices/rules/style.mdindex 64d173081..a8afb3695 100644--- a/.agents/skills/laravel-best-practices/rules/style.md+++ b/.agents/skills/laravel-best-practices/rules/style.md@@ -44,7 +44,7 @@ Strings — use `Str` and fluent `Str::of()` over raw PHP:// Incorrect$slug = strtolower(str_replace(' ', '-', $title));$short = substr($text, 0, 100) . '...';-$class = substr(strrchr('App\Models\User', '\'), 1);+$class = substr(strrchr('App\Models\User', '\\'), 1);// Correct$slug = Str::slug($title);diff --git a/.agents/skills/mcp-development/SKILL.md b/.agents/skills/mcp-development/SKILL.mdindex dcfb13004..4ef1bb9a6 100644--- a/.agents/skills/mcp-development/SKILL.md+++ b/.agents/skills/mcp-development/SKILL.md@@ -1,6 +1,6 @@---name: mcp-development-description: "Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP."+description: "Use this skill for Laravel MCP development. Trigger when creating or editing MCP tools, resources, prompts, servers, or UI apps in Laravel projects. Covers: artisan make:mcp-* generators, routes/ai.php, Tool/Resource/Prompt/AppResource classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, MCP debugging, MCP UI apps, the x-mcp::app Blade component, createMcpApp(), default AppResource handle() auto-infers view from class name, Response::view(), AppMeta/Csp/Permissions/appMeta() configuration, #[RendersApp] attribute, Library enum for CDN libraries (Tailwind, Alpine), and host theming via CSS variables. Use this whenever the user mentions MCP apps, MCP UI, interactive MCP resources, styling MCP apps with Tailwind or Alpine, or building visual interfaces for AI agents."license: MITmetadata:author: laravel@@ -12,6 +12,8 @@ metadata:Use `search-docs` for detailed Laravel MCP patterns and documentation.+For MCP UI apps (interactive HTML resources), read `references/app.md` — it covers the full architecture, host theming CSS variables, tool-to-UI linking patterns, library scripts (Tailwind, Alpine via `Library`), and real-world examples.+## Basic UsageRegister MCP servers in `routes/ai.php`:@@ -25,16 +27,16 @@ Mcp::web();### Creating MCP Primitives-Create MCP tools, resources, prompts, and servers using artisan commands:-```bash-php artisan make:mcp-tool ToolName # Create a tool+php artisan make:mcp-tool ToolName # Create a tool++php artisan make:mcp-resource ResourceName # Create a resource-php artisan make:mcp-resource ResourceName # Create a resource+php artisan make:mcp-prompt PromptName # Create a prompt-php artisan make:mcp-prompt PromptName # Create a prompt+php artisan make:mcp-server ServerName # Create a server-php artisan make:mcp-server ServerName # Create a server+php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)```@@ -44,23 +46,33 @@ After creating primitives, register them in your server's `$tools`, `$resources`<!-- MCP Tool Example -->```php+use Illuminate\Json\Schema\JsonSchema;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;use Laravel\Mcp\Server\Tool;-use Laravel\Mcp\Server\Request;-use Laravel\Mcp\Server\Response;class MyTool extends Tool{+ protected string $description = 'Describe what this tool does';++ public function schema(JsonSchema $schema): array+ {+ return [+ 'name' => $schema->string()->description('The name parameter')->required(),+ ];+ }+public function handle(Request $request): Response{- return new Response(['result' => 'success']);+ $request->validate(['name' => 'required|string']);++ return Response::text('Hello, '.$request->get('name'));}}```### Registering Primitives in a Server-Each MCP server must explicitly declare the tools, resources, and prompts it exposes.-<!-- Register Primitives in MCP Server -->```phpuse Laravel\Mcp\Server;@@ -81,6 +93,10 @@ class AppServer extends Server}```+## MCP UI Apps++For MCP UI apps, read `references/app.md` — it covers quick start examples, full architecture, AppMeta/Csp/Permissions, `#[RendersApp]` tool linking, library scripts (Tailwind/Alpine via `Library`), host theming CSS variables, and real-world patterns.+## Verification1. Check `routes/ai.php` for proper registration@@ -92,5 +108,5 @@ class AppServer extends Server- Using HTTPS locally with Node-based MCP clients- Not using `search-docs` for the latest MCP documentation- Not registering MCP server routes in `routes/ai.php`-- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.+- Do not register `ai.php` in `bootstrap.php`; it is registered automatically- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` configdiff --git a/.agents/skills/mcp-development/references/app.md b/.agents/skills/mcp-development/references/app.mdnew file mode 100644index 000000000..db2e752a3--- /dev/null+++ b/.agents/skills/mcp-development/references/app.md@@ -0,0 +1,940 @@+# MCP UI Apps Reference++## Quick Start++`make:mcp-app-resource DashboardApp` generates two files — a PHP registration stub and a Blade view. The entire app lives in the Blade view.++**PHP class** — renders the Blade view. The view name is auto-inferred from the class name (`mcp.<kebab-class-name>`), so the generated stub needs no changes unless you're passing additional server-side data:++```php+class DashboardApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.dashboard-app', [+ 'title' => $this->title(),+ ]);+ }+}+```++**Blade view** — HTML structure + inline JS, everything in one file:++```blade+<x-mcp::app title="Dashboard App">+ <x-slot:head>+ <script type="module">+ createMcpApp(async (app) => {+ document.getElementById('run-btn').addEventListener('click', async () => {+ const result = await app.callServerTool({ name: 'tool-name', arguments: {} });+ document.getElementById('output').textContent = result.content[0]?.text ?? '';+ });+ });+ </script>+ </x-slot:head>++ <div id="app">+ <h1>Dashboard App</h1>+ <button id="run-btn">Run</button>+ <p id="output"></p>+ </div>+</x-mcp::app>+```++`createMcpApp` is a global pre-bundled by the package — no npm install, no imports, no Vite required. It handles connection, error handling, and host theming automatically.++---++## Core Concept: Tool + Resource++Every MCP App is built from two parts linked together:++- **Tool** — called by the LLM or host. Returns a text/data response and tells the host which UI resource to render via `_meta.ui.resourceUri`.+- **AppResource** — serves the self-contained HTML app. The host fetches it after the tool is called and renders it in a sandboxed iframe.++```+LLM calls Tool+ └─► Tool response includes _meta.ui.resourceUri → "ui://dashboard-app"+ └─► Host fetches AppResource at that URI+ └─► Host renders HTML in sandboxed iframe+ └─► createMcpApp() connects the iframe back to the server+ └─► UI calls app-only tools to load/refresh data+```++The link is declared once with `#[RendersApp]` on the tool:++```php+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::text('Dashboard loaded.');+ }+}+```++After that, the host handles fetching and rendering the resource automatically — you never reference the URI by hand.++---++## Architecture Overview++MCP Apps add interactive UI to the Model Context Protocol. The server returns self-contained HTML with all JS/CSS inlined. The host renders it in a sandboxed iframe. Apps communicate back via `createMcpApp()` — a pre-bundled global implementing the MCP UI PostMessage protocol.++```+┌─────────────────────────────────────────────┐+│ Host (Claude, ChatGPT, VS Code) │+│ ┌───────────────────────────────────────┐ │+│ │ Sandboxed iframe │ │+│ │ ┌─────────────────────────────────┐ │ │+│ │ │ Your MCP App (HTML/JS/CSS) │ │ │+│ │ │ - Rendered by AppResource │ │ │+│ │ │ - Single self-contained HTML │ │ │+│ │ │ - Themed via host CSS vars │ │ │+│ │ └─────────────────────────────────┘ │ │+│ └───────────────────────────────────────┘ │+└──────────────────┬──────────────────────────┘+ │ MCP Protocol (JSON-RPC)+┌──────────────────▼──────────────────────────┐+│ Laravel MCP Server │+│ - AppResource → self-contained HTML │+│ - Tool #[RendersApp] → triggers UI display │+│ - resources/read → serves HTML + _meta.ui │+└─────────────────────────────────────────────┘+```++The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.++---++## Server-Side++Minimal case — `handle()` renders the Blade view, entire app lives there:++```php+class DashboardApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.dashboard-app', [+ 'title' => $this->title(),+ ]);+ }+}+```++Auto-renders `resources/views/mcp/dashboard-app.blade.php` with `$title` available via `$this->title()`.++Override `handle()` only when passing additional server-side data:++```php+class AnalyticsDashboard extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.analytics-dashboard', [+ 'title' => $this->title(),+ 'metrics' => Metric::latest()->take(10)->get(),+ 'totalUsers' => User::count(),+ ]);+ }+}+```++`Response::view($view, $data = [], $mergeData = [])` renders a Blade view and returns it as text.++`Response::html($path)` reads an HTML file from disk and returns its content. Relative paths resolve via `resource_path()`:++```php+class StaticApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::html('mcp/static-app.html');+ }+}+```++### AppMeta Configuration++The simplest way to configure UI metadata is via the `#[AppMeta]` attribute directly on your resource class:++```php+use Laravel\Mcp\Server\Attributes\AppMeta;+use Laravel\Mcp\Server\Ui\Enums\Library;+use Laravel\Mcp\Server\Ui\Enums\Permission;++#[AppMeta(+ connectDomains: ['https://api.stripe.com'],+ permissions: [Permission::Camera, Permission::ClipboardWrite],+ prefersBorder: true,+ libraries: [Library::Tailwind, Library::Alpine],+)]+class PaymentsResource extends AppResource+{+ // ...+}+```++For dynamic or computed configuration, override `appMeta()` instead:++```php+use Laravel\Mcp\Server\Ui\AppMeta;++public function appMeta(): AppMeta+{+ return AppMeta::make()+ ->csp(Csp::make()->connectDomains(config('services.api.domains')))+ ->permissions(Permissions::make()->allow(Permission::Camera))+ ->libraries(Library::Tailwind)+ ->domain('sandbox.example.com');+}+```++#### Permission Enum++Use the `Permission` enum for type-safe permission configuration:++```php+use Laravel\Mcp\Server\Ui\Enums\Permission;++Permission::Camera // 'camera'+Permission::Microphone // 'microphone'+Permission::Geolocation // 'geolocation'+Permission::ClipboardWrite // 'clipboardWrite'+```++#### Csp++Controls what external domains the iframe can access:++```php+Csp::make()+ ->connectDomains(['https://api.example.com']) // fetch, XHR, WebSocket origins+ ->resourceDomains(['https://cdn.example.com']) // images, scripts, fonts, media+ ->frameDomains(['https://embed.example.com']) // nested iframe origins+ ->baseUriDomains(['https://base.example.com']); // base URI origins+```++#### Permissions++```php+Permissions::make()->allow(Permission::Camera, Permission::ClipboardWrite);++Permissions::make()+ ->camera()+ ->microphone()+ ->geolocation()+ ->clipboardWrite();+```++Each enabled permission serializes as `"camera": {}` per the MCP spec.++#### AppMeta++```php+AppMeta::make()+ ->csp(Csp::make()->connectDomains([...]))+ ->permissions(Permissions::make()->allow(Permission::Camera))+ ->libraries(Library::Tailwind, Library::Alpine)+ ->domain('sandbox.example.com') // dedicated sandbox origin (OAuth/CORS)+ ->prefersBorder(false);+```++`prefersBorder` defaults to `true`. `toArray()` omits null fields and empty nested objects. Library CDN domains are automatically merged into `csp.resourceDomains`.++#### domain++The `domain` field provides a stable origin that external APIs can allowlist for CORS. It is automatically resolved from `config('app.url')` (your `APP_URL` env variable) via `resolvedAppMeta()`, so most apps need no configuration. Override only when a resource needs a different origin:++```php+#[AppMeta(domain: 'custom.example.com')]+class PaymentsResource extends AppResource+{+ // ...+}+```++#### Library Scripts++The `libraries` parameter adds pre-configured CDN scripts to the `<head>` of your app. Available libraries:++```php+use Laravel\Mcp\Server\Ui\Enums\Library;++Library::Tailwind // Tailwind CSS CDN + dark mode config+Library::Alpine // Alpine.js CDN + x-cloak style+```++When libraries are specified, the package automatically:++1. Injects the CDN `<script>` tags into the Blade view's `<head>` (after the MCP SDK, before your `<x-slot:head>`)+2. Merges each library's CDN domains into `csp.resourceDomains` so the host allows loading them++Via attribute:++```php+#[AppMeta(libraries: [Library::Tailwind])]+class StyledApp extends AppResource+{+ // Tailwind is available in the Blade view — no extra setup+}+```++Via fluent builder:++```php+public function appMeta(): AppMeta+{+ return AppMeta::make()+ ->libraries(Library::Tailwind, Library::Alpine);+}+```++---++## View Layer++### `<x-mcp::app>` Blade Component++Renders a complete self-contained HTML document with the MCP SDK inlined. `createMcpApp` is available globally.++```blade+<x-mcp::app title="Dashboard App">+ <x-slot:head>+ <script type="module">+ createMcpApp(async (app) => {+ document.getElementById('run-btn').addEventListener('click', async () => {+ const result = await app.callServerTool({ name: 'tool-name', arguments: {} });+ document.getElementById('output').textContent = result.content[0]?.text ?? '';+ });+ });+ </script>+ </x-slot:head>++ <div id="app">+ <button id="run-btn">Run</button>+ <p id="output"></p>+ </div>+</x-mcp::app>+```++**Props and slots:**++| Name | Type | Description |+| ------------- | ------------- | ---------------------------------------------------- |+| `title` | Prop | Sets `<title>`. Optional. |+| `head` | Named slot | Injected into `<head>` after the inlined SDK script. |+| Default slot | Slot | Body content. |+| `$attributes` | Attribute bag | Forwarded to `<body>` (e.g. `class="dark"`). |++The SDK is loaded from the `mcp.sdk` singleton (registered by `McpServiceProvider`) and inlined directly in a `<script>` tag. Library scripts (Tailwind, Alpine) configured via `#[AppMeta]` are injected after the SDK and before the `head` slot.++Publish the component: `php artisan vendor:publish --tag=mcp-views`.++To pass server-side data to JS, embed it as `data-*` attributes:++```blade+<div id="app" data-users="{{ $users->toJson() }}">+ ...+</div>+```++```js+const users = JSON.parse(document.getElementById("app").dataset.users);+```++## Client-Side++This package provides a simple MCP client library to easily work with client interactions.++### createMcpApp++Pre-bundled and inlined automatically — no npm install or imports required.++```js+createMcpApp(async (app) => {+ // app is ready — connection established, theming applied+});+```++### Tools++#### app.callServerTool()++Accepts an object or positional arguments:++```js+// Object form+const result = await app.callServerTool({ name: 'get-analytics', arguments: { dateRange: '7d' } });++// Positional form+const result = await app.callServerTool('get-analytics', { dateRange: '7d' });++// result structure depends on the server's tool response+const text = result.content[0]?.text ?? "";+```++All tool results share a standard structure:++| Property | Type | Description |+| --------- | --------- | ------------------------------------------------------------------------- |+| `content` | `Array` | Content items returned by the tool (each has `type` and `text` or `data`) |+| `isError` | `boolean` | `true` when the tool returned an error response |++Always check `result.isError` before consuming `content`. See [Error Handling](#error-handling) for a full example.++### Resources++#### app.listResources()++```js+const resources = await app.listResources();+// or with cursor for pagination+const resources = await app.listResources("cursor-value");+// or object form+const resources = await app.listResources({ cursor: "cursor-value" });+```++#### app.readResource()++```js+const resource = await app.readResource("ui://my-resource");+// or object form+const resource = await app.readResource({ uri: "ui://my-resource" });+```++### Messaging++#### app.sendMessage()++Send a message to the model (creates a conversation turn):++```js+// Object form with structured content+await app.sendMessage({+ role: "user",+ content: [{ type: "text", text: "User submitted the form." }],+});++// Shorthand — plain string content with optional role (defaults to 'user')+await app.sendMessage("User submitted the form.");+await app.sendMessage("System event occurred.", "user");+```++### Host Context++#### app.getHostContext()++Returns the current host context, including theme and style variables:++```js+const ctx = app.getHostContext();+ctx?.theme; // 'light' | 'dark'+ctx?.styles?.variables; // CSS variable map from host+ctx?.styles?.css?.fonts; // font CSS from host+```++#### app.getHostInfo()++```js+const info = app.getHostInfo();+```++#### app.getHostCapabilities()++```js+const caps = app.getHostCapabilities();+```++### Navigation & Files++#### app.openLink()++```js+await app.openLink("https://example.com");+// or object form+await app.openLink({ url: "https://example.com" });+```++#### app.downloadFile()++```js+await app.downloadFile("file contents here");+// or object form+await app.downloadFile({ contents: "file contents here" });+```++### Display++#### app.requestDisplayMode()++```js+await app.requestDisplayMode("fullscreen");+// or object form+await app.requestDisplayMode({ mode: "fullscreen" });+```++#### app.resize() / app.autoResize()++`resize()` sends a one-time size notification. `autoResize()` uses `ResizeObserver` to continuously notify the host of size changes. It returns a cleanup function that disconnects the observer — useful if you need to stop observing before teardown. The observer is also automatically disconnected on teardown.++```js+const stopObserving = app.autoResize();++// Later, if needed:+stopObserving();+```++### Model Context++#### app.updateModelContext()++```js+await app.updateModelContext({ key: "value" });+```++### Lifecycle++#### app.requestTeardown()++Sends a teardown notification to the host.++```js+app.requestTeardown();+```++### Logging++#### app.sendLog()++```js+// Positional form+await app.sendLog("info", "Processing started", "my-logger");++// Object form+await app.sendLog({+ level: "info",+ data: "Processing started",+ logger: "my-logger",+});+```++### Event Handlers++Register callbacks for host-side events. Tool input/result/cancelled events are queued until a handler is registered, then flushed.++```js+createMcpApp(async (app) => {+ app.onToolInput((params) => {+ /* tool input received */+ });+ app.onToolInputPartial((params) => {+ /* partial tool input */+ });+ app.onToolResult((params) => {+ /* tool result received */+ });+ app.onToolCancelled((params) => {+ /* tool was cancelled */+ });+ app.onHostContextChanged((ctx) => {+ /* theme/styles changed */+ });+ app.onTeardown(async () => {+ /* cleanup before teardown */+ });+ app.onCallTool(async (params) => {+ /* host requests tool call */+ });+ app.onListTools(async (params) => {+ /* host requests tool list */+ });+});+```++---++## Host Theming++`createMcpApp` automatically applies host theming on connect and on context change:++- Sets `data-theme` attribute and `color-scheme` on `<html>`+- Applies CSS variables from `hostContext.styles.variables` to `:root`+- Injects font CSS from `hostContext.styles.css.fonts` into a `<style>` tag++The specific CSS variables available depend on the host. Always provide fallback values — use `light-dark()` for theme-aware defaults:++```css+:root {+ --color-background-primary: light-dark(#ffffff, #171717);+ --color-text-primary: light-dark(#171717, #fafafa);+ --color-text-secondary: light-dark(#525252, #a3a3a3);+ --color-border-primary: light-dark(#e5e5e5, #404040);+ --font-sans: system-ui, -apple-system, sans-serif;+ --border-radius-md: 8px;+}++body {+ font-family: var(--font-sans);+ background: var(--color-background-primary);+ color: var(--color-text-primary);+ margin: 0;+}++.card {+ background: var(--color-background-secondary);+ border: 1px solid var(--color-border-primary);+ border-radius: var(--border-radius-md);+ padding: 1rem;+}+```++---++## Tool-to-UI Linking++### #[RendersApp] Attribute++Associates a Tool with a UI Resource. When the tool is called, the host fetches and renders the linked resource.++```php+use Laravel\Mcp\Server\Attributes\RendersApp;+use Laravel\Mcp\Server\Ui\Enums\Visibility;++// Both model and app can call this tool (default)+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool { ... }++// Only the app can call this tool (private to the UI)+#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]+class RefreshDashboardData extends Tool { ... }+```++**Visibility:**++The `Visibility` enum (`Laravel\Mcp\Server\Ui\Enums\Visibility`) has two cases: `Model` and `App`. The default is `[Visibility::Model, Visibility::App]`.++| Visibility | Model | App | Use case |+| -------------------------------------- | ----- | --- | ------------------------------------------------------ |+| `[Visibility::Model, Visibility::App]` | Yes | Yes | Primary tools that trigger UI display |+| `[Visibility::App]` | No | Yes | Backend actions the UI calls (refresh, save, paginate) |+| `[Visibility::Model]` | Yes | No | Model-only tools linked to a UI |++### Primary + Private Pattern++```php+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::text('Dashboard loaded.');+ }+}++#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]+class GetDashboardMetrics extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::json(Metric::latest()->take(50)->get());+ }+}+```++---++## Testing++```php+it('returns html content', function () {+ MyServer::readResource(DashboardApp::class)+ ->assertSee('<div id="app">');+});++it('has correct mime type and uri scheme', function () {+ $resource = new DashboardApp;+ $data = $resource->toArray();++ expect($data['mimeType'])->toBe('text/html;profile=mcp-app')+ ->and($data['_meta']['ui'])->toBeArray()+ ->and($resource->uri())->toStartWith('ui://');+});++it('configures ui meta correctly', function () {+ $meta = (new DashboardApp)->resolvedAppMeta();++ expect($meta['csp']['connectDomains'])->toContain('https://api.example.com')+ ->and($meta['permissions'])->toHaveKey('clipboardWrite');+});++it('includes ui metadata in tool listing', function () {+ MyServer::listTools()->assertSee('show-dashboard');+});+```++---++## Patterns++### Real-time Polling++Use app-only tools to fetch fresh data at regular intervals from the UI:++```php+#[RendersApp(resource: MonitorApp::class, visibility: [Visibility::App])]+class GetMonitorData extends Tool+{+ protected string $description = 'Fetch latest monitor metrics';++ public function handle(Request $request): Response+ {+ return Response::json([+ 'cpu' => sys_getloadavg()[0],+ 'memory' => memory_get_usage(true),+ 'timestamp' => now()->toISOString(),+ ]);+ }+}+```++```js+createMcpApp(async (app) => {+ async function poll() {+ const result = await app.callServerTool('get-monitor-data');+ const data = JSON.parse(result.content[0]?.text ?? '{}');+ document.getElementById('cpu').textContent = data.cpu;+ }++ setInterval(poll, 2000);+ poll();+});+```++### Chunked Data Loading++For large datasets, implement pagination via app-only tools:++```php+#[RendersApp(resource: LogViewerApp::class, visibility: [Visibility::App])]+class GetLogChunk extends Tool+{+ protected string $description = 'Fetch a chunk of log entries';++ public function schema(JsonSchema $schema): array+ {+ return [+ 'offset' => $schema->integer()->description('Byte offset to start from')->required(),+ 'limit' => $schema->integer()->description('Max bytes to return'),+ ];+ }++ public function handle(Request $request): Response+ {+ $request->validate(['offset' => 'required|integer', 'limit' => 'integer']);++ $offset = $request->get('offset');+ $limit = $request->get('limit', 500_000);+ $content = Storage::get('logs/app.log');+ $chunk = substr($content, $offset, $limit);++ return Response::json([+ 'data' => $chunk,+ 'offset' => $offset,+ 'totalBytes' => strlen($content),+ 'hasMore' => ($offset + $limit) < strlen($content),+ ]);+ }+}+```++### Binary Resource Serving++Deliver images and binary content through MCP resources using `Response::blob()`:++```php+#[RendersApp(resource: GalleryApp::class, visibility: [Visibility::App])]+class GetImage extends Tool+{+ protected string $description = 'Fetch an image by ID';++ public function handle(Request $request): Response+ {+ $request->validate(['id' => 'required|integer']);++ $image = Image::findOrFail($request->get('id'));+ $data = base64_encode(Storage::get($image->path));++ return Response::blob($data);+ }+}+```++In the client, convert the base64 blob to a data URI for rendering:++```js+const result = await app.callServerTool('get-image', { id: 42 });+const blob = result.content[0];+img.src = `data:${blob.mimeType};base64,${blob.data}`;+```++### Streaming Argument Previews++Use `onToolInputPartial` to show previews as the model streams tool arguments:++```js+createMcpApp(async (app) => {+ app.onToolInputPartial((params) => {+ try {+ const partial = JSON.parse(params.arguments);+ if (partial.query) {+ document.getElementById("preview").textContent = partial.query;+ }+ } catch {+ // partial JSON — ignore until parseable+ }+ });++ app.onToolResult((params) => {+ const data = JSON.parse(params.result.content[0]?.text ?? "{}");+ renderResults(data);+ });+});+```++### View State Persistence++Use `localStorage` to preserve UI state across re-renders. For important state, persist server-side via an app-only tool:++```js+createMcpApp(async (app) => {+ const STATE_KEY = "dashboard-view-state";++ // Restore from localStorage+ const saved = JSON.parse(localStorage.getItem(STATE_KEY) || "{}");+ if (saved.activeTab) selectTab(saved.activeTab);++ // Save on interaction+ function saveState(state) {+ localStorage.setItem(STATE_KEY, JSON.stringify(state));+ }++ // For durable state, persist server-side+ async function saveServerState(state) {+ await app.callServerTool('save-dashboard-state', { state: JSON.stringify(state) });+ }+});+```++### Fullscreen Toggling++Switch between inline and fullscreen display modes and react to mode changes:++```js+createMcpApp(async (app) => {+ document.getElementById("expand-btn").addEventListener("click", () => {+ app.requestDisplayMode("fullscreen");+ });++ app.onHostContextChanged((ctx) => {+ document.body.classList.toggle(+ "fullscreen",+ ctx.displayMode === "fullscreen",+ );+ });+});+```++### Model Context Updates++Keep the model informed about what the user is viewing so it can provide relevant assistance:++```js+createMcpApp(async (app) => {+ async function notifyContext(view, detail) {+ await app.updateModelContext({+ currentView: view,+ detail: detail,+ });+ }++ // Notify on tab change+ document.querySelectorAll(".tab").forEach((tab) => {+ tab.addEventListener("click", () => {+ notifyContext(tab.dataset.view, { filters: getActiveFilters() });+ });+ });++ // For large payloads, follow up with sendMessage+ await app.updateModelContext({ currentView: "report", rows: 5000 });+ await app.sendMessage("The user is viewing a report with 5000 rows.");+});+```++### Pause Offscreen Views++Conserve resources by pausing animations and polling when the view is not visible:++```js+createMcpApp(async (app) => {+ let pollInterval = null;++ function startPolling() {+ if (!pollInterval) {+ pollInterval = setInterval(fetchData, 2000);+ }+ }++ function stopPolling() {+ clearInterval(pollInterval);+ pollInterval = null;+ }++ const observer = new IntersectionObserver(([entry]) => {+ entry.isIntersecting ? startPolling() : stopPolling();+ });++ observer.observe(document.documentElement);+ startPolling();+});+```++### Error Handling++Return `Response::error()` from tools and use `updateModelContext()` to signal degraded state:++```php+class ProcessData extends Tool+{+ public function handle(Request $request): Response+ {+ $request->validate(['input' => 'required|string']);++ if (strlen($request->get('input')) > 10_000) {+ return Response::error('Input exceeds 10KB limit.');+ }++ return Response::json(process($request->get('input')));+ }+}+```++```js+createMcpApp(async (app) => {+ const result = await app.callServerTool('process-data', { input: value });++ if (result.isError) {+ document.getElementById("error").textContent =+ result.content[0]?.text ?? "Unknown error";+ await app.updateModelContext({+ state: "error",+ message: result.content[0]?.text,+ });+ return;+ }++ renderOutput(JSON.parse(result.content[0]?.text ?? "{}"));+});+```diff --git a/.claude/skills/infer-conventions/SKILL.md b/.claude/skills/infer-conventions/SKILL.mdnew file mode 100644index 000000000..11a932753--- /dev/null+++ b/.claude/skills/infer-conventions/SKILL.md@@ -0,0 +1,104 @@+---+name: infer-conventions+description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."+license: MIT+metadata:+ author: laravel+---++# Infer Conventions++Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it.++## Ground Rules (read before you start)++- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer.+- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record.+- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule.+- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering.+- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped.+- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar.+- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details.++## Process++Each step ends on a checkable completion criterion. Do not advance until it holds.++Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output.++### Step 0: Orient++Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2.++This app ships a frontend stack, so the frontend checklist group applies. Sweep it.++Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents.++### Step 1: Predefined sweep++Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:++- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files.+- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled.+- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention.+- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most).+- Tooling-owned or Already-recorded. Skip per the ground rules.++Done when: every applicable dimension carries exactly one of those verdicts.++### Step 2: Open-ended pass++First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude.++Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal.++Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none).++### Step 3: Confirm++Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style.++Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo.++Done when: every candidate is approved, rejected, or (conflicts) decided.++### Step 4: Record++Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand.++Record this:++> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models.++Not this:++> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models.++Done when: every approved item has a successful tool response, and any failure is reported with its rule text.++### Step 5: Summarize++List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions.++## Glob mapping++Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path.++Examples:++- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.+- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer.+- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses.+- Tests: `tests/**`.+- Migrations and database: `database/migrations/**`.+- Truly app-wide (rare, e.g. auth retrieval): `app/**`.++`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there.++## Edge cases++- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4.+- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing.+- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything.+- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface.+- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths.diff --git a/.claude/skills/infer-conventions/references/checklist.md b/.claude/skills/infer-conventions/references/checklist.mdnew file mode 100644index 000000000..f8d1b1441--- /dev/null+++ b/.claude/skills/infer-conventions/references/checklist.md@@ -0,0 +1,137 @@+# Detection Checklist++Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`).++Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence.++---++## A. Validation & HTTP input++1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.+ - Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`.+2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal.+ - Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`.+3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties.+ - Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.+4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.+ - Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`.++## B. Controllers & routing++5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.+ - Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes.+6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.+ - Hint: read a few controller methods; `ls app/Actions app/Services`.+7. Route handler style: closures in `routes/*.php` vs controller classes.+ - Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.+8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.+ - Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.+9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`.+ - Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`.+10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.+ - Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.++## C. Authorization++11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.+ - Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`.+12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade.+ - Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.++## D. Eloquent & models++13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.+ - Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.+14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain.+ - Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.+15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.+ - Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`.+16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings.+ - Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models.+17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`).+ - Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built.+18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.+ - Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`.+19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.+ - Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`.+20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture.+ - Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.++## E. Architecture & organization++21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked.+ - Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find.+22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.+ - Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`.+23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.+ - Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.+24. Decoupling: events + listeners vs direct service calls.+ - Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`.+25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).+ - Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.+26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).+ - Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.+27. Enums: backed vs pure; case naming; where they live.+ - Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`.++## F. Frontend & views++This app ships a frontend stack, so the items below apply.++28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA.+ - Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`.+29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.+ - Hint: `ls app/View/Components`; grep `<x-`, `@include` in `resources/views`.+32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).+ - Hint: `ls lang`; grep dotted `__('` vs sentence keys.++## G. Database & migrations++33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.+ - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.+34. `down()` methods: real reverse logic vs omitted / one-way migrations.+ - Hint: grep `function down` vs the migration count.+35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.+ - Hint: grep `->enum(` in migrations vs string columns cast to enums.+36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.+ - Hint: grep `DB::transaction`, `beginTransaction` in `app/`.+37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.+ - Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`.++## H. Testing++38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.+ - Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`.+39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.+ - Hint: grep those trait names in `tests/`.+40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories.+ - Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide.+41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery.+ - Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`.+42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.+ - Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.++## I. Responses & API resources++43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.+ - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.+44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately.+ - Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`.+45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority.+ - Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them.+46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`.+ - Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views.++## J. Strings, collections & dates++47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.+ - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.+48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).+ - Hint: grep `Str::of(` vs `Str::` vs native string funcs.+49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting.+ - Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy.++---++Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from.diff --git a/.claude/skills/laravel-best-practices/SKILL.md b/.claude/skills/laravel-best-practices/SKILL.mdindex 965e267e1..d136d7556 100644--- a/.claude/skills/laravel-best-practices/SKILL.md+++ b/.claude/skills/laravel-best-practices/SKILL.md@@ -8,183 +8,52 @@ metadata:# Laravel Best Practices-Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with `search-docs`.+Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.## Consistency First-Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.+Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.-Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.--## Quick Reference--### 1. Database Performance → `rules/db-performance.md`--- Eager load with `with()` to prevent N+1 queries-- Enable `Model::preventLazyLoading()` in development-- Select only needed columns, avoid `SELECT *`-- `chunk()` / `chunkById()` for large datasets-- Index columns used in `WHERE`, `ORDER BY`, `JOIN`-- `withCount()` instead of loading relations to count-- `cursor()` for memory-efficient read-only iteration-- Never query in Blade templates--### 2. Advanced Query Patterns → `rules/advanced-queries.md`--- `addSelect()` subqueries over eager-loading entire has-many for a single value-- Dynamic relationships via subquery FK + `belongsTo`-- Conditional aggregates (`CASE WHEN` in `selectRaw`) over multiple count queries-- `setRelation()` to prevent circular N+1 queries-- `whereIn` + `pluck()` over `whereHas` for better index usage-- Two simple queries can beat one complex query-- Compound indexes matching `orderBy` column order-- Correlated subqueries in `orderBy` for has-many sorting (avoid joins)--### 3. Security → `rules/security.md`--- Define `$fillable` or `$guarded` on every model, authorize every action via policies or gates-- No raw SQL with user input — use Eloquent or query builder-- `{{ }}` for output escaping, `@csrf` on all POST/PUT/DELETE forms, `throttle` on auth and API routes-- Validate MIME type, extension, and size for file uploads-- Never commit `.env`, use `config()` for secrets, `encrypted` cast for sensitive DB fields--### 4. Caching → `rules/caching.md`--- `Cache::remember()` over manual get/put-- `Cache::flexible()` for stale-while-revalidate on high-traffic data-- `Cache::memo()` to avoid redundant cache hits within a request-- Cache tags to invalidate related groups-- `Cache::add()` for atomic conditional writes-- `once()` to memoize per-request or per-object lifetime-- `Cache::lock()` / `lockForUpdate()` for race conditions-- Failover cache stores in production--### 5. Eloquent Patterns → `rules/eloquent.md`--- Correct relationship types with return type hints-- Local scopes for reusable query constraints-- Global scopes sparingly — document their existence-- Attribute casts in the `casts()` method-- Cast date columns, use Carbon instances in templates-- `whereBelongsTo($model)` for cleaner queries-- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries--### 6. Validation & Forms → `rules/validation.md`--- Form Request classes, not inline validation-- Array notation `['required', 'email']` for new code; follow existing convention-- `$request->validated()` only — never `$request->all()`-- `Rule::when()` for conditional validation-- `after()` instead of `withValidator()`--### 7. Configuration → `rules/config.md`--- `env()` only inside config files-- `App::environment()` or `app()->isProduction()`-- Config, lang files, and constants over hardcoded text--### 8. Testing Patterns → `rules/testing.md`--- `LazilyRefreshDatabase` over `RefreshDatabase` for speed-- `assertModelExists()` over raw `assertDatabaseHas()`-- Factory states and sequences over manual overrides-- Use fakes (`Event::fake()`, `Exceptions::fake()`, etc.) — but always after factory setup, not before-- `recycle()` to share relationship instances across factories--### 9. Queue & Job Patterns → `rules/queue-jobs.md`--- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`-- `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release-- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`-- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs-- Horizon for complex multi-queue scenarios--### 10. Routing & Controllers → `rules/routing.md`--- Implicit route model binding-- Scoped bindings for nested resources-- `Route::resource()` or `apiResource()`-- Methods under 10 lines — extract to actions/services-- Type-hint Form Requests for auto-validation--### 11. HTTP Client → `rules/http-client.md`--- Explicit `timeout` and `connectTimeout` on every request-- `retry()` with exponential backoff for external APIs-- Check response status or use `throw()`-- `Http::pool()` for concurrent independent requests-- `Http::fake()` and `preventStrayRequests()` in tests--### 12. Events, Notifications & Mail → `rules/events-notifications.md`, `rules/mail.md`--- Event discovery over manual registration; `event:cache` in production-- `ShouldDispatchAfterCommit` / `afterCommit()` inside transactions-- Queue notifications and mailables with `ShouldQueue`-- On-demand notifications for non-user recipients-- `HasLocalePreference` on notifiable models-- `assertQueued()` not `assertSent()` for queued mailables-- Markdown mailables for transactional emails--### 13. Error Handling → `rules/error-handling.md`--- `report()`/`render()` on exception classes or in `bootstrap/app.php` — follow existing pattern-- `ShouldntReport` for exceptions that should never log-- Throttle high-volume exceptions to protect log sinks-- `dontReportDuplicates()` for multi-catch scenarios-- Force JSON rendering for API routes-- Structured context via `context()` on exception classes--### 14. Task Scheduling → `rules/scheduling.md`--- `withoutOverlapping()` on variable-duration tasks-- `onOneServer()` on multi-server deployments-- `runInBackground()` for concurrent long tasks-- `environments()` to restrict to appropriate environments-- `takeUntilTimeout()` for time-bounded processing-- Schedule groups for shared configuration--### 15. Architecture → `rules/architecture.md`--- Single-purpose Action classes; dependency injection over `app()` helper-- Prefer official Laravel packages and follow conventions, don't override defaults-- Default to `ORDER BY id DESC` or `created_at DESC`; `mb_*` for UTF-8 safety-- `defer()` for post-response work; `Context` for request-scoped data; `Concurrency::run()` for parallel execution--### 16. Migrations → `rules/migrations.md`--- Generate migrations with `php artisan make:migration`-- `constrained()` for foreign keys-- Never modify migrations that have run in production-- Add indexes in the migration, not as an afterthought-- Mirror column defaults in model `$attributes`-- Reversible `down()` by default; forward-fix migrations for intentionally irreversible changes-- One concern per migration — never mix DDL and DML--### 17. Collections → `rules/collections.md`--- Higher-order messages for simple collection operations-- `cursor()` vs. `lazy()` — choose based on relationship needs-- `lazyById()` when updating records while iterating-- `toQuery()` for bulk operations on collections--### 18. Blade & Views → `rules/blade-views.md`--- `$attributes->merge()` in component templates-- Blade components over `@include`; `@pushOnce` for per-component scripts-- View Composers for shared view data-- `@aware` for deeply nested component props--### 19. Conventions & Style → `rules/style.md`--- Follow Laravel naming conventions for all entities-- Prefer Laravel helpers (`Str`, `Arr`, `Number`, `Uri`, `Str::of()`, `$request->string()`) over raw PHP functions-- No JS/CSS in Blade, no HTML in PHP classes-- Code should be readable; comments only for config files+Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.## How to Apply-Always use a sub-agent to read rule files and explore this skill's content.--1. Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)-2. Check sibling files for existing patterns — follow those first per Consistency First-3. Verify API syntax with `search-docs` for the installed Laravel version+1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.+2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.+3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.+4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable.+5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.+6. Re-read the diff against every mapped rule before finishing.++## Rule Index++Cross-cutting changes often need more than one rule file.++| Concern | Read |+| --- | --- |+| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) |+| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) |+| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) |+| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) |+| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) |+| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) |+| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) |+| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) |+| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) |+| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) |+| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) |+| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) |+| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) |+| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) |+| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) |+| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) |+| Environment values and application configuration | [`rules/config.md`](rules/config.md) |+| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) |+| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |+| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |++## Decision Rules++- Prefer framework features and existing application abstractions over new helpers or dependencies.+- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.+- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization.diff --git a/.claude/skills/laravel-best-practices/rules/architecture.md b/.claude/skills/laravel-best-practices/rules/architecture.mdindex 51c6e65dc..138d5a48d 100644--- a/.claude/skills/laravel-best-practices/rules/architecture.md+++ b/.claude/skills/laravel-best-practices/rules/architecture.md@@ -9,7 +9,7 @@ class CreateOrderAction{public function __construct(private InventoryService $inventory) {}- public function execute(array $data): Order+ public function handle(array $data): Order{$order = Order::create($data);$this->inventory->reserve($order);diff --git a/.claude/skills/laravel-best-practices/rules/eloquent.md b/.claude/skills/laravel-best-practices/rules/eloquent.mdindex 413d5da42..bd2cfca08 100644--- a/.claude/skills/laravel-best-practices/rules/eloquent.md+++ b/.claude/skills/laravel-best-practices/rules/eloquent.md@@ -30,7 +30,8 @@ $articles = Article::whereHas('user', function ($q) {Correct:```php-public function scopeActive(Builder $query): Builder+#[Scope]+protected function active(Builder $query): Builder{return $query->where('verified', true)->whereNotNull('activated_at');}@@ -58,7 +59,8 @@ class PublishedScope implements ScopeCorrect (local scope you opt into):```php-public function scopePublished(Builder $query): Builder+#[Scope]+protected function published(Builder $query): Builder{return $query->where('published', true);}diff --git a/.claude/skills/laravel-best-practices/rules/style.md b/.claude/skills/laravel-best-practices/rules/style.mdindex 64d173081..a8afb3695 100644--- a/.claude/skills/laravel-best-practices/rules/style.md+++ b/.claude/skills/laravel-best-practices/rules/style.md@@ -44,7 +44,7 @@ Strings — use `Str` and fluent `Str::of()` over raw PHP:// Incorrect$slug = strtolower(str_replace(' ', '-', $title));$short = substr($text, 0, 100) . '...';-$class = substr(strrchr('App\Models\User', '\'), 1);+$class = substr(strrchr('App\Models\User', '\\'), 1);// Correct$slug = Str::slug($title);diff --git a/.claude/skills/mcp-development/SKILL.md b/.claude/skills/mcp-development/SKILL.mdindex dcfb13004..4ef1bb9a6 100644--- a/.claude/skills/mcp-development/SKILL.md+++ b/.claude/skills/mcp-development/SKILL.md@@ -1,6 +1,6 @@---name: mcp-development-description: "Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP."+description: "Use this skill for Laravel MCP development. Trigger when creating or editing MCP tools, resources, prompts, servers, or UI apps in Laravel projects. Covers: artisan make:mcp-* generators, routes/ai.php, Tool/Resource/Prompt/AppResource classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, MCP debugging, MCP UI apps, the x-mcp::app Blade component, createMcpApp(), default AppResource handle() auto-infers view from class name, Response::view(), AppMeta/Csp/Permissions/appMeta() configuration, #[RendersApp] attribute, Library enum for CDN libraries (Tailwind, Alpine), and host theming via CSS variables. Use this whenever the user mentions MCP apps, MCP UI, interactive MCP resources, styling MCP apps with Tailwind or Alpine, or building visual interfaces for AI agents."license: MITmetadata:author: laravel@@ -12,6 +12,8 @@ metadata:Use `search-docs` for detailed Laravel MCP patterns and documentation.+For MCP UI apps (interactive HTML resources), read `references/app.md` — it covers the full architecture, host theming CSS variables, tool-to-UI linking patterns, library scripts (Tailwind, Alpine via `Library`), and real-world examples.+## Basic UsageRegister MCP servers in `routes/ai.php`:@@ -25,16 +27,16 @@ Mcp::web();### Creating MCP Primitives-Create MCP tools, resources, prompts, and servers using artisan commands:-```bash-php artisan make:mcp-tool ToolName # Create a tool+php artisan make:mcp-tool ToolName # Create a tool++php artisan make:mcp-resource ResourceName # Create a resource-php artisan make:mcp-resource ResourceName # Create a resource+php artisan make:mcp-prompt PromptName # Create a prompt-php artisan make:mcp-prompt PromptName # Create a prompt+php artisan make:mcp-server ServerName # Create a server-php artisan make:mcp-server ServerName # Create a server+php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)```@@ -44,23 +46,33 @@ After creating primitives, register them in your server's `$tools`, `$resources`<!-- MCP Tool Example -->```php+use Illuminate\Json\Schema\JsonSchema;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;use Laravel\Mcp\Server\Tool;-use Laravel\Mcp\Server\Request;-use Laravel\Mcp\Server\Response;class MyTool extends Tool{+ protected string $description = 'Describe what this tool does';++ public function schema(JsonSchema $schema): array+ {+ return [+ 'name' => $schema->string()->description('The name parameter')->required(),+ ];+ }+public function handle(Request $request): Response{- return new Response(['result' => 'success']);+ $request->validate(['name' => 'required|string']);++ return Response::text('Hello, '.$request->get('name'));}}```### Registering Primitives in a Server-Each MCP server must explicitly declare the tools, resources, and prompts it exposes.-<!-- Register Primitives in MCP Server -->```phpuse Laravel\Mcp\Server;@@ -81,6 +93,10 @@ class AppServer extends Server}```+## MCP UI Apps++For MCP UI apps, read `references/app.md` — it covers quick start examples, full architecture, AppMeta/Csp/Permissions, `#[RendersApp]` tool linking, library scripts (Tailwind/Alpine via `Library`), host theming CSS variables, and real-world patterns.+## Verification1. Check `routes/ai.php` for proper registration@@ -92,5 +108,5 @@ class AppServer extends Server- Using HTTPS locally with Node-based MCP clients- Not using `search-docs` for the latest MCP documentation- Not registering MCP server routes in `routes/ai.php`-- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.+- Do not register `ai.php` in `bootstrap.php`; it is registered automatically- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` configdiff --git a/.claude/skills/mcp-development/references/app.md b/.claude/skills/mcp-development/references/app.mdnew file mode 100644index 000000000..db2e752a3--- /dev/null+++ b/.claude/skills/mcp-development/references/app.md@@ -0,0 +1,940 @@+# MCP UI Apps Reference++## Quick Start++`make:mcp-app-resource DashboardApp` generates two files — a PHP registration stub and a Blade view. The entire app lives in the Blade view.++**PHP class** — renders the Blade view. The view name is auto-inferred from the class name (`mcp.<kebab-class-name>`), so the generated stub needs no changes unless you're passing additional server-side data:++```php+class DashboardApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.dashboard-app', [+ 'title' => $this->title(),+ ]);+ }+}+```++**Blade view** — HTML structure + inline JS, everything in one file:++```blade+<x-mcp::app title="Dashboard App">+ <x-slot:head>+ <script type="module">+ createMcpApp(async (app) => {+ document.getElementById('run-btn').addEventListener('click', async () => {+ const result = await app.callServerTool({ name: 'tool-name', arguments: {} });+ document.getElementById('output').textContent = result.content[0]?.text ?? '';+ });+ });+ </script>+ </x-slot:head>++ <div id="app">+ <h1>Dashboard App</h1>+ <button id="run-btn">Run</button>+ <p id="output"></p>+ </div>+</x-mcp::app>+```++`createMcpApp` is a global pre-bundled by the package — no npm install, no imports, no Vite required. It handles connection, error handling, and host theming automatically.++---++## Core Concept: Tool + Resource++Every MCP App is built from two parts linked together:++- **Tool** — called by the LLM or host. Returns a text/data response and tells the host which UI resource to render via `_meta.ui.resourceUri`.+- **AppResource** — serves the self-contained HTML app. The host fetches it after the tool is called and renders it in a sandboxed iframe.++```+LLM calls Tool+ └─► Tool response includes _meta.ui.resourceUri → "ui://dashboard-app"+ └─► Host fetches AppResource at that URI+ └─► Host renders HTML in sandboxed iframe+ └─► createMcpApp() connects the iframe back to the server+ └─► UI calls app-only tools to load/refresh data+```++The link is declared once with `#[RendersApp]` on the tool:++```php+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::text('Dashboard loaded.');+ }+}+```++After that, the host handles fetching and rendering the resource automatically — you never reference the URI by hand.++---++## Architecture Overview++MCP Apps add interactive UI to the Model Context Protocol. The server returns self-contained HTML with all JS/CSS inlined. The host renders it in a sandboxed iframe. Apps communicate back via `createMcpApp()` — a pre-bundled global implementing the MCP UI PostMessage protocol.++```+┌─────────────────────────────────────────────┐+│ Host (Claude, ChatGPT, VS Code) │+│ ┌───────────────────────────────────────┐ │+│ │ Sandboxed iframe │ │+│ │ ┌─────────────────────────────────┐ │ │+│ │ │ Your MCP App (HTML/JS/CSS) │ │ │+│ │ │ - Rendered by AppResource │ │ │+│ │ │ - Single self-contained HTML │ │ │+│ │ │ - Themed via host CSS vars │ │ │+│ │ └─────────────────────────────────┘ │ │+│ └───────────────────────────────────────┘ │+└──────────────────┬──────────────────────────┘+ │ MCP Protocol (JSON-RPC)+┌──────────────────▼──────────────────────────┐+│ Laravel MCP Server │+│ - AppResource → self-contained HTML │+│ - Tool #[RendersApp] → triggers UI display │+│ - resources/read → serves HTML + _meta.ui │+└─────────────────────────────────────────────┘+```++The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.++---++## Server-Side++Minimal case — `handle()` renders the Blade view, entire app lives there:++```php+class DashboardApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.dashboard-app', [+ 'title' => $this->title(),+ ]);+ }+}+```++Auto-renders `resources/views/mcp/dashboard-app.blade.php` with `$title` available via `$this->title()`.++Override `handle()` only when passing additional server-side data:++```php+class AnalyticsDashboard extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.analytics-dashboard', [+ 'title' => $this->title(),+ 'metrics' => Metric::latest()->take(10)->get(),+ 'totalUsers' => User::count(),+ ]);+ }+}+```++`Response::view($view, $data = [], $mergeData = [])` renders a Blade view and returns it as text.++`Response::html($path)` reads an HTML file from disk and returns its content. Relative paths resolve via `resource_path()`:++```php+class StaticApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::html('mcp/static-app.html');+ }+}+```++### AppMeta Configuration++The simplest way to configure UI metadata is via the `#[AppMeta]` attribute directly on your resource class:++```php+use Laravel\Mcp\Server\Attributes\AppMeta;+use Laravel\Mcp\Server\Ui\Enums\Library;+use Laravel\Mcp\Server\Ui\Enums\Permission;++#[AppMeta(+ connectDomains: ['https://api.stripe.com'],+ permissions: [Permission::Camera, Permission::ClipboardWrite],+ prefersBorder: true,+ libraries: [Library::Tailwind, Library::Alpine],+)]+class PaymentsResource extends AppResource+{+ // ...+}+```++For dynamic or computed configuration, override `appMeta()` instead:++```php+use Laravel\Mcp\Server\Ui\AppMeta;++public function appMeta(): AppMeta+{+ return AppMeta::make()+ ->csp(Csp::make()->connectDomains(config('services.api.domains')))+ ->permissions(Permissions::make()->allow(Permission::Camera))+ ->libraries(Library::Tailwind)+ ->domain('sandbox.example.com');+}+```++#### Permission Enum++Use the `Permission` enum for type-safe permission configuration:++```php+use Laravel\Mcp\Server\Ui\Enums\Permission;++Permission::Camera // 'camera'+Permission::Microphone // 'microphone'+Permission::Geolocation // 'geolocation'+Permission::ClipboardWrite // 'clipboardWrite'+```++#### Csp++Controls what external domains the iframe can access:++```php+Csp::make()+ ->connectDomains(['https://api.example.com']) // fetch, XHR, WebSocket origins+ ->resourceDomains(['https://cdn.example.com']) // images, scripts, fonts, media+ ->frameDomains(['https://embed.example.com']) // nested iframe origins+ ->baseUriDomains(['https://base.example.com']); // base URI origins+```++#### Permissions++```php+Permissions::make()->allow(Permission::Camera, Permission::ClipboardWrite);++Permissions::make()+ ->camera()+ ->microphone()+ ->geolocation()+ ->clipboardWrite();+```++Each enabled permission serializes as `"camera": {}` per the MCP spec.++#### AppMeta++```php+AppMeta::make()+ ->csp(Csp::make()->connectDomains([...]))+ ->permissions(Permissions::make()->allow(Permission::Camera))+ ->libraries(Library::Tailwind, Library::Alpine)+ ->domain('sandbox.example.com') // dedicated sandbox origin (OAuth/CORS)+ ->prefersBorder(false);+```++`prefersBorder` defaults to `true`. `toArray()` omits null fields and empty nested objects. Library CDN domains are automatically merged into `csp.resourceDomains`.++#### domain++The `domain` field provides a stable origin that external APIs can allowlist for CORS. It is automatically resolved from `config('app.url')` (your `APP_URL` env variable) via `resolvedAppMeta()`, so most apps need no configuration. Override only when a resource needs a different origin:++```php+#[AppMeta(domain: 'custom.example.com')]+class PaymentsResource extends AppResource+{+ // ...+}+```++#### Library Scripts++The `libraries` parameter adds pre-configured CDN scripts to the `<head>` of your app. Available libraries:++```php+use Laravel\Mcp\Server\Ui\Enums\Library;++Library::Tailwind // Tailwind CSS CDN + dark mode config+Library::Alpine // Alpine.js CDN + x-cloak style+```++When libraries are specified, the package automatically:++1. Injects the CDN `<script>` tags into the Blade view's `<head>` (after the MCP SDK, before your `<x-slot:head>`)+2. Merges each library's CDN domains into `csp.resourceDomains` so the host allows loading them++Via attribute:++```php+#[AppMeta(libraries: [Library::Tailwind])]+class StyledApp extends AppResource+{+ // Tailwind is available in the Blade view — no extra setup+}+```++Via fluent builder:++```php+public function appMeta(): AppMeta+{+ return AppMeta::make()+ ->libraries(Library::Tailwind, Library::Alpine);+}+```++---++## View Layer++### `<x-mcp::app>` Blade Component++Renders a complete self-contained HTML document with the MCP SDK inlined. `createMcpApp` is available globally.++```blade+<x-mcp::app title="Dashboard App">+ <x-slot:head>+ <script type="module">+ createMcpApp(async (app) => {+ document.getElementById('run-btn').addEventListener('click', async () => {+ const result = await app.callServerTool({ name: 'tool-name', arguments: {} });+ document.getElementById('output').textContent = result.content[0]?.text ?? '';+ });+ });+ </script>+ </x-slot:head>++ <div id="app">+ <button id="run-btn">Run</button>+ <p id="output"></p>+ </div>+</x-mcp::app>+```++**Props and slots:**++| Name | Type | Description |+| ------------- | ------------- | ---------------------------------------------------- |+| `title` | Prop | Sets `<title>`. Optional. |+| `head` | Named slot | Injected into `<head>` after the inlined SDK script. |+| Default slot | Slot | Body content. |+| `$attributes` | Attribute bag | Forwarded to `<body>` (e.g. `class="dark"`). |++The SDK is loaded from the `mcp.sdk` singleton (registered by `McpServiceProvider`) and inlined directly in a `<script>` tag. Library scripts (Tailwind, Alpine) configured via `#[AppMeta]` are injected after the SDK and before the `head` slot.++Publish the component: `php artisan vendor:publish --tag=mcp-views`.++To pass server-side data to JS, embed it as `data-*` attributes:++```blade+<div id="app" data-users="{{ $users->toJson() }}">+ ...+</div>+```++```js+const users = JSON.parse(document.getElementById("app").dataset.users);+```++## Client-Side++This package provides a simple MCP client library to easily work with client interactions.++### createMcpApp++Pre-bundled and inlined automatically — no npm install or imports required.++```js+createMcpApp(async (app) => {+ // app is ready — connection established, theming applied+});+```++### Tools++#### app.callServerTool()++Accepts an object or positional arguments:++```js+// Object form+const result = await app.callServerTool({ name: 'get-analytics', arguments: { dateRange: '7d' } });++// Positional form+const result = await app.callServerTool('get-analytics', { dateRange: '7d' });++// result structure depends on the server's tool response+const text = result.content[0]?.text ?? "";+```++All tool results share a standard structure:++| Property | Type | Description |+| --------- | --------- | ------------------------------------------------------------------------- |+| `content` | `Array` | Content items returned by the tool (each has `type` and `text` or `data`) |+| `isError` | `boolean` | `true` when the tool returned an error response |++Always check `result.isError` before consuming `content`. See [Error Handling](#error-handling) for a full example.++### Resources++#### app.listResources()++```js+const resources = await app.listResources();+// or with cursor for pagination+const resources = await app.listResources("cursor-value");+// or object form+const resources = await app.listResources({ cursor: "cursor-value" });+```++#### app.readResource()++```js+const resource = await app.readResource("ui://my-resource");+// or object form+const resource = await app.readResource({ uri: "ui://my-resource" });+```++### Messaging++#### app.sendMessage()++Send a message to the model (creates a conversation turn):++```js+// Object form with structured content+await app.sendMessage({+ role: "user",+ content: [{ type: "text", text: "User submitted the form." }],+});++// Shorthand — plain string content with optional role (defaults to 'user')+await app.sendMessage("User submitted the form.");+await app.sendMessage("System event occurred.", "user");+```++### Host Context++#### app.getHostContext()++Returns the current host context, including theme and style variables:++```js+const ctx = app.getHostContext();+ctx?.theme; // 'light' | 'dark'+ctx?.styles?.variables; // CSS variable map from host+ctx?.styles?.css?.fonts; // font CSS from host+```++#### app.getHostInfo()++```js+const info = app.getHostInfo();+```++#### app.getHostCapabilities()++```js+const caps = app.getHostCapabilities();+```++### Navigation & Files++#### app.openLink()++```js+await app.openLink("https://example.com");+// or object form+await app.openLink({ url: "https://example.com" });+```++#### app.downloadFile()++```js+await app.downloadFile("file contents here");+// or object form+await app.downloadFile({ contents: "file contents here" });+```++### Display++#### app.requestDisplayMode()++```js+await app.requestDisplayMode("fullscreen");+// or object form+await app.requestDisplayMode({ mode: "fullscreen" });+```++#### app.resize() / app.autoResize()++`resize()` sends a one-time size notification. `autoResize()` uses `ResizeObserver` to continuously notify the host of size changes. It returns a cleanup function that disconnects the observer — useful if you need to stop observing before teardown. The observer is also automatically disconnected on teardown.++```js+const stopObserving = app.autoResize();++// Later, if needed:+stopObserving();+```++### Model Context++#### app.updateModelContext()++```js+await app.updateModelContext({ key: "value" });+```++### Lifecycle++#### app.requestTeardown()++Sends a teardown notification to the host.++```js+app.requestTeardown();+```++### Logging++#### app.sendLog()++```js+// Positional form+await app.sendLog("info", "Processing started", "my-logger");++// Object form+await app.sendLog({+ level: "info",+ data: "Processing started",+ logger: "my-logger",+});+```++### Event Handlers++Register callbacks for host-side events. Tool input/result/cancelled events are queued until a handler is registered, then flushed.++```js+createMcpApp(async (app) => {+ app.onToolInput((params) => {+ /* tool input received */+ });+ app.onToolInputPartial((params) => {+ /* partial tool input */+ });+ app.onToolResult((params) => {+ /* tool result received */+ });+ app.onToolCancelled((params) => {+ /* tool was cancelled */+ });+ app.onHostContextChanged((ctx) => {+ /* theme/styles changed */+ });+ app.onTeardown(async () => {+ /* cleanup before teardown */+ });+ app.onCallTool(async (params) => {+ /* host requests tool call */+ });+ app.onListTools(async (params) => {+ /* host requests tool list */+ });+});+```++---++## Host Theming++`createMcpApp` automatically applies host theming on connect and on context change:++- Sets `data-theme` attribute and `color-scheme` on `<html>`+- Applies CSS variables from `hostContext.styles.variables` to `:root`+- Injects font CSS from `hostContext.styles.css.fonts` into a `<style>` tag++The specific CSS variables available depend on the host. Always provide fallback values — use `light-dark()` for theme-aware defaults:++```css+:root {+ --color-background-primary: light-dark(#ffffff, #171717);+ --color-text-primary: light-dark(#171717, #fafafa);+ --color-text-secondary: light-dark(#525252, #a3a3a3);+ --color-border-primary: light-dark(#e5e5e5, #404040);+ --font-sans: system-ui, -apple-system, sans-serif;+ --border-radius-md: 8px;+}++body {+ font-family: var(--font-sans);+ background: var(--color-background-primary);+ color: var(--color-text-primary);+ margin: 0;+}++.card {+ background: var(--color-background-secondary);+ border: 1px solid var(--color-border-primary);+ border-radius: var(--border-radius-md);+ padding: 1rem;+}+```++---++## Tool-to-UI Linking++### #[RendersApp] Attribute++Associates a Tool with a UI Resource. When the tool is called, the host fetches and renders the linked resource.++```php+use Laravel\Mcp\Server\Attributes\RendersApp;+use Laravel\Mcp\Server\Ui\Enums\Visibility;++// Both model and app can call this tool (default)+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool { ... }++// Only the app can call this tool (private to the UI)+#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]+class RefreshDashboardData extends Tool { ... }+```++**Visibility:**++The `Visibility` enum (`Laravel\Mcp\Server\Ui\Enums\Visibility`) has two cases: `Model` and `App`. The default is `[Visibility::Model, Visibility::App]`.++| Visibility | Model | App | Use case |+| -------------------------------------- | ----- | --- | ------------------------------------------------------ |+| `[Visibility::Model, Visibility::App]` | Yes | Yes | Primary tools that trigger UI display |+| `[Visibility::App]` | No | Yes | Backend actions the UI calls (refresh, save, paginate) |+| `[Visibility::Model]` | Yes | No | Model-only tools linked to a UI |++### Primary + Private Pattern++```php+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::text('Dashboard loaded.');+ }+}++#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]+class GetDashboardMetrics extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::json(Metric::latest()->take(50)->get());+ }+}+```++---++## Testing++```php+it('returns html content', function () {+ MyServer::readResource(DashboardApp::class)+ ->assertSee('<div id="app">');+});++it('has correct mime type and uri scheme', function () {+ $resource = new DashboardApp;+ $data = $resource->toArray();++ expect($data['mimeType'])->toBe('text/html;profile=mcp-app')+ ->and($data['_meta']['ui'])->toBeArray()+ ->and($resource->uri())->toStartWith('ui://');+});++it('configures ui meta correctly', function () {+ $meta = (new DashboardApp)->resolvedAppMeta();++ expect($meta['csp']['connectDomains'])->toContain('https://api.example.com')+ ->and($meta['permissions'])->toHaveKey('clipboardWrite');+});++it('includes ui metadata in tool listing', function () {+ MyServer::listTools()->assertSee('show-dashboard');+});+```++---++## Patterns++### Real-time Polling++Use app-only tools to fetch fresh data at regular intervals from the UI:++```php+#[RendersApp(resource: MonitorApp::class, visibility: [Visibility::App])]+class GetMonitorData extends Tool+{+ protected string $description = 'Fetch latest monitor metrics';++ public function handle(Request $request): Response+ {+ return Response::json([+ 'cpu' => sys_getloadavg()[0],+ 'memory' => memory_get_usage(true),+ 'timestamp' => now()->toISOString(),+ ]);+ }+}+```++```js+createMcpApp(async (app) => {+ async function poll() {+ const result = await app.callServerTool('get-monitor-data');+ const data = JSON.parse(result.content[0]?.text ?? '{}');+ document.getElementById('cpu').textContent = data.cpu;+ }++ setInterval(poll, 2000);+ poll();+});+```++### Chunked Data Loading++For large datasets, implement pagination via app-only tools:++```php+#[RendersApp(resource: LogViewerApp::class, visibility: [Visibility::App])]+class GetLogChunk extends Tool+{+ protected string $description = 'Fetch a chunk of log entries';++ public function schema(JsonSchema $schema): array+ {+ return [+ 'offset' => $schema->integer()->description('Byte offset to start from')->required(),+ 'limit' => $schema->integer()->description('Max bytes to return'),+ ];+ }++ public function handle(Request $request): Response+ {+ $request->validate(['offset' => 'required|integer', 'limit' => 'integer']);++ $offset = $request->get('offset');+ $limit = $request->get('limit', 500_000);+ $content = Storage::get('logs/app.log');+ $chunk = substr($content, $offset, $limit);++ return Response::json([+ 'data' => $chunk,+ 'offset' => $offset,+ 'totalBytes' => strlen($content),+ 'hasMore' => ($offset + $limit) < strlen($content),+ ]);+ }+}+```++### Binary Resource Serving++Deliver images and binary content through MCP resources using `Response::blob()`:++```php+#[RendersApp(resource: GalleryApp::class, visibility: [Visibility::App])]+class GetImage extends Tool+{+ protected string $description = 'Fetch an image by ID';++ public function handle(Request $request): Response+ {+ $request->validate(['id' => 'required|integer']);++ $image = Image::findOrFail($request->get('id'));+ $data = base64_encode(Storage::get($image->path));++ return Response::blob($data);+ }+}+```++In the client, convert the base64 blob to a data URI for rendering:++```js+const result = await app.callServerTool('get-image', { id: 42 });+const blob = result.content[0];+img.src = `data:${blob.mimeType};base64,${blob.data}`;+```++### Streaming Argument Previews++Use `onToolInputPartial` to show previews as the model streams tool arguments:++```js+createMcpApp(async (app) => {+ app.onToolInputPartial((params) => {+ try {+ const partial = JSON.parse(params.arguments);+ if (partial.query) {+ document.getElementById("preview").textContent = partial.query;+ }+ } catch {+ // partial JSON — ignore until parseable+ }+ });++ app.onToolResult((params) => {+ const data = JSON.parse(params.result.content[0]?.text ?? "{}");+ renderResults(data);+ });+});+```++### View State Persistence++Use `localStorage` to preserve UI state across re-renders. For important state, persist server-side via an app-only tool:++```js+createMcpApp(async (app) => {+ const STATE_KEY = "dashboard-view-state";++ // Restore from localStorage+ const saved = JSON.parse(localStorage.getItem(STATE_KEY) || "{}");+ if (saved.activeTab) selectTab(saved.activeTab);++ // Save on interaction+ function saveState(state) {+ localStorage.setItem(STATE_KEY, JSON.stringify(state));+ }++ // For durable state, persist server-side+ async function saveServerState(state) {+ await app.callServerTool('save-dashboard-state', { state: JSON.stringify(state) });+ }+});+```++### Fullscreen Toggling++Switch between inline and fullscreen display modes and react to mode changes:++```js+createMcpApp(async (app) => {+ document.getElementById("expand-btn").addEventListener("click", () => {+ app.requestDisplayMode("fullscreen");+ });++ app.onHostContextChanged((ctx) => {+ document.body.classList.toggle(+ "fullscreen",+ ctx.displayMode === "fullscreen",+ );+ });+});+```++### Model Context Updates++Keep the model informed about what the user is viewing so it can provide relevant assistance:++```js+createMcpApp(async (app) => {+ async function notifyContext(view, detail) {+ await app.updateModelContext({+ currentView: view,+ detail: detail,+ });+ }++ // Notify on tab change+ document.querySelectorAll(".tab").forEach((tab) => {+ tab.addEventListener("click", () => {+ notifyContext(tab.dataset.view, { filters: getActiveFilters() });+ });+ });++ // For large payloads, follow up with sendMessage+ await app.updateModelContext({ currentView: "report", rows: 5000 });+ await app.sendMessage("The user is viewing a report with 5000 rows.");+});+```++### Pause Offscreen Views++Conserve resources by pausing animations and polling when the view is not visible:++```js+createMcpApp(async (app) => {+ let pollInterval = null;++ function startPolling() {+ if (!pollInterval) {+ pollInterval = setInterval(fetchData, 2000);+ }+ }++ function stopPolling() {+ clearInterval(pollInterval);+ pollInterval = null;+ }++ const observer = new IntersectionObserver(([entry]) => {+ entry.isIntersecting ? startPolling() : stopPolling();+ });++ observer.observe(document.documentElement);+ startPolling();+});+```++### Error Handling++Return `Response::error()` from tools and use `updateModelContext()` to signal degraded state:++```php+class ProcessData extends Tool+{+ public function handle(Request $request): Response+ {+ $request->validate(['input' => 'required|string']);++ if (strlen($request->get('input')) > 10_000) {+ return Response::error('Input exceeds 10KB limit.');+ }++ return Response::json(process($request->get('input')));+ }+}+```++```js+createMcpApp(async (app) => {+ const result = await app.callServerTool('process-data', { input: value });++ if (result.isError) {+ document.getElementById("error").textContent =+ result.content[0]?.text ?? "Unknown error";+ await app.updateModelContext({+ state: "error",+ message: result.content[0]?.text,+ });+ return;+ }++ renderOutput(JSON.parse(result.content[0]?.text ?? "{}"));+});+```diff --git a/.cursor/rules/project-context.mdc b/.cursor/rules/project-context.mdcindex 2ca81aa7c..3614a5434 100644--- a/.cursor/rules/project-context.mdc+++ b/.cursor/rules/project-context.mdc@@ -11,7 +11,7 @@ Laravel + Inertia v3 + Vue 3 + Tailwind v4 application. You are an expert on the- inertiajs/inertia-laravel v3, @inertiajs/vue3 v3- laravel/cashier v16, laravel/horizon v5, laravel/passport v13- laravel/pennant v1, laravel/reverb v1, laravel/socialite v5-- laravel/wayfinder v0, laravel/ai v0, laravel/boost v2, laravel/mcp v0+- laravel/wayfinder v0, laravel/ai v0, laravel/boost v2.5, laravel/mcp v0.9- laravel/nightwatch v1, laravel/telescope v5, laravel/pail v1, laravel/pint v1, laravel/sail v1- laravel/prompts v0- pestphp/pest v5, phpunit/phpunit v13diff --git a/.cursor/skills/infer-conventions/SKILL.md b/.cursor/skills/infer-conventions/SKILL.mdnew file mode 100644index 000000000..11a932753--- /dev/null+++ b/.cursor/skills/infer-conventions/SKILL.md@@ -0,0 +1,104 @@+---+name: infer-conventions+description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, console), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand."+license: MIT+metadata:+ author: laravel+---++# Infer Conventions++Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it.++## Ground Rules (read before you start)++- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer.+- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record.+- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule.+- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering.+- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped.+- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar.+- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details.++## Process++Each step ends on a checkable completion criterion. Do not advance until it holds.++Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output.++### Step 0: Orient++Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2.++This app ships a frontend stack, so the frontend checklist group applies. Sweep it.++Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents.++### Step 1: Predefined sweep++Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict:++- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files.+- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled.+- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention.+- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most).+- Tooling-owned or Already-recorded. Skip per the ground rules.++Done when: every applicable dimension carries exactly one of those verdicts.++### Step 2: Open-ended pass++First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude.++Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal.++Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none).++### Step 3: Confirm++Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style.++Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo.++Done when: every candidate is approved, rejected, or (conflicts) decided.++### Step 4: Record++Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand.++Record this:++> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models.++Not this:++> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models.++Done when: every approved item has a successful tool response, and any failure is reported with its rule text.++### Step 5: Summarize++List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions.++## Glob mapping++Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path.++Examples:++- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one.+- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer.+- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses.+- Tests: `tests/**`.+- Migrations and database: `database/migrations/**`.+- Truly app-wide (rare, e.g. auth retrieval): `app/**`.++`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there.++## Edge cases++- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4.+- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing.+- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything.+- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface.+- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths.diff --git a/.cursor/skills/infer-conventions/references/checklist.md b/.cursor/skills/infer-conventions/references/checklist.mdnew file mode 100644index 000000000..f8d1b1441--- /dev/null+++ b/.cursor/skills/infer-conventions/references/checklist.md@@ -0,0 +1,137 @@+# Detection Checklist++Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`).++Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence.++---++## A. Validation & HTTP input++1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`.+ - Hint: `ls app/Http/Requests`; grep `->validate(` / `Validator::make(` in `app/Http/Controllers`.+2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal.+ - Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`.+3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties.+ - Hint: grep `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`.+4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods.+ - Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`.++## B. Controllers & routing++5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method.+ - Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes.+6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs.+ - Hint: read a few controller methods; `ls app/Actions app/Services`.+7. Route handler style: closures in `routes/*.php` vs controller classes.+ - Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`.+8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute.+ - Hint: grep `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes.+9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`.+ - Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`.+10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`.+ - Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files.++## C. Authorization++11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`.+ - Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`.+12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade.+ - Hint: grep `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`.++## D. Eloquent & models++13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list.+ - Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`.+14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain.+ - Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`.+15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`.+ - Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`.+16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings.+ - Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models.+17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`).+ - Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built.+18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes.+ - Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`.+19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes.+ - Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`.+20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture.+ - Hint: grep `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`.++## E. Architecture & organization++21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked.+ - Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find.+22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere.+ - Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`.+23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location.+ - Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps.+24. Decoupling: events + listeners vs direct service calls.+ - Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`.+25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`).+ - Hint: ratio of `config(` vs `Config::` (etc.) across `app/`.+26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules).+ - Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders.+27. Enums: backed vs pure; case naming; where they live.+ - Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`.++## F. Frontend & views++This app ships a frontend stack, so the items below apply.++28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA.+ - Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`.+29. Blade composition: class `<x-*>` components vs anonymous components (`@props`) vs `@include` partials.+ - Hint: `ls app/View/Components`; grep `<x-`, `@include` in `resources/views`.+32. Localization: short keys (`lang/*/*.php` + `__('messages.welcome')`) vs JSON string keys (`lang/*.json` + `__('Full sentence')`).+ - Hint: `ls lang`; grep dotted `__('` vs sentence keys.++## G. Database & migrations++33. Foreign keys: `foreignId()->constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`.+ - Hint: grep `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`.+34. `down()` methods: real reverse logic vs omitted / one-way migrations.+ - Hint: grep `function down` vs the migration count.+35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model.+ - Hint: grep `->enum(` in migrations vs string columns cast to enums.+36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`.+ - Hint: grep `DB::transaction`, `beginTransaction` in `app/`.+37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save.+ - Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`.++## H. Testing++38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes.+ - Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`.+39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`.+ - Hint: grep those trait names in `tests/`.+40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories.+ - Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide.+41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery.+ - Hint: grep `->mock(`, `->spy(`, `Mockery::` in `tests/`.+42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`.+ - Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`.++## I. Responses & API resources++43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly.+ - Hint: `ls app/Http/Resources`; grep `JsonResource`, `->json(` in controllers.+44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately.+ - Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`.+45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority.+ - Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them.+46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`.+ - Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views.++## J. Strings, collections & dates++47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`.+ - Hint: grep `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`.+48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`).+ - Hint: grep `Str::of(` vs `Str::` vs native string funcs.+49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting.+ - Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy.++---++Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from.diff --git a/.cursor/skills/laravel-best-practices/SKILL.md b/.cursor/skills/laravel-best-practices/SKILL.mdindex 965e267e1..d136d7556 100644--- a/.cursor/skills/laravel-best-practices/SKILL.md+++ b/.cursor/skills/laravel-best-practices/SKILL.md@@ -8,183 +8,52 @@ metadata:# Laravel Best Practices-Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with `search-docs`.+Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`.## Consistency First-Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.+Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.-Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.--## Quick Reference--### 1. Database Performance → `rules/db-performance.md`--- Eager load with `with()` to prevent N+1 queries-- Enable `Model::preventLazyLoading()` in development-- Select only needed columns, avoid `SELECT *`-- `chunk()` / `chunkById()` for large datasets-- Index columns used in `WHERE`, `ORDER BY`, `JOIN`-- `withCount()` instead of loading relations to count-- `cursor()` for memory-efficient read-only iteration-- Never query in Blade templates--### 2. Advanced Query Patterns → `rules/advanced-queries.md`--- `addSelect()` subqueries over eager-loading entire has-many for a single value-- Dynamic relationships via subquery FK + `belongsTo`-- Conditional aggregates (`CASE WHEN` in `selectRaw`) over multiple count queries-- `setRelation()` to prevent circular N+1 queries-- `whereIn` + `pluck()` over `whereHas` for better index usage-- Two simple queries can beat one complex query-- Compound indexes matching `orderBy` column order-- Correlated subqueries in `orderBy` for has-many sorting (avoid joins)--### 3. Security → `rules/security.md`--- Define `$fillable` or `$guarded` on every model, authorize every action via policies or gates-- No raw SQL with user input — use Eloquent or query builder-- `{{ }}` for output escaping, `@csrf` on all POST/PUT/DELETE forms, `throttle` on auth and API routes-- Validate MIME type, extension, and size for file uploads-- Never commit `.env`, use `config()` for secrets, `encrypted` cast for sensitive DB fields--### 4. Caching → `rules/caching.md`--- `Cache::remember()` over manual get/put-- `Cache::flexible()` for stale-while-revalidate on high-traffic data-- `Cache::memo()` to avoid redundant cache hits within a request-- Cache tags to invalidate related groups-- `Cache::add()` for atomic conditional writes-- `once()` to memoize per-request or per-object lifetime-- `Cache::lock()` / `lockForUpdate()` for race conditions-- Failover cache stores in production--### 5. Eloquent Patterns → `rules/eloquent.md`--- Correct relationship types with return type hints-- Local scopes for reusable query constraints-- Global scopes sparingly — document their existence-- Attribute casts in the `casts()` method-- Cast date columns, use Carbon instances in templates-- `whereBelongsTo($model)` for cleaner queries-- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries--### 6. Validation & Forms → `rules/validation.md`--- Form Request classes, not inline validation-- Array notation `['required', 'email']` for new code; follow existing convention-- `$request->validated()` only — never `$request->all()`-- `Rule::when()` for conditional validation-- `after()` instead of `withValidator()`--### 7. Configuration → `rules/config.md`--- `env()` only inside config files-- `App::environment()` or `app()->isProduction()`-- Config, lang files, and constants over hardcoded text--### 8. Testing Patterns → `rules/testing.md`--- `LazilyRefreshDatabase` over `RefreshDatabase` for speed-- `assertModelExists()` over raw `assertDatabaseHas()`-- Factory states and sequences over manual overrides-- Use fakes (`Event::fake()`, `Exceptions::fake()`, etc.) — but always after factory setup, not before-- `recycle()` to share relationship instances across factories--### 9. Queue & Job Patterns → `rules/queue-jobs.md`--- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`-- `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release-- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`-- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs-- Horizon for complex multi-queue scenarios--### 10. Routing & Controllers → `rules/routing.md`--- Implicit route model binding-- Scoped bindings for nested resources-- `Route::resource()` or `apiResource()`-- Methods under 10 lines — extract to actions/services-- Type-hint Form Requests for auto-validation--### 11. HTTP Client → `rules/http-client.md`--- Explicit `timeout` and `connectTimeout` on every request-- `retry()` with exponential backoff for external APIs-- Check response status or use `throw()`-- `Http::pool()` for concurrent independent requests-- `Http::fake()` and `preventStrayRequests()` in tests--### 12. Events, Notifications & Mail → `rules/events-notifications.md`, `rules/mail.md`--- Event discovery over manual registration; `event:cache` in production-- `ShouldDispatchAfterCommit` / `afterCommit()` inside transactions-- Queue notifications and mailables with `ShouldQueue`-- On-demand notifications for non-user recipients-- `HasLocalePreference` on notifiable models-- `assertQueued()` not `assertSent()` for queued mailables-- Markdown mailables for transactional emails--### 13. Error Handling → `rules/error-handling.md`--- `report()`/`render()` on exception classes or in `bootstrap/app.php` — follow existing pattern-- `ShouldntReport` for exceptions that should never log-- Throttle high-volume exceptions to protect log sinks-- `dontReportDuplicates()` for multi-catch scenarios-- Force JSON rendering for API routes-- Structured context via `context()` on exception classes--### 14. Task Scheduling → `rules/scheduling.md`--- `withoutOverlapping()` on variable-duration tasks-- `onOneServer()` on multi-server deployments-- `runInBackground()` for concurrent long tasks-- `environments()` to restrict to appropriate environments-- `takeUntilTimeout()` for time-bounded processing-- Schedule groups for shared configuration--### 15. Architecture → `rules/architecture.md`--- Single-purpose Action classes; dependency injection over `app()` helper-- Prefer official Laravel packages and follow conventions, don't override defaults-- Default to `ORDER BY id DESC` or `created_at DESC`; `mb_*` for UTF-8 safety-- `defer()` for post-response work; `Context` for request-scoped data; `Concurrency::run()` for parallel execution--### 16. Migrations → `rules/migrations.md`--- Generate migrations with `php artisan make:migration`-- `constrained()` for foreign keys-- Never modify migrations that have run in production-- Add indexes in the migration, not as an afterthought-- Mirror column defaults in model `$attributes`-- Reversible `down()` by default; forward-fix migrations for intentionally irreversible changes-- One concern per migration — never mix DDL and DML--### 17. Collections → `rules/collections.md`--- Higher-order messages for simple collection operations-- `cursor()` vs. `lazy()` — choose based on relationship needs-- `lazyById()` when updating records while iterating-- `toQuery()` for bulk operations on collections--### 18. Blade & Views → `rules/blade-views.md`--- `$attributes->merge()` in component templates-- Blade components over `@include`; `@pushOnce` for per-component scripts-- View Composers for shared view data-- `@aware` for deeply nested component props--### 19. Conventions & Style → `rules/style.md`--- Follow Laravel naming conventions for all entities-- Prefer Laravel helpers (`Str`, `Arr`, `Number`, `Uri`, `Str::of()`, `$request->string()`) over raw PHP functions-- No JS/CSS in Blade, no HTML in PHP classes-- Code should be readable; comments only for config files+Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.## How to Apply-Always use a sub-agent to read rule files and explore this skill's content.--1. Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)-2. Check sibling files for existing patterns — follow those first per Consistency First-3. Verify API syntax with `search-docs` for the installed Laravel version+1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out.+2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files.+3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job.+4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable.+5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them.+6. Re-read the diff against every mapped rule before finishing.++## Rule Index++Cross-cutting changes often need more than one rule file.++| Concern | Read |+| --- | --- |+| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) |+| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) |+| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) |+| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) |+| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) |+| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) |+| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) |+| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) |+| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) |+| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) |+| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) |+| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) |+| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) |+| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) |+| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) |+| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) |+| Environment values and application configuration | [`rules/config.md`](rules/config.md) |+| Pest/PHPUnit patterns, factories, fakes | [`rules/testing.md`](rules/testing.md) |+| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) |+| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) |++## Decision Rules++- Prefer framework features and existing application abstractions over new helpers or dependencies.+- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable.+- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization.diff --git a/.cursor/skills/laravel-best-practices/rules/architecture.md b/.cursor/skills/laravel-best-practices/rules/architecture.mdindex 51c6e65dc..138d5a48d 100644--- a/.cursor/skills/laravel-best-practices/rules/architecture.md+++ b/.cursor/skills/laravel-best-practices/rules/architecture.md@@ -9,7 +9,7 @@ class CreateOrderAction{public function __construct(private InventoryService $inventory) {}- public function execute(array $data): Order+ public function handle(array $data): Order{$order = Order::create($data);$this->inventory->reserve($order);diff --git a/.cursor/skills/laravel-best-practices/rules/eloquent.md b/.cursor/skills/laravel-best-practices/rules/eloquent.mdindex 413d5da42..bd2cfca08 100644--- a/.cursor/skills/laravel-best-practices/rules/eloquent.md+++ b/.cursor/skills/laravel-best-practices/rules/eloquent.md@@ -30,7 +30,8 @@ $articles = Article::whereHas('user', function ($q) {Correct:```php-public function scopeActive(Builder $query): Builder+#[Scope]+protected function active(Builder $query): Builder{return $query->where('verified', true)->whereNotNull('activated_at');}@@ -58,7 +59,8 @@ class PublishedScope implements ScopeCorrect (local scope you opt into):```php-public function scopePublished(Builder $query): Builder+#[Scope]+protected function published(Builder $query): Builder{return $query->where('published', true);}diff --git a/.cursor/skills/laravel-best-practices/rules/style.md b/.cursor/skills/laravel-best-practices/rules/style.mdindex 64d173081..a8afb3695 100644--- a/.cursor/skills/laravel-best-practices/rules/style.md+++ b/.cursor/skills/laravel-best-practices/rules/style.md@@ -44,7 +44,7 @@ Strings — use `Str` and fluent `Str::of()` over raw PHP:// Incorrect$slug = strtolower(str_replace(' ', '-', $title));$short = substr($text, 0, 100) . '...';-$class = substr(strrchr('App\Models\User', '\'), 1);+$class = substr(strrchr('App\Models\User', '\\'), 1);// Correct$slug = Str::slug($title);diff --git a/.cursor/skills/mcp-development/SKILL.md b/.cursor/skills/mcp-development/SKILL.mdindex dcfb13004..4ef1bb9a6 100644--- a/.cursor/skills/mcp-development/SKILL.md+++ b/.cursor/skills/mcp-development/SKILL.md@@ -1,6 +1,6 @@---name: mcp-development-description: "Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP."+description: "Use this skill for Laravel MCP development. Trigger when creating or editing MCP tools, resources, prompts, servers, or UI apps in Laravel projects. Covers: artisan make:mcp-* generators, routes/ai.php, Tool/Resource/Prompt/AppResource classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, MCP debugging, MCP UI apps, the x-mcp::app Blade component, createMcpApp(), default AppResource handle() auto-infers view from class name, Response::view(), AppMeta/Csp/Permissions/appMeta() configuration, #[RendersApp] attribute, Library enum for CDN libraries (Tailwind, Alpine), and host theming via CSS variables. Use this whenever the user mentions MCP apps, MCP UI, interactive MCP resources, styling MCP apps with Tailwind or Alpine, or building visual interfaces for AI agents."license: MITmetadata:author: laravel@@ -12,6 +12,8 @@ metadata:Use `search-docs` for detailed Laravel MCP patterns and documentation.+For MCP UI apps (interactive HTML resources), read `references/app.md` — it covers the full architecture, host theming CSS variables, tool-to-UI linking patterns, library scripts (Tailwind, Alpine via `Library`), and real-world examples.+## Basic UsageRegister MCP servers in `routes/ai.php`:@@ -25,16 +27,16 @@ Mcp::web();### Creating MCP Primitives-Create MCP tools, resources, prompts, and servers using artisan commands:-```bash-php artisan make:mcp-tool ToolName # Create a tool+php artisan make:mcp-tool ToolName # Create a tool++php artisan make:mcp-resource ResourceName # Create a resource-php artisan make:mcp-resource ResourceName # Create a resource+php artisan make:mcp-prompt PromptName # Create a prompt-php artisan make:mcp-prompt PromptName # Create a prompt+php artisan make:mcp-server ServerName # Create a server-php artisan make:mcp-server ServerName # Create a server+php artisan make:mcp-app-resource DashboardApp # Create a UI app (2 files)```@@ -44,23 +46,33 @@ After creating primitives, register them in your server's `$tools`, `$resources`<!-- MCP Tool Example -->```php+use Illuminate\Json\Schema\JsonSchema;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;use Laravel\Mcp\Server\Tool;-use Laravel\Mcp\Server\Request;-use Laravel\Mcp\Server\Response;class MyTool extends Tool{+ protected string $description = 'Describe what this tool does';++ public function schema(JsonSchema $schema): array+ {+ return [+ 'name' => $schema->string()->description('The name parameter')->required(),+ ];+ }+public function handle(Request $request): Response{- return new Response(['result' => 'success']);+ $request->validate(['name' => 'required|string']);++ return Response::text('Hello, '.$request->get('name'));}}```### Registering Primitives in a Server-Each MCP server must explicitly declare the tools, resources, and prompts it exposes.-<!-- Register Primitives in MCP Server -->```phpuse Laravel\Mcp\Server;@@ -81,6 +93,10 @@ class AppServer extends Server}```+## MCP UI Apps++For MCP UI apps, read `references/app.md` — it covers quick start examples, full architecture, AppMeta/Csp/Permissions, `#[RendersApp]` tool linking, library scripts (Tailwind/Alpine via `Library`), host theming CSS variables, and real-world patterns.+## Verification1. Check `routes/ai.php` for proper registration@@ -92,5 +108,5 @@ class AppServer extends Server- Using HTTPS locally with Node-based MCP clients- Not using `search-docs` for the latest MCP documentation- Not registering MCP server routes in `routes/ai.php`-- Do not register `ai.php` in `bootstrap.php`; it is registered automatically.+- Do not register `ai.php` in `bootstrap.php`; it is registered automatically- OAuth registration supports custom URI schemes (e.g., `cursor://`, `vscode://`) for native desktop clients via `mcp.custom_schemes` configdiff --git a/.cursor/skills/mcp-development/references/app.md b/.cursor/skills/mcp-development/references/app.mdnew file mode 100644index 000000000..db2e752a3--- /dev/null+++ b/.cursor/skills/mcp-development/references/app.md@@ -0,0 +1,940 @@+# MCP UI Apps Reference++## Quick Start++`make:mcp-app-resource DashboardApp` generates two files — a PHP registration stub and a Blade view. The entire app lives in the Blade view.++**PHP class** — renders the Blade view. The view name is auto-inferred from the class name (`mcp.<kebab-class-name>`), so the generated stub needs no changes unless you're passing additional server-side data:++```php+class DashboardApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.dashboard-app', [+ 'title' => $this->title(),+ ]);+ }+}+```++**Blade view** — HTML structure + inline JS, everything in one file:++```blade+<x-mcp::app title="Dashboard App">+ <x-slot:head>+ <script type="module">+ createMcpApp(async (app) => {+ document.getElementById('run-btn').addEventListener('click', async () => {+ const result = await app.callServerTool({ name: 'tool-name', arguments: {} });+ document.getElementById('output').textContent = result.content[0]?.text ?? '';+ });+ });+ </script>+ </x-slot:head>++ <div id="app">+ <h1>Dashboard App</h1>+ <button id="run-btn">Run</button>+ <p id="output"></p>+ </div>+</x-mcp::app>+```++`createMcpApp` is a global pre-bundled by the package — no npm install, no imports, no Vite required. It handles connection, error handling, and host theming automatically.++---++## Core Concept: Tool + Resource++Every MCP App is built from two parts linked together:++- **Tool** — called by the LLM or host. Returns a text/data response and tells the host which UI resource to render via `_meta.ui.resourceUri`.+- **AppResource** — serves the self-contained HTML app. The host fetches it after the tool is called and renders it in a sandboxed iframe.++```+LLM calls Tool+ └─► Tool response includes _meta.ui.resourceUri → "ui://dashboard-app"+ └─► Host fetches AppResource at that URI+ └─► Host renders HTML in sandboxed iframe+ └─► createMcpApp() connects the iframe back to the server+ └─► UI calls app-only tools to load/refresh data+```++The link is declared once with `#[RendersApp]` on the tool:++```php+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::text('Dashboard loaded.');+ }+}+```++After that, the host handles fetching and rendering the resource automatically — you never reference the URI by hand.++---++## Architecture Overview++MCP Apps add interactive UI to the Model Context Protocol. The server returns self-contained HTML with all JS/CSS inlined. The host renders it in a sandboxed iframe. Apps communicate back via `createMcpApp()` — a pre-bundled global implementing the MCP UI PostMessage protocol.++```+┌─────────────────────────────────────────────┐+│ Host (Claude, ChatGPT, VS Code) │+│ ┌───────────────────────────────────────┐ │+│ │ Sandboxed iframe │ │+│ │ ┌─────────────────────────────────┐ │ │+│ │ │ Your MCP App (HTML/JS/CSS) │ │ │+│ │ │ - Rendered by AppResource │ │ │+│ │ │ - Single self-contained HTML │ │ │+│ │ │ - Themed via host CSS vars │ │ │+│ │ └─────────────────────────────────┘ │ │+│ └───────────────────────────────────────┘ │+└──────────────────┬──────────────────────────┘+ │ MCP Protocol (JSON-RPC)+┌──────────────────▼──────────────────────────┐+│ Laravel MCP Server │+│ - AppResource → self-contained HTML │+│ - Tool #[RendersApp] → triggers UI display │+│ - resources/read → serves HTML + _meta.ui │+└─────────────────────────────────────────────┘+```++The server automatically advertises `io.modelcontextprotocol/ui` capability when any `AppResource` is registered. The client declares support in `capabilities.extensions["io.modelcontextprotocol/ui"]` during the initialize handshake.++---++## Server-Side++Minimal case — `handle()` renders the Blade view, entire app lives there:++```php+class DashboardApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.dashboard-app', [+ 'title' => $this->title(),+ ]);+ }+}+```++Auto-renders `resources/views/mcp/dashboard-app.blade.php` with `$title` available via `$this->title()`.++Override `handle()` only when passing additional server-side data:++```php+class AnalyticsDashboard extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::view('mcp.analytics-dashboard', [+ 'title' => $this->title(),+ 'metrics' => Metric::latest()->take(10)->get(),+ 'totalUsers' => User::count(),+ ]);+ }+}+```++`Response::view($view, $data = [], $mergeData = [])` renders a Blade view and returns it as text.++`Response::html($path)` reads an HTML file from disk and returns its content. Relative paths resolve via `resource_path()`:++```php+class StaticApp extends AppResource+{+ public function handle(Request $request): Response+ {+ return Response::html('mcp/static-app.html');+ }+}+```++### AppMeta Configuration++The simplest way to configure UI metadata is via the `#[AppMeta]` attribute directly on your resource class:++```php+use Laravel\Mcp\Server\Attributes\AppMeta;+use Laravel\Mcp\Server\Ui\Enums\Library;+use Laravel\Mcp\Server\Ui\Enums\Permission;++#[AppMeta(+ connectDomains: ['https://api.stripe.com'],+ permissions: [Permission::Camera, Permission::ClipboardWrite],+ prefersBorder: true,+ libraries: [Library::Tailwind, Library::Alpine],+)]+class PaymentsResource extends AppResource+{+ // ...+}+```++For dynamic or computed configuration, override `appMeta()` instead:++```php+use Laravel\Mcp\Server\Ui\AppMeta;++public function appMeta(): AppMeta+{+ return AppMeta::make()+ ->csp(Csp::make()->connectDomains(config('services.api.domains')))+ ->permissions(Permissions::make()->allow(Permission::Camera))+ ->libraries(Library::Tailwind)+ ->domain('sandbox.example.com');+}+```++#### Permission Enum++Use the `Permission` enum for type-safe permission configuration:++```php+use Laravel\Mcp\Server\Ui\Enums\Permission;++Permission::Camera // 'camera'+Permission::Microphone // 'microphone'+Permission::Geolocation // 'geolocation'+Permission::ClipboardWrite // 'clipboardWrite'+```++#### Csp++Controls what external domains the iframe can access:++```php+Csp::make()+ ->connectDomains(['https://api.example.com']) // fetch, XHR, WebSocket origins+ ->resourceDomains(['https://cdn.example.com']) // images, scripts, fonts, media+ ->frameDomains(['https://embed.example.com']) // nested iframe origins+ ->baseUriDomains(['https://base.example.com']); // base URI origins+```++#### Permissions++```php+Permissions::make()->allow(Permission::Camera, Permission::ClipboardWrite);++Permissions::make()+ ->camera()+ ->microphone()+ ->geolocation()+ ->clipboardWrite();+```++Each enabled permission serializes as `"camera": {}` per the MCP spec.++#### AppMeta++```php+AppMeta::make()+ ->csp(Csp::make()->connectDomains([...]))+ ->permissions(Permissions::make()->allow(Permission::Camera))+ ->libraries(Library::Tailwind, Library::Alpine)+ ->domain('sandbox.example.com') // dedicated sandbox origin (OAuth/CORS)+ ->prefersBorder(false);+```++`prefersBorder` defaults to `true`. `toArray()` omits null fields and empty nested objects. Library CDN domains are automatically merged into `csp.resourceDomains`.++#### domain++The `domain` field provides a stable origin that external APIs can allowlist for CORS. It is automatically resolved from `config('app.url')` (your `APP_URL` env variable) via `resolvedAppMeta()`, so most apps need no configuration. Override only when a resource needs a different origin:++```php+#[AppMeta(domain: 'custom.example.com')]+class PaymentsResource extends AppResource+{+ // ...+}+```++#### Library Scripts++The `libraries` parameter adds pre-configured CDN scripts to the `<head>` of your app. Available libraries:++```php+use Laravel\Mcp\Server\Ui\Enums\Library;++Library::Tailwind // Tailwind CSS CDN + dark mode config+Library::Alpine // Alpine.js CDN + x-cloak style+```++When libraries are specified, the package automatically:++1. Injects the CDN `<script>` tags into the Blade view's `<head>` (after the MCP SDK, before your `<x-slot:head>`)+2. Merges each library's CDN domains into `csp.resourceDomains` so the host allows loading them++Via attribute:++```php+#[AppMeta(libraries: [Library::Tailwind])]+class StyledApp extends AppResource+{+ // Tailwind is available in the Blade view — no extra setup+}+```++Via fluent builder:++```php+public function appMeta(): AppMeta+{+ return AppMeta::make()+ ->libraries(Library::Tailwind, Library::Alpine);+}+```++---++## View Layer++### `<x-mcp::app>` Blade Component++Renders a complete self-contained HTML document with the MCP SDK inlined. `createMcpApp` is available globally.++```blade+<x-mcp::app title="Dashboard App">+ <x-slot:head>+ <script type="module">+ createMcpApp(async (app) => {+ document.getElementById('run-btn').addEventListener('click', async () => {+ const result = await app.callServerTool({ name: 'tool-name', arguments: {} });+ document.getElementById('output').textContent = result.content[0]?.text ?? '';+ });+ });+ </script>+ </x-slot:head>++ <div id="app">+ <button id="run-btn">Run</button>+ <p id="output"></p>+ </div>+</x-mcp::app>+```++**Props and slots:**++| Name | Type | Description |+| ------------- | ------------- | ---------------------------------------------------- |+| `title` | Prop | Sets `<title>`. Optional. |+| `head` | Named slot | Injected into `<head>` after the inlined SDK script. |+| Default slot | Slot | Body content. |+| `$attributes` | Attribute bag | Forwarded to `<body>` (e.g. `class="dark"`). |++The SDK is loaded from the `mcp.sdk` singleton (registered by `McpServiceProvider`) and inlined directly in a `<script>` tag. Library scripts (Tailwind, Alpine) configured via `#[AppMeta]` are injected after the SDK and before the `head` slot.++Publish the component: `php artisan vendor:publish --tag=mcp-views`.++To pass server-side data to JS, embed it as `data-*` attributes:++```blade+<div id="app" data-users="{{ $users->toJson() }}">+ ...+</div>+```++```js+const users = JSON.parse(document.getElementById("app").dataset.users);+```++## Client-Side++This package provides a simple MCP client library to easily work with client interactions.++### createMcpApp++Pre-bundled and inlined automatically — no npm install or imports required.++```js+createMcpApp(async (app) => {+ // app is ready — connection established, theming applied+});+```++### Tools++#### app.callServerTool()++Accepts an object or positional arguments:++```js+// Object form+const result = await app.callServerTool({ name: 'get-analytics', arguments: { dateRange: '7d' } });++// Positional form+const result = await app.callServerTool('get-analytics', { dateRange: '7d' });++// result structure depends on the server's tool response+const text = result.content[0]?.text ?? "";+```++All tool results share a standard structure:++| Property | Type | Description |+| --------- | --------- | ------------------------------------------------------------------------- |+| `content` | `Array` | Content items returned by the tool (each has `type` and `text` or `data`) |+| `isError` | `boolean` | `true` when the tool returned an error response |++Always check `result.isError` before consuming `content`. See [Error Handling](#error-handling) for a full example.++### Resources++#### app.listResources()++```js+const resources = await app.listResources();+// or with cursor for pagination+const resources = await app.listResources("cursor-value");+// or object form+const resources = await app.listResources({ cursor: "cursor-value" });+```++#### app.readResource()++```js+const resource = await app.readResource("ui://my-resource");+// or object form+const resource = await app.readResource({ uri: "ui://my-resource" });+```++### Messaging++#### app.sendMessage()++Send a message to the model (creates a conversation turn):++```js+// Object form with structured content+await app.sendMessage({+ role: "user",+ content: [{ type: "text", text: "User submitted the form." }],+});++// Shorthand — plain string content with optional role (defaults to 'user')+await app.sendMessage("User submitted the form.");+await app.sendMessage("System event occurred.", "user");+```++### Host Context++#### app.getHostContext()++Returns the current host context, including theme and style variables:++```js+const ctx = app.getHostContext();+ctx?.theme; // 'light' | 'dark'+ctx?.styles?.variables; // CSS variable map from host+ctx?.styles?.css?.fonts; // font CSS from host+```++#### app.getHostInfo()++```js+const info = app.getHostInfo();+```++#### app.getHostCapabilities()++```js+const caps = app.getHostCapabilities();+```++### Navigation & Files++#### app.openLink()++```js+await app.openLink("https://example.com");+// or object form+await app.openLink({ url: "https://example.com" });+```++#### app.downloadFile()++```js+await app.downloadFile("file contents here");+// or object form+await app.downloadFile({ contents: "file contents here" });+```++### Display++#### app.requestDisplayMode()++```js+await app.requestDisplayMode("fullscreen");+// or object form+await app.requestDisplayMode({ mode: "fullscreen" });+```++#### app.resize() / app.autoResize()++`resize()` sends a one-time size notification. `autoResize()` uses `ResizeObserver` to continuously notify the host of size changes. It returns a cleanup function that disconnects the observer — useful if you need to stop observing before teardown. The observer is also automatically disconnected on teardown.++```js+const stopObserving = app.autoResize();++// Later, if needed:+stopObserving();+```++### Model Context++#### app.updateModelContext()++```js+await app.updateModelContext({ key: "value" });+```++### Lifecycle++#### app.requestTeardown()++Sends a teardown notification to the host.++```js+app.requestTeardown();+```++### Logging++#### app.sendLog()++```js+// Positional form+await app.sendLog("info", "Processing started", "my-logger");++// Object form+await app.sendLog({+ level: "info",+ data: "Processing started",+ logger: "my-logger",+});+```++### Event Handlers++Register callbacks for host-side events. Tool input/result/cancelled events are queued until a handler is registered, then flushed.++```js+createMcpApp(async (app) => {+ app.onToolInput((params) => {+ /* tool input received */+ });+ app.onToolInputPartial((params) => {+ /* partial tool input */+ });+ app.onToolResult((params) => {+ /* tool result received */+ });+ app.onToolCancelled((params) => {+ /* tool was cancelled */+ });+ app.onHostContextChanged((ctx) => {+ /* theme/styles changed */+ });+ app.onTeardown(async () => {+ /* cleanup before teardown */+ });+ app.onCallTool(async (params) => {+ /* host requests tool call */+ });+ app.onListTools(async (params) => {+ /* host requests tool list */+ });+});+```++---++## Host Theming++`createMcpApp` automatically applies host theming on connect and on context change:++- Sets `data-theme` attribute and `color-scheme` on `<html>`+- Applies CSS variables from `hostContext.styles.variables` to `:root`+- Injects font CSS from `hostContext.styles.css.fonts` into a `<style>` tag++The specific CSS variables available depend on the host. Always provide fallback values — use `light-dark()` for theme-aware defaults:++```css+:root {+ --color-background-primary: light-dark(#ffffff, #171717);+ --color-text-primary: light-dark(#171717, #fafafa);+ --color-text-secondary: light-dark(#525252, #a3a3a3);+ --color-border-primary: light-dark(#e5e5e5, #404040);+ --font-sans: system-ui, -apple-system, sans-serif;+ --border-radius-md: 8px;+}++body {+ font-family: var(--font-sans);+ background: var(--color-background-primary);+ color: var(--color-text-primary);+ margin: 0;+}++.card {+ background: var(--color-background-secondary);+ border: 1px solid var(--color-border-primary);+ border-radius: var(--border-radius-md);+ padding: 1rem;+}+```++---++## Tool-to-UI Linking++### #[RendersApp] Attribute++Associates a Tool with a UI Resource. When the tool is called, the host fetches and renders the linked resource.++```php+use Laravel\Mcp\Server\Attributes\RendersApp;+use Laravel\Mcp\Server\Ui\Enums\Visibility;++// Both model and app can call this tool (default)+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool { ... }++// Only the app can call this tool (private to the UI)+#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]+class RefreshDashboardData extends Tool { ... }+```++**Visibility:**++The `Visibility` enum (`Laravel\Mcp\Server\Ui\Enums\Visibility`) has two cases: `Model` and `App`. The default is `[Visibility::Model, Visibility::App]`.++| Visibility | Model | App | Use case |+| -------------------------------------- | ----- | --- | ------------------------------------------------------ |+| `[Visibility::Model, Visibility::App]` | Yes | Yes | Primary tools that trigger UI display |+| `[Visibility::App]` | No | Yes | Backend actions the UI calls (refresh, save, paginate) |+| `[Visibility::Model]` | Yes | No | Model-only tools linked to a UI |++### Primary + Private Pattern++```php+#[RendersApp(resource: DashboardApp::class)]+class ShowDashboard extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::text('Dashboard loaded.');+ }+}++#[RendersApp(resource: DashboardApp::class, visibility: [Visibility::App])]+class GetDashboardMetrics extends Tool+{+ public function handle(Request $request): Response+ {+ return Response::json(Metric::latest()->take(50)->get());+ }+}+```++---++## Testing++```php+it('returns html content', function () {+ MyServer::readResource(DashboardApp::class)+ ->assertSee('<div id="app">');+});++it('has correct mime type and uri scheme', function () {+ $resource = new DashboardApp;+ $data = $resource->toArray();++ expect($data['mimeType'])->toBe('text/html;profile=mcp-app')+ ->and($data['_meta']['ui'])->toBeArray()+ ->and($resource->uri())->toStartWith('ui://');+});++it('configures ui meta correctly', function () {+ $meta = (new DashboardApp)->resolvedAppMeta();++ expect($meta['csp']['connectDomains'])->toContain('https://api.example.com')+ ->and($meta['permissions'])->toHaveKey('clipboardWrite');+});++it('includes ui metadata in tool listing', function () {+ MyServer::listTools()->assertSee('show-dashboard');+});+```++---++## Patterns++### Real-time Polling++Use app-only tools to fetch fresh data at regular intervals from the UI:++```php+#[RendersApp(resource: MonitorApp::class, visibility: [Visibility::App])]+class GetMonitorData extends Tool+{+ protected string $description = 'Fetch latest monitor metrics';++ public function handle(Request $request): Response+ {+ return Response::json([+ 'cpu' => sys_getloadavg()[0],+ 'memory' => memory_get_usage(true),+ 'timestamp' => now()->toISOString(),+ ]);+ }+}+```++```js+createMcpApp(async (app) => {+ async function poll() {+ const result = await app.callServerTool('get-monitor-data');+ const data = JSON.parse(result.content[0]?.text ?? '{}');+ document.getElementById('cpu').textContent = data.cpu;+ }++ setInterval(poll, 2000);+ poll();+});+```++### Chunked Data Loading++For large datasets, implement pagination via app-only tools:++```php+#[RendersApp(resource: LogViewerApp::class, visibility: [Visibility::App])]+class GetLogChunk extends Tool+{+ protected string $description = 'Fetch a chunk of log entries';++ public function schema(JsonSchema $schema): array+ {+ return [+ 'offset' => $schema->integer()->description('Byte offset to start from')->required(),+ 'limit' => $schema->integer()->description('Max bytes to return'),+ ];+ }++ public function handle(Request $request): Response+ {+ $request->validate(['offset' => 'required|integer', 'limit' => 'integer']);++ $offset = $request->get('offset');+ $limit = $request->get('limit', 500_000);+ $content = Storage::get('logs/app.log');+ $chunk = substr($content, $offset, $limit);++ return Response::json([+ 'data' => $chunk,+ 'offset' => $offset,+ 'totalBytes' => strlen($content),+ 'hasMore' => ($offset + $limit) < strlen($content),+ ]);+ }+}+```++### Binary Resource Serving++Deliver images and binary content through MCP resources using `Response::blob()`:++```php+#[RendersApp(resource: GalleryApp::class, visibility: [Visibility::App])]+class GetImage extends Tool+{+ protected string $description = 'Fetch an image by ID';++ public function handle(Request $request): Response+ {+ $request->validate(['id' => 'required|integer']);++ $image = Image::findOrFail($request->get('id'));+ $data = base64_encode(Storage::get($image->path));++ return Response::blob($data);+ }+}+```++In the client, convert the base64 blob to a data URI for rendering:++```js+const result = await app.callServerTool('get-image', { id: 42 });+const blob = result.content[0];+img.src = `data:${blob.mimeType};base64,${blob.data}`;+```++### Streaming Argument Previews++Use `onToolInputPartial` to show previews as the model streams tool arguments:++```js+createMcpApp(async (app) => {+ app.onToolInputPartial((params) => {+ try {+ const partial = JSON.parse(params.arguments);+ if (partial.query) {+ document.getElementById("preview").textContent = partial.query;+ }+ } catch {+ // partial JSON — ignore until parseable+ }+ });++ app.onToolResult((params) => {+ const data = JSON.parse(params.result.content[0]?.text ?? "{}");+ renderResults(data);+ });+});+```++### View State Persistence++Use `localStorage` to preserve UI state across re-renders. For important state, persist server-side via an app-only tool:++```js+createMcpApp(async (app) => {+ const STATE_KEY = "dashboard-view-state";++ // Restore from localStorage+ const saved = JSON.parse(localStorage.getItem(STATE_KEY) || "{}");+ if (saved.activeTab) selectTab(saved.activeTab);++ // Save on interaction+ function saveState(state) {+ localStorage.setItem(STATE_KEY, JSON.stringify(state));+ }++ // For durable state, persist server-side+ async function saveServerState(state) {+ await app.callServerTool('save-dashboard-state', { state: JSON.stringify(state) });+ }+});+```++### Fullscreen Toggling++Switch between inline and fullscreen display modes and react to mode changes:++```js+createMcpApp(async (app) => {+ document.getElementById("expand-btn").addEventListener("click", () => {+ app.requestDisplayMode("fullscreen");+ });++ app.onHostContextChanged((ctx) => {+ document.body.classList.toggle(+ "fullscreen",+ ctx.displayMode === "fullscreen",+ );+ });+});+```++### Model Context Updates++Keep the model informed about what the user is viewing so it can provide relevant assistance:++```js+createMcpApp(async (app) => {+ async function notifyContext(view, detail) {+ await app.updateModelContext({+ currentView: view,+ detail: detail,+ });+ }++ // Notify on tab change+ document.querySelectorAll(".tab").forEach((tab) => {+ tab.addEventListener("click", () => {+ notifyContext(tab.dataset.view, { filters: getActiveFilters() });+ });+ });++ // For large payloads, follow up with sendMessage+ await app.updateModelContext({ currentView: "report", rows: 5000 });+ await app.sendMessage("The user is viewing a report with 5000 rows.");+});+```++### Pause Offscreen Views++Conserve resources by pausing animations and polling when the view is not visible:++```js+createMcpApp(async (app) => {+ let pollInterval = null;++ function startPolling() {+ if (!pollInterval) {+ pollInterval = setInterval(fetchData, 2000);+ }+ }++ function stopPolling() {+ clearInterval(pollInterval);+ pollInterval = null;+ }++ const observer = new IntersectionObserver(([entry]) => {+ entry.isIntersecting ? startPolling() : stopPolling();+ });++ observer.observe(document.documentElement);+ startPolling();+});+```++### Error Handling++Return `Response::error()` from tools and use `updateModelContext()` to signal degraded state:++```php+class ProcessData extends Tool+{+ public function handle(Request $request): Response+ {+ $request->validate(['input' => 'required|string']);++ if (strlen($request->get('input')) > 10_000) {+ return Response::error('Input exceeds 10KB limit.');+ }++ return Response::json(process($request->get('input')));+ }+}+```++```js+createMcpApp(async (app) => {+ const result = await app.callServerTool('process-data', { input: value });++ if (result.isError) {+ document.getElementById("error").textContent =+ result.content[0]?.text ?? "Unknown error";+ await app.updateModelContext({+ state: "error",+ message: result.content[0]?.text,+ });+ return;+ }++ renderOutput(JSON.parse(result.content[0]?.text ?? "{}"));+});+```diff --git a/.env.example b/.env.exampleindex 4a631e7ee..66b174352 100644--- a/.env.example+++ b/.env.example@@ -11,6 +11,13 @@ WEBHOOK_URL=# Self-hosted mode (skips payment requirements)SELF_HOSTED=true+# Passport OAuth keys (API tokens / MCP). Prefer env vars over key files so+# every node behind a load balancer shares the same key pair. Use literal \n+# for newlines in the PEM. When unset, Passport falls back to storage/oauth-*.key+# (generate with: php artisan passport:keys).+# PASSPORT_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"+# PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"+TELESCOPE_ENABLED=falseAPP_LOCALE=endiff --git a/AGENTS.md b/AGENTS.mdindex b842f92cc..db8230fdc 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -7,36 +7,11 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for## Foundational Context-This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.--- php - 8.5-- inertiajs/inertia-laravel (INERTIA_LARAVEL) - v3-- laravel/ai (AI) - v0-- laravel/boost (BOOST) - v2-- laravel/cashier (CASHIER) - v16-- laravel/framework (LARAVEL) - v13-- laravel/horizon (HORIZON) - v5-- laravel/mcp (MCP) - v0-- laravel/nightwatch (NIGHTWATCH) - v1-- laravel/passport (PASSPORT) - v13-- laravel/prompts (PROMPTS) - v0-- laravel/reverb (REVERB) - v1-- laravel/socialite (SOCIALITE) - v5-- laravel/wayfinder (WAYFINDER) - v0-- laravel/pail (PAIL) - v1-- laravel/pint (PINT) - v1-- laravel/sail (SAIL) - v1-- laravel/telescope (TELESCOPE) - v5-- pestphp/pest (PEST) - v5-- phpunit/phpunit (PHPUNIT) - v13-- @inertiajs/vue3 (INERTIA_VUE) - v3-- tailwindcss (TAILWINDCSS) - v4-- vue (VUE) - v3-- @laravel/echo-vue (ECHO_VUE) - v2-- @laravel/vite-plugin-wayfinder (WAYFINDER_VITE) - v0-- eslint (ESLINT) - v9-- laravel-echo (ECHO) - v2-- prettier (PRETTIER) - v3+This application is a Laravel application running on PHP 8.5. You are an expert with the Laravel ecosystem. Always use the APIs that match the installed major version of each package — do not assume a version.++Before relying on a package's API, confirm its installed version:+- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show <vendor/package>` for a single package.+- JS packages: check `package.json` for the installed versions.## Skills Activation@@ -95,6 +70,11 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac3. Combine words and phrases for mixed queries: `middleware "rate limit"`.4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.+## Project Rules++- This project keeps committed, area-grouped rules in `.ai/rules` (settled decisions, non-obvious traps, standing constraints). Framework and package guidelines that only apply to specific paths (testing, frontend, components) also live there, under `.ai/rules/boost` — this is not just recorded decisions, it is load-bearing guidance you have not seen inline. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule.+- Record durable rules with `record-rule` so the next agent or teammate inherits them instead of working them out again. Pass a `glob` (e.g. `app/Http/Controllers/**`), a short `title`, and a few-line `note`. Always use `record-rule`, never your native memory or notes tool — native memory is personal and session-scoped; only `.ai/rules` is shared with the team and persists in the repo.+## Artisan- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.diff --git a/CLAUDE.md b/CLAUDE.mdindex 709aa853f..ff38c0766 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -7,36 +7,11 @@ The Laravel Boost guidelines are specifically curated by Laravel maintainers for## Foundational Context-This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.--- php - 8.5-- inertiajs/inertia-laravel (INERTIA_LARAVEL) - v3-- laravel/ai (AI) - v0-- laravel/boost (BOOST) - v2-- laravel/cashier (CASHIER) - v16-- laravel/framework (LARAVEL) - v13-- laravel/horizon (HORIZON) - v5-- laravel/mcp (MCP) - v0-- laravel/nightwatch (NIGHTWATCH) - v1-- laravel/passport (PASSPORT) - v13-- laravel/prompts (PROMPTS) - v0-- laravel/reverb (REVERB) - v1-- laravel/socialite (SOCIALITE) - v5-- laravel/wayfinder (WAYFINDER) - v0-- laravel/pail (PAIL) - v1-- laravel/pint (PINT) - v1-- laravel/sail (SAIL) - v1-- laravel/telescope (TELESCOPE) - v5-- pestphp/pest (PEST) - v5-- phpunit/phpunit (PHPUNIT) - v13-- @inertiajs/vue3 (INERTIA_VUE) - v3-- tailwindcss (TAILWINDCSS) - v4-- vue (VUE) - v3-- @laravel/echo-vue (ECHO_VUE) - v2-- @laravel/vite-plugin-wayfinder (WAYFINDER_VITE) - v0-- eslint (ESLINT) - v9-- laravel-echo (ECHO) - v2-- prettier (PRETTIER) - v3+This application is a Laravel application running on PHP 8.5. You are an expert with the Laravel ecosystem. Always use the APIs that match the installed major version of each package — do not assume a version.++Before relying on a package's API, confirm its installed version:+- PHP packages: run `composer show --direct` to list direct dependencies with versions, or `composer show <vendor/package>` for a single package.+- JS packages: check `package.json` for the installed versions.## Skills Activation@@ -95,6 +70,11 @@ This project has domain-specific skills available in `**/skills/**`. You MUST ac3. Combine words and phrases for mixed queries: `middleware "rate limit"`.4. Use multiple queries for OR logic: `queries=["authentication", "middleware"]`.+## Project Rules++- This project keeps committed, area-grouped rules in `.ai/rules` (settled decisions, non-obvious traps, standing constraints). Framework and package guidelines that only apply to specific paths (testing, frontend, components) also live there, under `.ai/rules/boost` — this is not just recorded decisions, it is load-bearing guidance you have not seen inline. Before you enter plan mode or create/edit any file, you MUST first: open @.ai/rules/index.md (it maps file globs to rule files), read every rule file whose globs cover the path(s) in scope, and run `grep -rin 'keyword' .ai/rules` to catch what a path match alone misses. Do not write code until you have read and are following every matching rule.+- Record durable rules with `record-rule` so the next agent or teammate inherits them instead of working them out again. Pass a `glob` (e.g. `app/Http/Controllers/**`), a short `title`, and a few-line `note`. Always use `record-rule`, never your native memory or notes tool — native memory is personal and session-scoped; only `.ai/rules` is shared with the team and persists in the repo.+## Artisan- Run Artisan commands directly via the command line (e.g., `php artisan route:list`). Use `php artisan list` to discover available commands and `php artisan [command] --help` to check parameters.diff --git a/app/Actions/AccessToken/ListConnectedMcpClients.php b/app/Actions/AccessToken/ListConnectedMcpClients.phpnew file mode 100644index 000000000..ef00eac92--- /dev/null+++ b/app/Actions/AccessToken/ListConnectedMcpClients.php@@ -0,0 +1,44 @@+<?php++declare(strict_types=1);++namespace App\Actions\AccessToken;++use App\Models\AccessToken;+use App\Models\User;+use Illuminate\Support\Collection;++class ListConnectedMcpClients+{+ /**+ * The viewer's own MCP OAuth connections, keyed by OAuth client.+ * Matches API keys: each person only sees what they connected.+ *+ * @return list<array{client_id: string, name: string, can_disconnect: bool, last_used_at: mixed}>+ */+ public static function forUser(User $user): array+ {+ $tokens = AccessToken::query()+ ->where('user_id', $user->id)+ ->connectedMcpOAuth()+ ->with(['client', 'user.currentWorkspace', 'workspace', 'refreshToken'])+ ->get();++ return $tokens+ ->filter(fn (AccessToken $token): bool => $token->isListedMcpConnection($user))+ ->groupBy('client_id')+ ->map(function (Collection $group): array {+ /** @var AccessToken $token */+ $token = $group->first();++ return [+ 'client_id' => $token->client_id,+ 'name' => $token->client->name,+ 'can_disconnect' => true,+ 'last_used_at' => $group->max('last_used_at'),+ ];+ })+ ->values()+ ->all();+ }+}diff --git a/app/Actions/AccessToken/RevokeMcpOAuthGrants.php b/app/Actions/AccessToken/RevokeMcpOAuthGrants.phpnew file mode 100644index 000000000..0ce564357--- /dev/null+++ b/app/Actions/AccessToken/RevokeMcpOAuthGrants.php@@ -0,0 +1,94 @@+<?php++declare(strict_types=1);++namespace App\Actions\AccessToken;++use App\Models\AccessToken;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\DB;++class RevokeMcpOAuthGrants+{+ /**+ * Revoke MCP OAuth grants only when the user can no longer view any+ * workspace (full removal). Demotion to Viewer keeps the grant — write+ * tools enforce createPost via policies, matching the web app.+ *+ * @return bool True when at least one grant was revoked.+ */+ public static function forUserIfLacksWorkspaceAccess(User $user): bool+ {+ if (self::canViewSomewhere($user)) {+ return false;+ }++ return self::forUser($user);+ }++ /**+ * Revoke every active MCP OAuth access token (and its refresh tokens) for the user.+ *+ * @return bool True when at least one grant was revoked.+ */+ public static function forUser(User $user): bool+ {+ return self::revoke(+ AccessToken::query()+ ->where('user_id', $user->id)+ ->mcpOAuth()+ ->where('revoked', false)+ ->get(),+ );+ }++ /**+ * Revoke active MCP OAuth grants for one OAuth client owned by the user.+ *+ * @return bool True when at least one grant was revoked.+ */+ public static function forUserClient(User $user, string $clientId): bool+ {+ return self::revoke(+ AccessToken::query()+ ->where('user_id', $user->id)+ ->where('client_id', $clientId)+ ->mcpOAuth()+ ->where('revoked', false)+ ->get(),+ );+ }++ public static function canViewSomewhere(User $user): bool+ {+ return $user->workspaces()+ ->get()+ ->contains(fn (Workspace $workspace): bool => $user->can('view', $workspace));+ }++ /**+ * @param Collection<int, AccessToken> $tokens+ */+ private static function revoke(Collection $tokens): bool+ {+ if ($tokens->isEmpty()) {+ return false;+ }++ DB::transaction(function () use ($tokens): void {+ $tokenIds = $tokens->pluck('id');++ DB::table('oauth_refresh_tokens')+ ->whereIn('access_token_id', $tokenIds)+ ->update(['revoked' => true]);++ $tokens->each(function (AccessToken $token): void {+ $token->forceFill(['revoked' => true])->saveQuietly();+ });+ });++ return true;+ }+}diff --git a/app/Actions/AccessToken/RevokeWorkspaceApiKeys.php b/app/Actions/AccessToken/RevokeWorkspaceApiKeys.phpnew file mode 100644index 000000000..7e0ff6224--- /dev/null+++ b/app/Actions/AccessToken/RevokeWorkspaceApiKeys.php@@ -0,0 +1,46 @@+<?php++declare(strict_types=1);++namespace App\Actions\AccessToken;++use App\Enums\UserWorkspace\Role as WorkspaceRole;+use App\Models\AccessToken;+use App\Models\Workspace;++class RevokeWorkspaceApiKeys+{+ /**+ * Revoke personal-access API keys for a user on one workspace.+ * Used when the member is removed or demoted below Admin (manageTeam).+ *+ * @return int Number of tokens revoked.+ */+ public static function forUserOnWorkspace(string $userId, Workspace $workspace): int+ {+ return AccessToken::query()+ ->where('user_id', $userId)+ ->where('workspace_id', $workspace->id)+ ->where('revoked', false)+ ->personalAccessApiKey()+ ->update(['revoked' => true]);+ }++ /**+ * Admins (and account owners acting as admin) may keep workspace API keys.+ * Any other role loses them.+ *+ * @return int Number of tokens revoked.+ */+ public static function forUserUnlessAdmin(+ string $userId,+ Workspace $workspace,+ WorkspaceRole $role,+ ): int {+ if ($role === WorkspaceRole::Admin) {+ return 0;+ }++ return self::forUserOnWorkspace($userId, $workspace);+ }+}diff --git a/app/Actions/ApiKey/CreateApiKey.php b/app/Actions/ApiKey/CreateApiKey.phpnew file mode 100644index 000000000..d484e249b--- /dev/null+++ b/app/Actions/ApiKey/CreateApiKey.php@@ -0,0 +1,44 @@+<?php++declare(strict_types=1);++namespace App\Actions\ApiKey;++use App\Models\AccessToken;+use App\Models\User;+use App\Models\Workspace;++class CreateApiKey+{+ /**+ * @return list<string>+ */+ public static function expiresAtRules(): array+ {+ return ['nullable', 'date', 'after_or_equal:today'];+ }++ /**+ * @param array{name: string, expires_at?: string|null} $data+ * @return array{token: AccessToken, plain_token: string}+ */+ public static function execute(User $user, Workspace $workspace, array $data): array+ {+ $result = $user->createToken(data_get($data, 'name'));+ $token = AccessToken::query()->findOrFail($result->token->id);+ $expiresAt = data_get($data, 'expires_at');++ $token->forceFill([+ 'workspace_id' => $workspace->id,+ // Empty = never expire (overrides Passport's JWT default lifetime in the DB).+ 'expires_at' => filled($expiresAt)+ ? now()->parse($expiresAt)->endOfDay()+ : null,+ ])->saveQuietly();++ return [+ 'token' => $token->refresh(),+ 'plain_token' => $result->accessToken,+ ];+ }+}diff --git a/app/Actions/Invite/CreateInvite.php b/app/Actions/Invite/CreateInvite.phpindex e3640aee4..33cbd65ef 100644--- a/app/Actions/Invite/CreateInvite.php+++ b/app/Actions/Invite/CreateInvite.php@@ -18,7 +18,7 @@ class CreateInvite'account_id' => $workspace->account_id,'invited_by' => auth()->id(),'email' => data_get($data, 'email'),- 'role' => WorkspaceRole::from((string) data_get($data, 'role')),+ 'role' => WorkspaceRole::from(data_get($data, 'role')),'workspaces' => [$workspace->id],]);diff --git a/app/Actions/Invite/RemoveMember.php b/app/Actions/Invite/RemoveMember.phpindex 37f6f62bb..d231a2134 100644--- a/app/Actions/Invite/RemoveMember.php+++ b/app/Actions/Invite/RemoveMember.php@@ -4,6 +4,8 @@ declare(strict_types=1);namespace App\Actions\Invite;+use App\Actions\AccessToken\RevokeMcpOAuthGrants;+use App\Actions\AccessToken\RevokeWorkspaceApiKeys;use App\Actions\User\ReassignCurrentWorkspace;use App\Actions\User\SettleStrandedMember;use App\Actions\User\StrandedSettlement;@@ -30,6 +32,7 @@ class RemoveMember$user = User::query()->find($userId);$workspace->members()->detach($userId);+ RevokeWorkspaceApiKeys::forUserOnWorkspace($userId, $workspace);if (! $user) {return;@@ -50,6 +53,14 @@ class RemoveMember) {$settlement = SettleStrandedMember::execute($user, $account);}++ // If the member still exists but can no longer view any workspace,+ // drop their MCP OAuth grants (refresh tokens included).+ $remaining = User::query()->find($userId);++ if ($remaining instanceof User) {+ RevokeMcpOAuthGrants::forUserIfLacksWorkspaceAccess($remaining);+ }});$settlement->flush();diff --git a/app/Http/Controllers/Api/ApiKeyController.php b/app/Http/Controllers/Api/ApiKeyController.phpindex 3c164c3a7..48fe36c2f 100644--- a/app/Http/Controllers/Api/ApiKeyController.php+++ b/app/Http/Controllers/Api/ApiKeyController.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Http\Controllers\Api;+use App\Actions\ApiKey\CreateApiKey;use App\Http\Requests\Api\ApiKey\StoreApiKeyRequest;use App\Http\Resources\Api\ApiKeyResource;use App\Models\AccessToken;@@ -16,6 +17,8 @@ class ApiKeyController extends Controller{public function index(Request $request): AnonymousResourceCollection{+ $this->authorize('manageTeam', $request->user()->currentWorkspace);+$tokens = AccessToken::where('user_id', $request->user()->id)->where('workspace_id', $request->user()->currentWorkspace->id)->where('revoked', false)@@ -28,24 +31,24 @@ class ApiKeyController extends Controllerpublic function store(StoreApiKeyRequest $request): JsonResponse{$workspace = $request->user()->currentWorkspace;- $validated = $request->validated();-- $result = $request->user()->createToken($validated['name']);+ $this->authorize('manageTeam', $workspace);- $token = AccessToken::find($result->token->id);- $token->forceFill([- 'workspace_id' => $workspace->id,- 'expires_at' => $validated['expires_at'] ?? null,- ])->saveQuietly();+ $created = CreateApiKey::execute(+ $request->user(),+ $workspace,+ $request->validated(),+ );return response()->json([- 'token' => new ApiKeyResource($token->refresh()),- 'plain_token' => $result->accessToken,+ 'token' => new ApiKeyResource($created['token']),+ 'plain_token' => $created['plain_token'],], Response::HTTP_CREATED);}public function destroy(Request $request, string $tokenId): JsonResponse{+ $this->authorize('manageTeam', $request->user()->currentWorkspace);+$token = AccessToken::where('id', $tokenId)->where('user_id', $request->user()->id)->where('workspace_id', $request->user()->currentWorkspace->id)diff --git a/app/Http/Controllers/App/ApiKeyController.php b/app/Http/Controllers/App/ApiKeyController.phpindex 8d0369db1..01f4f8077 100644--- a/app/Http/Controllers/App/ApiKeyController.php+++ b/app/Http/Controllers/App/ApiKeyController.php@@ -4,15 +4,18 @@ declare(strict_types=1);namespace App\Http\Controllers\App;+use App\Actions\ApiKey\CreateApiKey;+use App\Http\Requests\App\ApiKey\StoreApiKeyRequest;use App\Models\AccessToken;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Inertia\Inertia;-use Inertia\Response;+use Inertia\Response as InertiaResponse;+use Symfony\Component\HttpFoundation\Response;class ApiKeyController extends Controller{- public function index(Request $request): Response|RedirectResponse+ public function index(Request $request): InertiaResponse|RedirectResponse{$workspace = $request->user()->currentWorkspace;@@ -41,7 +44,7 @@ class ApiKeyController extends Controller]);}- public function store(Request $request): RedirectResponse+ public function store(StoreApiKeyRequest $request): RedirectResponse{$workspace = $request->user()->currentWorkspace;@@ -51,21 +54,15 @@ class ApiKeyController extends Controller$this->authorize('manageTeam', $workspace);- $validated = $request->validate([- 'name' => ['required', 'string', 'max:255'],- 'expires_at' => ['nullable', 'date', 'after:today'],- ]);-- $result = $request->user()->createToken($validated['name']);- $accessToken = AccessToken::find($result->token->id);- $accessToken->forceFill([- 'workspace_id' => $workspace->id,- 'expires_at' => $validated['expires_at'] ?? null,- ])->saveQuietly();+ $created = CreateApiKey::execute(+ $request->user(),+ $workspace,+ $request->validated(),+ );return back()->with('flash.success', __('settings.api_keys.flash.created'))- ->with('flash.plainToken', $result->accessToken);+ ->with('flash.plainToken', $created['plain_token']);}public function destroy(Request $request, string $tokenId): RedirectResponse@@ -84,7 +81,7 @@ class ApiKeyController extends Controller->first();if (! $token) {- abort(404);+ abort(Response::HTTP_NOT_FOUND);}$token->forceFill(['revoked' => true])->saveQuietly();diff --git a/app/Http/Controllers/App/AssetController.php b/app/Http/Controllers/App/AssetController.phpindex 2d8bf40ef..590a2615f 100644--- a/app/Http/Controllers/App/AssetController.php+++ b/app/Http/Controllers/App/AssetController.php@@ -78,7 +78,7 @@ class AssetController extends Controllerreturn $receiver->receive($workspace,$request->user(),- (string) $request->validated('file_name'),+ $request->validated('file_name'),$request->getContent(),(int) $request->validated('range_start'),(int) $request->validated('range_end'),@@ -99,7 +99,7 @@ class AssetController extends Controller$unsplash->trackDownload($downloadLocation);}- $url = (string) data_get($validated, 'url');+ $url = data_get($validated, 'url');try {$response = $safeHttp->guardedRequest($url)->timeout(30)->get($url);diff --git a/app/Http/Controllers/App/AutomationController.php b/app/Http/Controllers/App/AutomationController.phpindex ee1a9e608..b4dce4e99 100644--- a/app/Http/Controllers/App/AutomationController.php+++ b/app/Http/Controllers/App/AutomationController.php@@ -231,7 +231,7 @@ class AutomationController extends Controller$this->authorize('update', $automation);$feedUrl = $resolver->resolve(- (string) $request->validated('feed_url'),+ $request->validated('feed_url'),['variables' => $automation->resolvedVariables()],);diff --git a/app/Http/Controllers/App/DiscordController.php b/app/Http/Controllers/App/DiscordController.phpindex 83d230e41..14fd62c63 100644--- a/app/Http/Controllers/App/DiscordController.php+++ b/app/Http/Controllers/App/DiscordController.php@@ -40,7 +40,7 @@ class DiscordController extends Controllerreturn response()->json(['mentions' => $this->discord->mentions((string) $account->platform_user_id,- (string) $request->validated('q', ''),+ $request->validated('q', ''),),]);}diff --git a/app/Http/Controllers/App/McpSettingsController.php b/app/Http/Controllers/App/McpSettingsController.phpnew file mode 100644index 000000000..a519e24c2--- /dev/null+++ b/app/Http/Controllers/App/McpSettingsController.php@@ -0,0 +1,41 @@+<?php++declare(strict_types=1);++namespace App\Http\Controllers\App;++use App\Actions\AccessToken\ListConnectedMcpClients;+use App\Actions\AccessToken\RevokeMcpOAuthGrants;+use Illuminate\Http\RedirectResponse;+use Illuminate\Http\Request;+use Inertia\Inertia;+use Inertia\Response;++class McpSettingsController extends Controller+{+ public function index(Request $request): Response+ {+ $user = $request->user();+ $workspace = $user->currentWorkspace;++ $this->authorize('view', $workspace);++ return Inertia::render('settings/workspace/Mcp', [+ 'mcpUrl' => route('mcp.trypost'),+ 'connectedClients' => ListConnectedMcpClients::forUser($user),+ ]);+ }++ public function disconnect(Request $request, string $client): RedirectResponse+ {+ $user = $request->user();++ $this->authorize('view', $user->currentWorkspace);++ if (! RevokeMcpOAuthGrants::forUserClient($user, $client)) {+ return back();+ }++ return back()->with('flash.success', __('mcp.disconnected'));+ }+}diff --git a/app/Http/Controllers/App/OnboardingController.php b/app/Http/Controllers/App/OnboardingController.phpindex a9628a224..5f906a17a 100644--- a/app/Http/Controllers/App/OnboardingController.php+++ b/app/Http/Controllers/App/OnboardingController.php@@ -55,7 +55,7 @@ class OnboardingController extends Controllerreturn redirect()->route('app.calendar');}- $persona = (string) $request->validated('persona');+ $persona = $request->validated('persona');$user->update(['persona' => $persona]);@@ -161,7 +161,7 @@ class OnboardingController extends Controllerreturn redirect()->route('app.onboarding.goals');}- $referralSource = (string) $request->validated('referral_source');+ $referralSource = $request->validated('referral_source');$user->update(['referral_source' => $referralSource]);diff --git a/app/Http/Controllers/App/WorkspaceInviteController.php b/app/Http/Controllers/App/WorkspaceInviteController.phpindex 821224426..cbcb15655 100644--- a/app/Http/Controllers/App/WorkspaceInviteController.php+++ b/app/Http/Controllers/App/WorkspaceInviteController.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Http\Controllers\App;+use App\Actions\AccessToken\RevokeWorkspaceApiKeys;use App\Actions\Invite\CreateInvite;use App\Actions\Invite\DeleteInvite;use App\Actions\Invite\RemoveMember;@@ -15,11 +16,12 @@ use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Validation\Rule;use Inertia\Inertia;-use Inertia\Response;+use Inertia\Response as InertiaResponse;+use Symfony\Component\HttpFoundation\Response;class WorkspaceInviteController extends Controller{- public function index(Request $request): Response|RedirectResponse+ public function index(Request $request): InertiaResponse|RedirectResponse{$workspace = $request->user()->currentWorkspace;@@ -103,7 +105,7 @@ class WorkspaceInviteController extends Controller$this->authorize('manageTeam', $workspace);if ($invite->account_id !== $workspace->account_id) {- abort(404);+ abort(Response::HTTP_NOT_FOUND);}DeleteInvite::execute($invite);@@ -165,11 +167,14 @@ class WorkspaceInviteController extends Controller$validated = $request->validate(['role' => ['required', Rule::in(array_column(WorkspaceRole::cases(), 'value'))],]);+ $role = WorkspaceRole::from(data_get($validated, 'role'));$workspace->members()->updateExistingPivot($userId, [- 'role' => data_get($validated, 'role'),+ 'role' => $role->value,]);+ RevokeWorkspaceApiKeys::forUserUnlessAdmin($userId, $workspace, $role);+session()->flash('flash.banner', __('settings.members.flash.role_updated'));session()->flash('flash.bannerStyle', 'success');diff --git a/app/Http/Middleware/Api/LoadWorkspaceFromToken.php b/app/Http/Middleware/Api/LoadWorkspaceFromToken.phpindex dd9743646..bd333457a 100644--- a/app/Http/Middleware/Api/LoadWorkspaceFromToken.php+++ b/app/Http/Middleware/Api/LoadWorkspaceFromToken.php@@ -4,22 +4,34 @@ declare(strict_types=1);namespace App\Http\Middleware\Api;+use App\Models\AccessToken;use App\Models\Workspace;use Closure;use Illuminate\Http\Request;+use Laravel\Passport\AccessToken as PassportAccessToken;use Symfony\Component\HttpFoundation\Response;class LoadWorkspaceFromToken{- public function handle(Request $request, Closure $next): Response+ public function handle(Request $request, Closure $next, ?string $context = null): Response{$user = $request->user();- $token = $user?->token();+ $authenticatedToken = $user?->token();- if (! $token) {+ if (! $authenticatedToken instanceof PassportAccessToken) {return response()->json(['message' => 'Token not found.'], Response::HTTP_UNAUTHORIZED);}+ $token = AccessToken::query()->find($authenticatedToken->oauth_access_token_id);++ if ($token === null) {+ return response()->json(['message' => 'Token not found.'], Response::HTTP_UNAUTHORIZED);+ }++ if ($token->expires_at?->isPast()) {+ return response()->json(['message' => 'Token expired.'], Response::HTTP_UNAUTHORIZED);+ }+// Personal API tokens (created from settings) bind to a specific// workspace at creation. OAuth tokens (e.g. ChatGPT MCP) don't —// they follow the user's current workspace.@@ -31,7 +43,27 @@ class LoadWorkspaceFromTokenreturn response()->json(['message' => 'No workspace selected.'], Response::HTTP_UNAUTHORIZED);}- if (! config('trypost.self_hosted') && ! $workspace->account?->hasActiveSubscription()) {+ if (! $user->can('view', $workspace)) {+ return response()->json(['message' => 'Workspace access denied.'], Response::HTTP_FORBIDDEN);+ }++ if ($context === 'mcp') {+ if (! $token->isActiveMcpGrant() || ! $authenticatedToken->can('mcp:use')) {+ return response()->json(['message' => 'MCP OAuth authorization required.'], Response::HTTP_FORBIDDEN);+ }+ } else {+ if (! $token->isPersonalAccessToken()) {+ return response()->json(['message' => 'Personal access token required.'], Response::HTTP_FORBIDDEN);+ }++ if (! $user->can('manageTeam', $workspace)) {+ return response()->json(['message' => 'Insufficient workspace permissions.'], Response::HTTP_FORBIDDEN);+ }+ }++ // Match web access (EnsureAccountReady): Stripe subscription OR generic+ // no-card trial when REQUIRE_CARD_FOR_TRIAL is disabled.+ if (! config('trypost.self_hosted') && ! $workspace->account?->hasAppAccess()) {return response()->json(['message' => 'Active subscription required.'], Response::HTTP_PAYMENT_REQUIRED);}diff --git a/app/Http/Middleware/App/EnsureAccountReady.php b/app/Http/Middleware/App/EnsureAccountReady.phpindex 7e15bfe6c..b0f1011ce 100644--- a/app/Http/Middleware/App/EnsureAccountReady.php+++ b/app/Http/Middleware/App/EnsureAccountReady.php@@ -4,7 +4,6 @@ declare(strict_types=1);namespace App\Http\Middleware\App;-use App\Models\Account;use Closure;use Illuminate\Http\Request;use Symfony\Component\HttpFoundation\Response;@@ -24,13 +23,8 @@ class EnsureAccountReadyif (! config('trypost.self_hosted')) {$account = $user->account;- $requiresCardForTrial = (bool) config('trypost.billing.require_card_for_trial', true);- $hasAccess = $account && (- $account->subscribed(Account::SUBSCRIPTION_NAME)- || (! $requiresCardForTrial && $account->isOnTrial())- );- if (! $hasAccess) {+ if (! $account?->hasAppAccess()) {return redirect()->route('app.onboarding');}}diff --git a/app/Http/Requests/Api/ApiKey/StoreApiKeyRequest.php b/app/Http/Requests/Api/ApiKey/StoreApiKeyRequest.phpindex 404a552e5..796ecc61b 100644--- a/app/Http/Requests/Api/ApiKey/StoreApiKeyRequest.php+++ b/app/Http/Requests/Api/ApiKey/StoreApiKeyRequest.php@@ -4,13 +4,18 @@ declare(strict_types=1);namespace App\Http\Requests\Api\ApiKey;+use App\Actions\ApiKey\CreateApiKey;use Illuminate\Foundation\Http\FormRequest;class StoreApiKeyRequest extends FormRequest{public function authorize(): bool{- return true;+ $user = $this->user();+ $workspace = $user?->currentWorkspace;++ return $workspace !== null+ && $user->can('manageTeam', $workspace);}/**@@ -20,7 +25,7 @@ class StoreApiKeyRequest extends FormRequest{return ['name' => ['required', 'string', 'max:255'],- 'expires_at' => ['nullable', 'date', 'after:today'],+ 'expires_at' => CreateApiKey::expiresAtRules(),];}}diff --git a/app/Http/Requests/App/ApiKey/StoreApiKeyRequest.php b/app/Http/Requests/App/ApiKey/StoreApiKeyRequest.phpindex b4f881ca1..08971f62f 100644--- a/app/Http/Requests/App/ApiKey/StoreApiKeyRequest.php+++ b/app/Http/Requests/App/ApiKey/StoreApiKeyRequest.php@@ -4,13 +4,18 @@ declare(strict_types=1);namespace App\Http\Requests\App\ApiKey;+use App\Actions\ApiKey\CreateApiKey;use Illuminate\Foundation\Http\FormRequest;class StoreApiKeyRequest extends FormRequest{public function authorize(): bool{- return true;+ $user = $this->user();+ $workspace = $user?->currentWorkspace;++ return $workspace !== null+ && $user->can('manageTeam', $workspace);}/**@@ -20,7 +25,7 @@ class StoreApiKeyRequest extends FormRequest{return ['name' => ['required', 'string', 'max:255'],- 'expires_at' => ['nullable', 'date', 'after:today'],+ 'expires_at' => CreateApiKey::expiresAtRules(),];}}diff --git a/app/Mcp/Concerns/AuthorizesMcpTool.php b/app/Mcp/Concerns/AuthorizesMcpTool.phpnew file mode 100644index 000000000..bdd0eb2e7--- /dev/null+++ b/app/Mcp/Concerns/AuthorizesMcpTool.php@@ -0,0 +1,52 @@+<?php++declare(strict_types=1);++namespace App\Mcp\Concerns;++use App\Models\Workspace;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;++trait AuthorizesMcpTool+{+ /**+ * Mirror web policies inside MCP tools. Returns an error response when denied.+ * Fails closed when the request has no user or when $arguments is null.+ */+ protected function denyUnlessCan(+ Request $request,+ string $ability,+ mixed $arguments,+ string $message,+ ): Response|ResponseFactory|null {+ $user = $request->user();++ if ($user === null || $arguments === null || $user->cannot($ability, $arguments)) {+ return Response::error($message);+ }++ return null;+ }++ /**+ * Authorize a workspace-level ability against the current workspace.+ * Resolves the workspace via nullsafe access so missing auth never TypeErrors.+ */+ protected function authorizeCurrentWorkspace(+ Request $request,+ string $ability,+ string $message,+ ): Workspace|Response|ResponseFactory {+ $workspace = $request->user()?->currentWorkspace;++ if ($denied = $this->denyUnlessCan($request, $ability, $workspace, $message)) {+ return $denied;+ }++ assert($workspace instanceof Workspace);++ return $workspace;+ }+}diff --git a/app/Mcp/Servers/TryPostServer.php b/app/Mcp/Servers/TryPostServer.phpindex e9f709a20..a26899d1c 100644--- a/app/Mcp/Servers/TryPostServer.php+++ b/app/Mcp/Servers/TryPostServer.php@@ -33,12 +33,14 @@ use App\Mcp\Tools\SocialAccount\ListSocialAccountsTool;use App\Mcp\Tools\SocialAccount\ToggleSocialAccountTool;use App\Mcp\Tools\Workspace\GetWorkspaceTool;use Laravel\Mcp\Server;+use Laravel\Mcp\Server\Attributes\Icon;use Laravel\Mcp\Server\Attributes\Instructions;use Laravel\Mcp\Server\Attributes\Name;use Laravel\Mcp\Server\Attributes\Version;#[Name('TryPost')]#[Version('1.0.0')]+#[Icon('images/trypost/icon.png', mimeType: 'image/png')]#[Instructions('TryPost is a social media scheduling platform. Use this server to manage posts, signatures, labels, social accounts, workspaces, and API keys.')]class TryPostServer extends Server{diff --git a/app/Mcp/Tools/ApiKey/CreateApiKeyTool.php b/app/Mcp/Tools/ApiKey/CreateApiKeyTool.phpindex 23609ebf7..bbc791b50 100644--- a/app/Mcp/Tools/ApiKey/CreateApiKeyTool.php+++ b/app/Mcp/Tools/ApiKey/CreateApiKeyTool.php@@ -4,8 +4,10 @@ declare(strict_types=1);namespace App\Mcp\Tools\ApiKey;+use App\Actions\ApiKey\CreateApiKey;use App\Http\Resources\Api\ApiKeyResource;-use App\Models\AccessToken;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -16,26 +18,30 @@ use Laravel\Mcp\Server\Tool;#[Description('Create a new Personal Access Token (API key) for the current workspace. The plain token value is returned ONCE — store it immediately, it cannot be retrieved later.')]class CreateApiKeyTool extends Tool{- public function handle(Request $request): ResponseFactory+ use AuthorizesMcpTool;++ public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'manageTeam',+ 'Not authorized to manage API keys.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['name' => ['required', 'string', 'max:255'],- 'expires_at' => ['nullable', 'date', 'after:now'],+ 'expires_at' => CreateApiKey::expiresAtRules(),]);- $user = $request->user();-- $result = $user->createToken(data_get($validated, 'name'));-- $token = AccessToken::find($result->token->id);- $token->forceFill([- 'workspace_id' => $user->current_workspace_id,- 'expires_at' => data_get($validated, 'expires_at'),- ])->saveQuietly();+ $created = CreateApiKey::execute($request->user(), $workspace, $validated);return Response::structured(array_merge(- (new ApiKeyResource($token))->resolve(),- ['token' => $result->accessToken],+ (new ApiKeyResource($created['token']))->resolve(),+ ['token' => $created['plain_token']],));}@@ -43,7 +49,7 @@ class CreateApiKeyTool extends Tool{return ['name' => $schema->string()->required()->description('A human-readable name to identify the key (e.g. "My integration").'),- 'expires_at' => $schema->string()->description('Optional ISO 8601 expiration date (e.g. 2026-12-31). Must be in the future.'),+ 'expires_at' => $schema->string()->description('Optional expiration date (YYYY-MM-DD or ISO 8601). Omit for a key that never expires.'),];}}diff --git a/app/Mcp/Tools/ApiKey/DeleteApiKeyTool.php b/app/Mcp/Tools/ApiKey/DeleteApiKeyTool.phpindex 3192e71f6..1bf3bf7bf 100644--- a/app/Mcp/Tools/ApiKey/DeleteApiKeyTool.php+++ b/app/Mcp/Tools/ApiKey/DeleteApiKeyTool.php@@ -4,7 +4,9 @@ declare(strict_types=1);namespace App\Mcp\Tools\ApiKey;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\AccessToken;+use App\Models\Workspace;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -17,15 +19,27 @@ use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;#[Description('Revoke (delete) a Personal Access Token by ID. The current OAuth session token cannot be revoked through this tool. Existing integrations using the token will stop working.')]class DeleteApiKeyTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'manageTeam',+ 'Not authorized to manage API keys.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['api_key_id' => ['required', 'string']]);// workspace_id filter excludes OAuth-flow tokens (which have null// workspace_id), so the caller can't accidentally revoke their own// ChatGPT/MCP session token through this tool.$token = AccessToken::where('user_id', $request->user()->id)- ->where('workspace_id', $request->user()->current_workspace_id)+ ->where('workspace_id', $workspace->id)->where('revoked', false)->find(data_get($validated, 'api_key_id'));diff --git a/app/Mcp/Tools/ApiKey/ListApiKeysTool.php b/app/Mcp/Tools/ApiKey/ListApiKeysTool.phpindex 583f407b5..2e867ec18 100644--- a/app/Mcp/Tools/ApiKey/ListApiKeysTool.php+++ b/app/Mcp/Tools/ApiKey/ListApiKeysTool.php@@ -5,7 +5,9 @@ declare(strict_types=1);namespace App\Mcp\Tools\ApiKey;use App\Http\Resources\Api\ApiKeyResource;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\AccessToken;+use App\Models\Workspace;use Laravel\Mcp\Request;use Laravel\Mcp\Response;use Laravel\Mcp\ResponseFactory;@@ -17,13 +19,25 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;#[Description('List all Personal Access Tokens (API keys) for the current workspace. Returns metadata only — the secret token value is shown only once at creation. OAuth tokens (e.g. ChatGPT MCP sessions) are excluded.')]class ListApiKeysTool extends Tool{- public function handle(Request $request): ResponseFactory+ use AuthorizesMcpTool;++ public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'manageTeam',+ 'Not authorized to manage API keys.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+// Filtering by workspace_id excludes OAuth-flow tokens (whose// workspace_id is null and resolved at request time via// LoadWorkspaceFromToken middleware).$tokens = AccessToken::where('user_id', $request->user()->id)- ->where('workspace_id', $request->user()->current_workspace_id)+ ->where('workspace_id', $workspace->id)->where('revoked', false)->latest()->get();diff --git a/app/Mcp/Tools/Label/CreateLabelTool.php b/app/Mcp/Tools/Label/CreateLabelTool.phpindex 663db4ea0..7f5111e07 100644--- a/app/Mcp/Tools/Label/CreateLabelTool.php+++ b/app/Mcp/Tools/Label/CreateLabelTool.php@@ -6,6 +6,8 @@ namespace App\Mcp\Tools\Label;use App\Actions\Label\CreateLabel;use App\Http\Resources\Api\LabelResource;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -16,14 +18,26 @@ use Laravel\Mcp\Server\Tool;#[Description('Create a new label with a name and hex color.')]class CreateLabelTool extends Tool{- public function handle(Request $request): ResponseFactory+ use AuthorizesMcpTool;++ public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage labels.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['name' => ['required', 'string', 'max:255'],'color' => ['required', 'string', 'max:7', 'regex:/^#[0-9A-Fa-f]{6}$/'],]);- $label = CreateLabel::execute($request->user()->currentWorkspace, $validated);+ $label = CreateLabel::execute($workspace, $validated);return Response::structured((new LabelResource($label))->resolve());}diff --git a/app/Mcp/Tools/Label/DeleteLabelTool.php b/app/Mcp/Tools/Label/DeleteLabelTool.phpindex 2264edb64..12c13a0e3 100644--- a/app/Mcp/Tools/Label/DeleteLabelTool.php+++ b/app/Mcp/Tools/Label/DeleteLabelTool.php@@ -5,6 +5,8 @@ declare(strict_types=1);namespace App\Mcp\Tools\Label;use App\Actions\Label\DeleteLabel;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use App\Models\WorkspaceLabel;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;@@ -18,11 +20,23 @@ use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;#[Description('Delete a label permanently. The label is detached from all posts that referenced it. This cannot be undone.')]class DeleteLabelTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage labels.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['label_id' => ['required', 'string']]);- $label = WorkspaceLabel::where('workspace_id', $request->user()->current_workspace_id)+ $label = WorkspaceLabel::where('workspace_id', $workspace->id)->find(data_get($validated, 'label_id'));if (! $label) {diff --git a/app/Mcp/Tools/Label/UpdateLabelTool.php b/app/Mcp/Tools/Label/UpdateLabelTool.phpindex 17f368a80..de327281b 100644--- a/app/Mcp/Tools/Label/UpdateLabelTool.php+++ b/app/Mcp/Tools/Label/UpdateLabelTool.php@@ -6,6 +6,8 @@ namespace App\Mcp\Tools\Label;use App\Actions\Label\UpdateLabel;use App\Http\Resources\Api\LabelResource;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use App\Models\WorkspaceLabel;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;@@ -17,15 +19,27 @@ use Laravel\Mcp\Server\Tool;#[Description('Update a label name or color.')]class UpdateLabelTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage labels.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['label_id' => ['required', 'string'],'name' => ['required', 'string', 'max:255'],'color' => ['required', 'string', 'max:7', 'regex:/^#[0-9A-Fa-f]{6}$/'],]);- $label = WorkspaceLabel::where('workspace_id', $request->user()->current_workspace_id)+ $label = WorkspaceLabel::where('workspace_id', $workspace->id)->find(data_get($validated, 'label_id'));if (! $label) {diff --git a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.phpindex 94a32afb8..69de8dd7d 100644--- a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php+++ b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Mcp\Tools\Post;use App\Http\Resources\Api\PostResource;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\Media;use App\Models\Post;use App\Models\Workspace;@@ -19,6 +20,8 @@ use Laravel\Mcp\Server\Tool;#[Description('Attach a Media uploaded via RequestMediaUploadTool to a post. The upload_token is the value returned by RequestMediaUploadTool; the Media is resolved by that token within the current workspace, then appended to the post.')]class AttachMediaFromUploadTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{$validated = $request->validate([@@ -27,15 +30,20 @@ class AttachMediaFromUploadTool extends Tool'alt' => ['nullable', 'string', 'max:'.PostMediaRules::ALT_TEXT_MAX_LENGTH],]);- $workspaceId = $request->user()->current_workspace_id;+ $workspaceId = $request->user()?->current_workspace_id;- $post = Post::where('workspace_id', $workspaceId)- ->find(data_get($validated, 'post_id'));+ $post = $workspaceId+ ? Post::where('workspace_id', $workspaceId)->find(data_get($validated, 'post_id'))+ : null;if (! $post) {return Response::error('Post not found.');}+ if ($denied = $this->denyUnlessCan($request, 'update', $post, 'Not authorized to update this post.')) {+ return $denied;+ }+$media = Media::query()->where('upload_token', data_get($validated, 'upload_token'))->where('mediable_type', (new Workspace)->getMorphClass())diff --git a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.phpindex aa0adcf7c..73589c3db 100644--- a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php+++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Mcp\Tools\Post;use App\Http\Resources\Api\PostResource;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\Post;use App\Services\Post\MediaAttacher;use App\Support\PostMediaRules;@@ -18,6 +19,8 @@ use Laravel\Mcp\Server\Tool;#[Description('Download images, videos, or PDF documents from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')]class AttachMediaFromUrlTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{$validated = $request->validate([@@ -27,13 +30,17 @@ class AttachMediaFromUrlTool extends Tool'urls.*.alt' => ['nullable', 'string', 'max:'.PostMediaRules::ALT_TEXT_MAX_LENGTH],]);- $post = Post::where('workspace_id', $request->user()->current_workspace_id)+ $post = Post::where('workspace_id', $request->user()?->current_workspace_id)->find(data_get($validated, 'post_id'));if (! $post) {return Response::error('Post not found.');}+ if ($denied = $this->denyUnlessCan($request, 'update', $post, 'Not authorized to update this post.')) {+ return $denied;+ }+$result = app(MediaAttacher::class)->attachFromUrls($post,data_get($validated, 'urls', []),diff --git a/app/Mcp/Tools/Post/CreatePostTool.php b/app/Mcp/Tools/Post/CreatePostTool.phpindex 933f1380b..a90e40305 100644--- a/app/Mcp/Tools/Post/CreatePostTool.php+++ b/app/Mcp/Tools/Post/CreatePostTool.php@@ -8,6 +8,8 @@ use App\Actions\Post\CreatePost;use App\Enums\Post\CreatedVia;use App\Enums\PostPlatform\ContentType;use App\Http\Resources\Api\PostResource;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use App\Rules\ContentTypeMatchesPlatform;use App\Support\PostPlatformMetaRules;use Illuminate\Contracts\JsonSchema\JsonSchema;@@ -21,9 +23,19 @@ use Laravel\Mcp\Server\Tool;#[Description('Create a draft post in the current workspace. Accepts content, scheduled_at, label_ids, and a list of platforms (social accounts to publish on, with their content_type). Use list-content-types-tool to discover valid content_types per platform.')]class CreatePostTool extends Tool{- public function handle(Request $request): ResponseFactory+ use AuthorizesMcpTool;++ public function handle(Request $request): Response|ResponseFactory{- $workspace = $request->user()->currentWorkspace;+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to create posts.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }$validated = $request->validate([diff --git a/app/Mcp/Tools/Post/DeletePostTool.php b/app/Mcp/Tools/Post/DeletePostTool.phpindex 0bff66a0c..63db5fa7d 100644--- a/app/Mcp/Tools/Post/DeletePostTool.php+++ b/app/Mcp/Tools/Post/DeletePostTool.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Mcp\Tools\Post;use App\Actions\Post\DeletePost;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\Post;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;@@ -18,17 +19,23 @@ use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;#[Description('Delete a post permanently. This cannot be undone.')]class DeletePostTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{$validated = $request->validate(['post_id' => ['required', 'string']]);- $post = Post::where('workspace_id', $request->user()->current_workspace_id)+ $post = Post::where('workspace_id', $request->user()?->current_workspace_id)->find(data_get($validated, 'post_id'));if (! $post) {return Response::error('Post not found.');}+ if ($denied = $this->denyUnlessCan($request, 'delete', $post, 'Not authorized to delete this post.')) {+ return $denied;+ }+DeletePost::execute($post);return Response::structured(['deleted' => true]);diff --git a/app/Mcp/Tools/Post/PublishPostTool.php b/app/Mcp/Tools/Post/PublishPostTool.phpindex 00e0990d0..16278625c 100644--- a/app/Mcp/Tools/Post/PublishPostTool.php+++ b/app/Mcp/Tools/Post/PublishPostTool.php@@ -8,6 +8,7 @@ use App\Actions\Post\UpdatePost;use App\Enums\Post\Action as PostAction;use App\Enums\Post\Status;use App\Http\Resources\Api\PostResource;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\Post;use App\Rules\ContentTypeCompatibleWithMedia;use App\Support\PostPlatformMetaRules;@@ -24,21 +25,28 @@ use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;#[Description('Publish a draft post — either immediately or scheduled for a future time. The post must already have at least one enabled platform. Use update-post-tool first to set content/platforms.')]class PublishPostTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{- $workspace = $request->user()->currentWorkspace;-$validated = $request->validate(['post_id' => ['required', 'uuid'],'scheduled_at' => ['nullable', 'date', 'after:now'],]);- $post = Post::where('workspace_id', $workspace->id)->find(data_get($validated, 'post_id'));+ $workspace = $request->user()?->currentWorkspace;+ $post = $workspace+ ? Post::where('workspace_id', $workspace->id)->find(data_get($validated, 'post_id'))+ : null;if (! $post) {return Response::error('Post not found.');}+ if ($denied = $this->denyUnlessCan($request, 'update', $post, 'Not authorized to publish this post.')) {+ return $denied;+ }+if (! $post->postPlatforms()->where('enabled', true)->exists()) {return Response::error('Post has no enabled platforms. Use update-post-tool to enable at least one platform first.');}diff --git a/app/Mcp/Tools/Post/RequestMediaUploadTool.php b/app/Mcp/Tools/Post/RequestMediaUploadTool.phpindex 6585016a2..629a83984 100644--- a/app/Mcp/Tools/Post/RequestMediaUploadTool.php+++ b/app/Mcp/Tools/Post/RequestMediaUploadTool.php@@ -5,6 +5,8 @@ declare(strict_types=1);namespace App\Mcp\Tools\Post;use App\Enums\Media\Type as MediaType;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use Carbon\CarbonImmutable;use Illuminate\Contracts\JsonSchema\JsonSchema;use Illuminate\Support\Facades\URL;@@ -18,10 +20,21 @@ use Laravel\Mcp\Server\Tool;#[Description('Issue a one-shot signed POST URL that lets the user upload a local file (image, video, or PDF document) directly to this workspace. Size caps match web/API media limits — see max_bytes_by_type (max_bytes is the overall ceiling, equal to the video cap). Returns an upload_token, upload_url, max_bytes, and max_bytes_by_type. Hand the URL to the user (e.g. as a curl command with `-F media=@path/to/file`) or to the MCP client. After upload, call AttachMediaFromUploadTool(post_id, upload_token) to attach the result to a post.')]class RequestMediaUploadTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{- $user = $request->user();- $workspaceId = $user->current_workspace_id;+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to upload media.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }++ $workspaceId = $workspace->id;$ttlMinutes = (int) config('trypost.media.signed_upload_url_ttl_minutes');diff --git a/app/Mcp/Tools/Post/UpdatePostTool.php b/app/Mcp/Tools/Post/UpdatePostTool.phpindex 19eb5b001..3f0ae0e62 100644--- a/app/Mcp/Tools/Post/UpdatePostTool.php+++ b/app/Mcp/Tools/Post/UpdatePostTool.php@@ -9,7 +9,9 @@ use App\Enums\Post\Action as PostAction;use App\Enums\Post\Status;use App\Enums\PostPlatform\ContentType;use App\Http\Resources\Api\PostResource;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\Post;+use App\Models\Workspace;use App\Rules\ContentTypeCompatibleWithMedia;use App\Rules\ContentTypeMatchesPostPlatform;use App\Support\PostPlatformMetaRules;@@ -26,17 +28,23 @@ use Laravel\Mcp\Server\Tool;#[Description('Update a draft post — content, media, scheduled_at, labels, and which platforms are enabled. Cannot edit a post that has already been published.')]class UpdatePostTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{- $workspace = $request->user()->currentWorkspace;-- $postId = data_get($request->all(), 'post_id');- $post = is_string($postId) ? Post::where('workspace_id', $workspace->id)->find($postId) : null;+ $workspace = $request->user()?->currentWorkspace;+ $post = $workspace instanceof Workspace+ ? Post::where('workspace_id', $workspace->id)->find(data_get($request->all(), 'post_id'))+ : null;if (! $post) {return Response::error('Post not found.');}+ if ($denied = $this->denyUnlessCan($request, 'update', $post, 'Not authorized to update this post.')) {+ return $denied;+ }+$status = data_get($request->all(), 'status');$validated = $request->validate(diff --git a/app/Mcp/Tools/Signature/CreateSignatureTool.php b/app/Mcp/Tools/Signature/CreateSignatureTool.phpindex 15104df9d..30e468f83 100644--- a/app/Mcp/Tools/Signature/CreateSignatureTool.php+++ b/app/Mcp/Tools/Signature/CreateSignatureTool.php@@ -6,6 +6,8 @@ namespace App\Mcp\Tools\Signature;use App\Actions\Signature\CreateSignature;use App\Http\Resources\Api\SignatureResource;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -16,14 +18,26 @@ use Laravel\Mcp\Server\Tool;#[Description('Create a new signature with a name and content (hashtags, links, custom text, etc.).')]class CreateSignatureTool extends Tool{- public function handle(Request $request): ResponseFactory+ use AuthorizesMcpTool;++ public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage signatures.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['name' => ['required', 'string', 'max:255'],'content' => ['required', 'string'],]);- $signature = CreateSignature::execute($request->user()->currentWorkspace, $validated);+ $signature = CreateSignature::execute($workspace, $validated);return Response::structured((new SignatureResource($signature))->resolve());}diff --git a/app/Mcp/Tools/Signature/DeleteSignatureTool.php b/app/Mcp/Tools/Signature/DeleteSignatureTool.phpindex 399ce5d8d..868c8faa7 100644--- a/app/Mcp/Tools/Signature/DeleteSignatureTool.php+++ b/app/Mcp/Tools/Signature/DeleteSignatureTool.php@@ -5,6 +5,8 @@ declare(strict_types=1);namespace App\Mcp\Tools\Signature;use App\Actions\Signature\DeleteSignature;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use App\Models\WorkspaceSignature;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;@@ -18,11 +20,23 @@ use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;#[Description('Delete a signature permanently. This cannot be undone.')]class DeleteSignatureTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage signatures.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['signature_id' => ['required', 'string']]);- $signature = WorkspaceSignature::where('workspace_id', $request->user()->current_workspace_id)+ $signature = WorkspaceSignature::where('workspace_id', $workspace->id)->find(data_get($validated, 'signature_id'));if (! $signature) {diff --git a/app/Mcp/Tools/Signature/UpdateSignatureTool.php b/app/Mcp/Tools/Signature/UpdateSignatureTool.phpindex 3636301b2..a9a49a529 100644--- a/app/Mcp/Tools/Signature/UpdateSignatureTool.php+++ b/app/Mcp/Tools/Signature/UpdateSignatureTool.php@@ -6,6 +6,8 @@ namespace App\Mcp\Tools\Signature;use App\Actions\Signature\UpdateSignature;use App\Http\Resources\Api\SignatureResource;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\Workspace;use App\Models\WorkspaceSignature;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;@@ -17,15 +19,27 @@ use Laravel\Mcp\Server\Tool;#[Description('Update a signature name or content.')]class UpdateSignatureTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage signatures.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['signature_id' => ['required', 'string'],'name' => ['required', 'string', 'max:255'],'content' => ['required', 'string'],]);- $signature = WorkspaceSignature::where('workspace_id', $request->user()->current_workspace_id)+ $signature = WorkspaceSignature::where('workspace_id', $workspace->id)->find(data_get($validated, 'signature_id'));if (! $signature) {diff --git a/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.php b/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.phpindex 704c4c479..11977831f 100644--- a/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.php+++ b/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.php@@ -7,7 +7,9 @@ namespace App\Mcp\Tools\SocialAccount;use App\Actions\SocialAccount\ListDiscordChannels;use App\Enums\SocialAccount\Platform;use App\Exceptions\PlatformUnavailableException;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\SocialAccount;+use App\Models\Workspace;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -18,13 +20,25 @@ use Laravel\Mcp\Server\Tool;#[Description('List Discord text/announcement channels the bot can post to for a connected Discord server. Use the returned channel id as platforms[].meta.channel_id when creating or updating a Discord post (required to publish).')]class ListDiscordChannelsTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage posts.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['account_id' => ['required', 'string', 'uuid'],]);- $account = SocialAccount::where('workspace_id', $request->user()->current_workspace_id)+ $account = SocialAccount::where('workspace_id', $workspace->id)->find(data_get($validated, 'account_id'));if (! $account) {diff --git a/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.php b/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.phpindex 2227a193f..9025e566c 100644--- a/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.php+++ b/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.php@@ -8,7 +8,9 @@ use App\Actions\SocialAccount\ListPinterestBoards;use App\Enums\SocialAccount\Platform;use App\Exceptions\Social\PinterestPublishException;use App\Exceptions\TokenExpiredException;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\SocialAccount;+use App\Models\Workspace;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -19,13 +21,25 @@ use Laravel\Mcp\Server\Tool;#[Description('List Pinterest boards for a connected Pinterest account. Use the returned board id as platforms[].meta.board_id when creating or updating a Pinterest post (required to publish).')]class ListPinterestBoardsTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'createPost',+ 'Not authorized to manage posts.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['account_id' => ['required', 'string', 'uuid'],]);- $account = SocialAccount::where('workspace_id', $request->user()->current_workspace_id)+ $account = SocialAccount::where('workspace_id', $workspace->id)->find(data_get($validated, 'account_id'));if (! $account) {diff --git a/app/Mcp/Tools/SocialAccount/ToggleSocialAccountTool.php b/app/Mcp/Tools/SocialAccount/ToggleSocialAccountTool.phpindex ec1433e95..ee27a9cf9 100644--- a/app/Mcp/Tools/SocialAccount/ToggleSocialAccountTool.php+++ b/app/Mcp/Tools/SocialAccount/ToggleSocialAccountTool.php@@ -6,7 +6,9 @@ namespace App\Mcp\Tools\SocialAccount;use App\Actions\SocialAccount\ToggleSocialAccount;use App\Http\Resources\Api\SocialAccountResource;+use App\Mcp\Concerns\AuthorizesMcpTool;use App\Models\SocialAccount;+use App\Models\Workspace;use Illuminate\Contracts\JsonSchema\JsonSchema;use Laravel\Mcp\Request;use Laravel\Mcp\Response;@@ -17,13 +19,25 @@ use Laravel\Mcp\Server\Tool;#[Description('Toggle a social account active/inactive. When inactive, the account is skipped during scheduled publishing. Returns the updated account.')]class ToggleSocialAccountTool extends Tool{+ use AuthorizesMcpTool;+public function handle(Request $request): Response|ResponseFactory{+ $workspace = $this->authorizeCurrentWorkspace(+ $request,+ 'manageAccounts',+ 'Not authorized to manage social accounts.',+ );++ if (! $workspace instanceof Workspace) {+ return $workspace;+ }+$validated = $request->validate(['account_id' => ['required', 'string', 'uuid'],]);- $account = SocialAccount::where('workspace_id', $request->user()->current_workspace_id)+ $account = SocialAccount::where('workspace_id', $workspace->id)->find(data_get($validated, 'account_id'));if (! $account) {diff --git a/app/Models/AccessToken.php b/app/Models/AccessToken.phpindex 0f81b83c0..b1243ab0c 100644--- a/app/Models/AccessToken.php+++ b/app/Models/AccessToken.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Models;+use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Laravel\Passport\Token;@@ -41,4 +42,199 @@ class AccessToken extends Token{return $this->belongsTo(Workspace::class);}++ /**+ * Passport resolves the user model via the OAuth client's provider, which+ * breaks eager-loading `user` (the relation is built on an empty token with+ * no client). Tokens in TryPost always belong to App\Models\User.+ */+ public function user(): BelongsTo+ {+ return $this->belongsTo(User::class);+ }++ /**+ * Active OAuth grants used by MCP clients (excludes personal access API keys).+ *+ * @param Builder<static> $query+ * @return Builder<static>+ */+ public function scopeActiveMcpOAuth(Builder $query): Builder+ {+ return $query+ ->mcpOAuth()+ ->where('revoked', false)+ ->where(function (Builder $expires): void {+ $expires->whereNull('expires_at')+ ->orWhere('expires_at', '>', now());+ });+ }++ /**+ * MCP OAuth grants that still represent a live or recoverable session+ * (unexpired access token, or expired access with a live refresh token).+ *+ * @param Builder<static> $query+ * @return Builder<static>+ */+ public function scopeConnectedMcpOAuth(Builder $query): Builder+ {+ return $query+ ->mcpOAuth()+ ->where('revoked', false)+ ->where(function (Builder $alive): void {+ $alive+ ->where(function (Builder $expires): void {+ $expires->whereNull('expires_at')+ ->orWhere('expires_at', '>', now());+ })+ ->orWhereHas(+ 'refreshToken',+ fn (Builder $refresh): Builder => $refresh+ ->where('revoked', false)+ ->where(function (Builder $refreshExpires): void {+ $refreshExpires->whereNull('expires_at')+ ->orWhere('expires_at', '>', now());+ }),+ );+ });+ }++ /**+ * @param Builder<static> $query+ * @return Builder<static>+ */+ public function scopeMcpOAuth(Builder $query): Builder+ {+ return $query+ ->whereJsonContains('scopes', 'mcp:use')+ ->whereHas(+ 'client',+ fn (Builder $client): Builder => $client+ ->where('revoked', false)+ ->whereJsonDoesntContain('grant_types', 'personal_access'),+ );+ }++ /**+ * Personal-access API keys (REST), excluding MCP OAuth clients.+ *+ * @param Builder<static> $query+ * @return Builder<static>+ */+ public function scopePersonalAccessApiKey(Builder $query): Builder+ {+ return $query->whereHas(+ 'client',+ fn (Builder $client): Builder => $client+ ->where('revoked', false)+ ->whereJsonContains('grant_types', 'personal_access'),+ );+ }++ /**+ * Whether this token was issued by a live personal-access client (REST API keys).+ */+ public function isPersonalAccessToken(): bool+ {+ $this->loadMissing('client');++ return $this->client !== null+ && ! $this->client->revoked+ && $this->client->hasGrantType('personal_access');+ }++ /**+ * Whether this is a non-revoked MCP OAuth grant with mcp:use (ignores expiry).+ */+ public function isMcpOAuthGrant(): bool+ {+ $this->loadMissing('client');++ if ($this->revoked) {+ return false;+ }++ if (! in_array('mcp:use', $this->scopes ?? [], true)) {+ return false;+ }++ return $this->client !== null+ && ! $this->client->revoked+ && ! $this->client->hasGrantType('personal_access');+ }++ /**+ * Whether this is a non-revoked, unexpired MCP OAuth grant with mcp:use.+ */+ public function isActiveMcpGrant(): bool+ {+ if (! $this->isMcpOAuthGrant()) {+ return false;+ }++ return $this->expires_at === null || ! $this->expires_at->isPast();+ }++ /**+ * Whether a refresh token can still mint a new access token for this grant.+ */+ public function hasLiveRefreshToken(): bool+ {+ $this->loadMissing('refreshToken');++ $refresh = $this->refreshToken;++ if ($refresh === null || $refresh->revoked) {+ return false;+ }++ return $refresh->expires_at === null || $refresh->expires_at->isFuture();+ }++ /**+ * Whether this MCP grant can actually use the product (active token + a+ * workspace the owner can view — write tools enforce createPost themselves).+ */+ public function isUsableMcpGrant(?User $user = null, ?Workspace $workspace = null): bool+ {+ if (! $this->isActiveMcpGrant()) {+ return false;+ }++ return $this->ownerCanViewWorkspace($user, $workspace);+ }++ /**+ * Whether this MCP grant should appear in the connected-clients list+ * (usable now, or recoverable via refresh, for a user who can view a workspace).+ */+ public function isListedMcpConnection(?User $user = null, ?Workspace $workspace = null): bool+ {+ if (! $this->isMcpOAuthGrant()) {+ return false;+ }++ if (! $this->isActiveMcpGrant() && ! $this->hasLiveRefreshToken()) {+ return false;+ }++ return $this->ownerCanViewWorkspace($user, $workspace);+ }++ private function ownerCanViewWorkspace(?User $user = null, ?Workspace $workspace = null): bool+ {+ $user ??= User::query()+ ->with('currentWorkspace')+ ->find($this->user_id);++ if (! $user instanceof User) {+ return false;+ }++ $workspace ??= $this->workspace ?? $user->currentWorkspace;++ return $workspace instanceof Workspace+ && $user->can('view', $workspace);+ }}diff --git a/app/Models/Account.php b/app/Models/Account.phpindex b8e31b00a..6834abe2e 100644--- a/app/Models/Account.php+++ b/app/Models/Account.php@@ -78,6 +78,22 @@ class Account extends Modelreturn $this->subscribed(self::SUBSCRIPTION_NAME);}+ /**+ * Whether the account may use the app (active subscription, or a generic+ * trial when REQUIRE_CARD_FOR_TRIAL is disabled).+ */+ public function hasAppAccess(): bool+ {+ if (config('trypost.self_hosted')) {+ return true;+ }++ $requiresCardForTrial = (bool) config('trypost.billing.require_card_for_trial', true);++ return $this->subscribed(self::SUBSCRIPTION_NAME)+ || (! $requiresCardForTrial && $this->isOnTrial());+ }+/*** Align the Stripe subscription quantity with the number of workspaces the* account owns. Each workspace is a billed unit. No-op in self-hosted modediff --git a/app/Policies/AccountPolicy.php b/app/Policies/AccountPolicy.phpindex b7042f16e..48be159f0 100644--- a/app/Policies/AccountPolicy.php+++ b/app/Policies/AccountPolicy.php@@ -32,12 +32,7 @@ class AccountPolicyreturn Response::allow();}- $requiresCardForTrial = (bool) config('trypost.billing.require_card_for_trial', true);-- $hasAccess = $account->subscribed(Account::SUBSCRIPTION_NAME)- || (! $requiresCardForTrial && $account->isOnTrial());-- if (! $hasAccess) {+ if (! $account->hasAppAccess()) {return Response::deny(__('billing.flash.subscription_required'));}diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.phpindex 61349bc7c..55b360d0c 100644--- a/app/Providers/AppServiceProvider.php+++ b/app/Providers/AppServiceProvider.php@@ -102,6 +102,11 @@ class AppServiceProvider extends ServiceProvider{Passport::useTokenModel(AccessToken::class);+ // API keys may omit an application expiry ("never"). Passport still+ // embeds a JWT `exp`, so keep that far ahead and enforce optional+ // `oauth_access_tokens.expires_at` in LoadWorkspaceFromToken.+ Passport::personalAccessTokensExpireIn(now()->addYears(100));+Passport::tokensCan(['mcp:use' => 'Use MCP server',]);@@ -160,6 +165,11 @@ class AppServiceProvider extends ServiceProviderreturn Limit::perMinute(60)->by($request->workspace?->id ?: $request->ip());});+ RateLimiter::for(+ 'mcp-oauth-registration',+ fn (Request $request): Limit => Limit::perMinute(30)->by($request->ip()),+ );+// Signed media uploads (api.uploads.store). MCP hosts share egress IPs// across tenants — key by workspace_id from the signed URL, with a high// IP backstop so one client cannot flood every workspace.diff --git a/boost.json b/boost.jsonindex c8baa782b..8dac4b120 100644--- a/boost.json+++ b/boost.json@@ -10,6 +10,7 @@"nightwatch": true,"sail": false,"skills": [+ "infer-conventions","ai-sdk-development","cashier-stripe-development","laravel-best-practices",diff --git a/compose.prod.yaml b/compose.prod.yamlindex d5bafaab9..ffacc9ea4 100644--- a/compose.prod.yaml+++ b/compose.prod.yaml@@ -50,6 +50,16 @@ services:REVERB_PORT: "8080"REVERB_SCHEME: http+ # ===== Passport (OAuth / API keys / MCP) =====+ # REQUIRED for any durable deploy (and always for multi-node / load+ # balancers). File keys under storage/ are NOT persisted by the volumes+ # below — without these env vars a container recreate issues new keys and+ # invalidates every API/MCP token. Generate once:+ # docker compose -f compose.prod.yaml run --rm app php artisan passport:keys --show+ # then paste the PEM contents here (use \n for newlines).+ PASSPORT_PRIVATE_KEY: ""+ PASSPORT_PUBLIC_KEY: ""+# ===== Storage =====# Default: local disk, persisted in the "storage" volume below.FILESYSTEM_DISK: publicdiff --git a/composer.json b/composer.jsonindex 485c6dbd0..8b1c7222b 100644--- a/composer.json+++ b/composer.json@@ -38,11 +38,11 @@"inertiajs/inertia-laravel": "^3.0","intervention/image": "^4.0","laravel/ai": "^0.5.1",- "laravel/boost": "^2.0",+ "laravel/boost": "^2.5","laravel/cashier": "^16.2","laravel/framework": "^13.0","laravel/horizon": "^5.45",- "laravel/mcp": "^0.6.4",+ "laravel/mcp": "^0.9.1","laravel/nightwatch": "^1.22","laravel/passport": "^13.7","laravel/reverb": "^1.0",diff --git a/composer.lock b/composer.lockindex 244069417..91f542e5d 100644--- a/composer.lock+++ b/composer.lock@@ -4,7 +4,7 @@"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies","This file is @generated automatically"],- "content-hash": "84ccdb211d510192123d0d7ccd477d55",+ "content-hash": "d2abd6288d12131200c2297189b1f11f","packages": [{"name": "aws/aws-crt-php",@@ -415,6 +415,83 @@],"time": "2025-01-03T16:18:33+00:00"},+ {+ "name": "composer/semver",+ "version": "3.4.4",+ "source": {+ "type": "git",+ "url": "https://github.com/composer/semver.git",+ "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/composer/semver/zipball/198166618906cb2de69b95d7d47e5fa8aa1b2b95",+ "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95",+ "shasum": ""+ },+ "require": {+ "php": "^5.3.2 || ^7.0 || ^8.0"+ },+ "require-dev": {+ "phpstan/phpstan": "^1.11",+ "symfony/phpunit-bridge": "^3 || ^7"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "3.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "Composer\\Semver\\": "src"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Nils Adermann",+ "email": "[email protected]",+ "homepage": "http://www.naderman.de"+ },+ {+ "name": "Jordi Boggiano",+ "email": "[email protected]",+ "homepage": "http://seld.be"+ },+ {+ "name": "Rob Bast",+ "email": "[email protected]",+ "homepage": "http://robbast.nl"+ }+ ],+ "description": "Semver library that offers utilities, version constraint parsing and validation.",+ "keywords": [+ "semantic",+ "semver",+ "validation",+ "versioning"+ ],+ "support": {+ "irc": "ircs://irc.libera.chat:6697/composer",+ "issues": "https://github.com/composer/semver/issues",+ "source": "https://github.com/composer/semver/tree/3.4.4"+ },+ "funding": [+ {+ "url": "https://packagist.com",+ "type": "custom"+ },+ {+ "url": "https://github.com/composer",+ "type": "github"+ }+ ],+ "time": "2025-08-20T19:15:30+00:00"+ },{"name": "defuse/php-encryption","version": "v2.4.0",@@ -1280,21 +1357,21 @@},{"name": "guzzlehttp/guzzle",- "version": "7.15.2",+ "version": "7.15.3","source": {"type": "git","url": "https://github.com/guzzle/guzzle.git",- "reference": "744101956d78b7c1384d0cbf379db13e859167bf"+ "reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/guzzle/guzzle/zipball/744101956d78b7c1384d0cbf379db13e859167bf",- "reference": "744101956d78b7c1384d0cbf379db13e859167bf",+ "url": "https://api.github.com/repos/guzzle/guzzle/zipball/ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc",+ "reference": "ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc","shasum": ""},"require": {"ext-json": "*",- "guzzlehttp/promises": "^2.5.1",+ "guzzlehttp/promises": "^2.5.2","guzzlehttp/psr7": "^2.13","php": "^7.2.5 || ^8.0","psr/http-client": "^1.0",@@ -1388,7 +1465,7 @@],"support": {"issues": "https://github.com/guzzle/guzzle/issues",- "source": "https://github.com/guzzle/guzzle/tree/7.15.2"+ "source": "https://github.com/guzzle/guzzle/tree/7.15.3"},"funding": [{@@ -1404,20 +1481,20 @@"type": "tidelift"}],- "time": "2026-07-26T23:23:20+00:00"+ "time": "2026-08-05T19:48:21+00:00"},{"name": "guzzlehttp/promises",- "version": "2.5.1",+ "version": "2.5.2","source": {"type": "git","url": "https://github.com/guzzle/promises.git",- "reference": "9ad1e4fc607446a055b95870c7f668e93b5cff29"+ "reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/guzzle/promises/zipball/9ad1e4fc607446a055b95870c7f668e93b5cff29",- "reference": "9ad1e4fc607446a055b95870c7f668e93b5cff29",+ "url": "https://api.github.com/repos/guzzle/promises/zipball/2823687acff28b2dbe67b2508a6b300e2c3fa4ce",+ "reference": "2823687acff28b2dbe67b2508a6b300e2c3fa4ce","shasum": ""},"require": {@@ -1472,7 +1549,7 @@],"support": {"issues": "https://github.com/guzzle/promises/issues",- "source": "https://github.com/guzzle/promises/tree/2.5.1"+ "source": "https://github.com/guzzle/promises/tree/2.5.2"},"funding": [{@@ -1488,7 +1565,7 @@"type": "tidelift"}],- "time": "2026-07-08T15:48:39+00:00"+ "time": "2026-08-05T19:30:54+00:00"},{"name": "guzzlehttp/psr7",@@ -1982,16 +2059,16 @@},{"name": "laravel/boost",- "version": "v2.4.8",+ "version": "v2.5.0","source": {"type": "git","url": "https://github.com/laravel/boost.git",- "reference": "d11d720cf9537f8d236a11d973e99563a598ec9c"+ "reference": "f6b054dcbc0aacf1d187128edf7d917c6d99792a"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/boost/zipball/d11d720cf9537f8d236a11d973e99563a598ec9c",- "reference": "d11d720cf9537f8d236a11d973e99563a598ec9c",+ "url": "https://api.github.com/repos/laravel/boost/zipball/f6b054dcbc0aacf1d187128edf7d917c6d99792a",+ "reference": "f6b054dcbc0aacf1d187128edf7d917c6d99792a","shasum": ""},"require": {@@ -2000,9 +2077,9 @@"illuminate/contracts": "^11.45.3|^12.41.1|^13.0","illuminate/routing": "^11.45.3|^12.41.1|^13.0","illuminate/support": "^11.45.3|^12.41.1|^13.0",- "laravel/mcp": "^0.5.1|^0.6.0|~0.7.0,<0.7.1",+ "laravel/mcp": "^0.7.1|^0.8.0|^0.9.0","laravel/prompts": "^0.3.10",- "laravel/roster": "^0.5.0",+ "laravel/roster": "^1.0.0","php": "^8.2"},"require-dev": {@@ -2044,7 +2121,7 @@"issues": "https://github.com/laravel/boost/issues","source": "https://github.com/laravel/boost"},- "time": "2026-05-19T20:09:50+00:00"+ "time": "2026-08-04T21:10:39+00:00"},{"name": "laravel/cashier",@@ -2137,16 +2214,16 @@},{"name": "laravel/framework",- "version": "v13.23.0",+ "version": "v13.24.0","source": {"type": "git","url": "https://github.com/laravel/framework.git",- "reference": "92a707229148e57f08a249211c8a5a194159c619"+ "reference": "6d481710375d2aa67656922ef760cdd2b18bcfe0"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/framework/zipball/92a707229148e57f08a249211c8a5a194159c619",- "reference": "92a707229148e57f08a249211c8a5a194159c619",+ "url": "https://api.github.com/repos/laravel/framework/zipball/6d481710375d2aa67656922ef760cdd2b18bcfe0",+ "reference": "6d481710375d2aa67656922ef760cdd2b18bcfe0","shasum": ""},"require": {@@ -2166,7 +2243,7 @@"guzzlehttp/guzzle": "^7.8.2","guzzlehttp/promises": "^2.0.3","guzzlehttp/uri-template": "^1.0",- "laravel/prompts": "^0.3.0",+ "laravel/prompts": "^0.3.11","laravel/serializable-closure": "^2.0.10","league/commonmark": "^2.8.1","league/flysystem": "^3.25.1",@@ -2360,7 +2437,7 @@"issues": "https://github.com/laravel/framework/issues","source": "https://github.com/laravel/framework"},- "time": "2026-07-27T14:48:58+00:00"+ "time": "2026-08-04T15:54:59+00:00"},{"name": "laravel/horizon",@@ -2444,16 +2521,16 @@},{"name": "laravel/mcp",- "version": "v0.6.7",+ "version": "v0.9.1","source": {"type": "git","url": "https://github.com/laravel/mcp.git",- "reference": "c3775e57b95d7eadb580d543689d9971ec8721f2"+ "reference": "a08884d79a95c5143498507aec5badf751cdbec4"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/mcp/zipball/c3775e57b95d7eadb580d543689d9971ec8721f2",- "reference": "c3775e57b95d7eadb580d543689d9971ec8721f2",+ "url": "https://api.github.com/repos/laravel/mcp/zipball/a08884d79a95c5143498507aec5badf751cdbec4",+ "reference": "a08884d79a95c5143498507aec5badf751cdbec4","shasum": ""},"require": {@@ -2467,7 +2544,8 @@"illuminate/routing": "^11.45.3|^12.41.1|^13.0","illuminate/support": "^11.45.3|^12.41.1|^13.0","illuminate/validation": "^11.45.3|^12.41.1|^13.0",- "php": "^8.2"+ "php": "^8.2",+ "symfony/process": "^7.4.5|^8.0.5"},"require-dev": {"laravel/pint": "^1.20",@@ -2480,7 +2558,7 @@"extra": {"laravel": {"aliases": {- "Mcp": "Laravel\\Mcp\\Server\\Facades\\Mcp"+ "Mcp": "Laravel\\Mcp\\Facades\\Mcp"},"providers": ["Laravel\\Mcp\\Server\\McpServiceProvider"@@ -2513,7 +2591,7 @@"issues": "https://github.com/laravel/mcp/issues","source": "https://github.com/laravel/mcp"},- "time": "2026-04-15T08:30:42+00:00"+ "time": "2026-07-21T13:23:52+00:00"},{"name": "laravel/nightwatch",@@ -2686,16 +2764,16 @@},{"name": "laravel/prompts",- "version": "v0.3.21",+ "version": "v0.3.22","source": {"type": "git","url": "https://github.com/laravel/prompts.git",- "reference": "7753c65c281c2550c7c183f14e18062073b7d821"+ "reference": "02b89b39e8972a998db4d5d4ad4719239dd4aee4"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/prompts/zipball/7753c65c281c2550c7c183f14e18062073b7d821",- "reference": "7753c65c281c2550c7c183f14e18062073b7d821",+ "url": "https://api.github.com/repos/laravel/prompts/zipball/02b89b39e8972a998db4d5d4ad4719239dd4aee4",+ "reference": "02b89b39e8972a998db4d5d4ad4719239dd4aee4","shasum": ""},"require": {@@ -2739,9 +2817,9 @@"description": "Add beautiful and user-friendly forms to your command-line applications.","support": {"issues": "https://github.com/laravel/prompts/issues",- "source": "https://github.com/laravel/prompts/tree/v0.3.21"+ "source": "https://github.com/laravel/prompts/tree/v0.3.22"},- "time": "2026-06-26T00:11:25+00:00"+ "time": "2026-08-04T14:50:50+00:00"},{"name": "laravel/reverb",@@ -2824,32 +2902,33 @@},{"name": "laravel/roster",- "version": "v0.5.1",+ "version": "v1.0.0","source": {"type": "git","url": "https://github.com/laravel/roster.git",- "reference": "5089de7615f72f78e831590ff9d0435fed0102bb"+ "reference": "89e518bd88ae98ff50f6082f6b517c8d8e8245fa"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/laravel/roster/zipball/5089de7615f72f78e831590ff9d0435fed0102bb",- "reference": "5089de7615f72f78e831590ff9d0435fed0102bb",+ "url": "https://api.github.com/repos/laravel/roster/zipball/89e518bd88ae98ff50f6082f6b517c8d8e8245fa",+ "reference": "89e518bd88ae98ff50f6082f6b517c8d8e8245fa","shasum": ""},"require": {+ "composer/semver": "^3.0","illuminate/console": "^11.0|^12.0|^13.0","illuminate/contracts": "^11.0|^12.0|^13.0",- "illuminate/routing": "^11.0|^12.0|^13.0","illuminate/support": "^11.0|^12.0|^13.0","php": "^8.2","symfony/yaml": "^7.2|^8.0"},"require-dev": {- "laravel/pint": "^1.14",+ "laravel/pint": "^1.29","mockery/mockery": "^1.6","orchestra/testbench": "^9.0|^10.0|^11.0","pestphp/pest": "^3.0|^4.1",- "phpstan/phpstan": "^2.0"+ "phpstan/phpstan": "^2.0",+ "rector/rector": "^2.0"},"type": "library","extra": {@@ -2881,7 +2960,7 @@"issues": "https://github.com/laravel/roster/issues","source": "https://github.com/laravel/roster"},- "time": "2026-03-05T07:58:43+00:00"+ "time": "2026-07-18T17:53:15+00:00"},{"name": "laravel/sentinel",@@ -3404,16 +3483,16 @@},{"name": "league/commonmark",- "version": "2.8.3",+ "version": "2.9.0","source": {"type": "git","url": "https://github.com/thephpleague/commonmark.git",- "reference": "1902f60f984235023acbe03db6ad614a37b3c3e7"+ "reference": "5703d83ba3da3b2e356a5fedc848ed6d8ffb6529"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/1902f60f984235023acbe03db6ad614a37b3c3e7",- "reference": "1902f60f984235023acbe03db6ad614a37b3c3e7",+ "url": "https://api.github.com/repos/thephpleague/commonmark/zipball/5703d83ba3da3b2e356a5fedc848ed6d8ffb6529",+ "reference": "5703d83ba3da3b2e356a5fedc848ed6d8ffb6529","shasum": ""},"require": {@@ -3450,7 +3529,7 @@"type": "library","extra": {"branch-alias": {- "dev-main": "2.9-dev"+ "dev-main": "2.10-dev"}},"autoload": {@@ -3507,7 +3586,7 @@"type": "tidelift"}],- "time": "2026-07-12T15:29:16+00:00"+ "time": "2026-08-03T13:42:31+00:00"},{"name": "league/config",@@ -10618,16 +10697,16 @@},{"name": "symfony/yaml",- "version": "v8.1.0",+ "version": "v8.1.2","source": {"type": "git","url": "https://github.com/symfony/yaml.git",- "reference": "efb42bd2c6f4f3ccfd4683583449938b5fc146b0"+ "reference": "faabdbe998e8c5c599dceffa27aa265b185c0736"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/symfony/yaml/zipball/efb42bd2c6f4f3ccfd4683583449938b5fc146b0",- "reference": "efb42bd2c6f4f3ccfd4683583449938b5fc146b0",+ "url": "https://api.github.com/repos/symfony/yaml/zipball/faabdbe998e8c5c599dceffa27aa265b185c0736",+ "reference": "faabdbe998e8c5c599dceffa27aa265b185c0736","shasum": ""},"require": {@@ -10670,7 +10749,7 @@"description": "Loads and dumps YAML files","homepage": "https://symfony.com","support": {- "source": "https://github.com/symfony/yaml/tree/v8.1.0"+ "source": "https://github.com/symfony/yaml/tree/v8.1.2"},"funding": [{@@ -10690,7 +10769,7 @@"type": "tidelift"}],- "time": "2026-05-29T05:06:50+00:00"+ "time": "2026-07-22T15:42:13+00:00"},{"name": "tijsverkoyen/css-to-inline-styles",diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.phpindex b1f2022a0..5222ec9a8 100644--- a/database/seeders/DatabaseSeeder.php+++ b/database/seeders/DatabaseSeeder.php@@ -14,8 +14,8 @@ class DatabaseSeeder extends Seederpublic function run(): void{$this->call([- PlanSeeder::class,PassportSeeder::class,+ PlanSeeder::class,]);}}diff --git a/database/seeders/PassportSeeder.php b/database/seeders/PassportSeeder.phpindex 32c5473eb..417c3a2bf 100644--- a/database/seeders/PassportSeeder.php+++ b/database/seeders/PassportSeeder.php@@ -5,20 +5,24 @@ declare(strict_types=1);namespace Database\Seeders;use Illuminate\Database\Seeder;+use Illuminate\Support\Facades\Cache;use Laravel\Passport\ClientRepository;+use RuntimeException;class PassportSeeder extends Seeder{public function run(ClientRepository $clients): void{- try {- $clients->personalAccessClient('users');+ Cache::lock('passport:personal-access-client', 30)->block(10, function () use ($clients): void {+ try {+ $clients->personalAccessClient('users');- return;- } catch (\RuntimeException) {- // No client yet — fall through to create.- }+ return;+ } catch (RuntimeException) {+ // No client yet — fall through to create.+ }- $clients->createPersonalAccessGrantClient(name: 'TryPost Personal Access Client');+ $clients->createPersonalAccessGrantClient(name: 'TryPost Personal Access Client');+ });}}diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 23aa100fa..8fdc403ab 100755--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -7,6 +7,17 @@ cd /var/www/htmlTARGET="${TRYPOST_TARGET:-dev}"+# One-off commands from `docker compose run app ...` must bypass the long-lived+# application bootstrap and execute exactly as requested.+if [ "$#" -gt 0 ]; then+ exec "$@"+fi++if [ "${TARGET}" = "production" ] && [ -z "${APP_KEY:-}" ]; then+ echo "[entrypoint] APP_KEY is required in production" >&2+ exit 1+fi+# 1) Bootstrap .env from the Docker template on first dev boot. The bind-mount# in dev hides /var/www/html/.env.docker.example, so prefer docker/ first.if [ "${TRYPOST_DOCKER_BOOTSTRAP:-0}" = "1" ] && [ ! -f .env ]; then@@ -65,7 +76,7 @@ done# 7) Run migrations (graceful: succeeds even when nothing to migrate).echo "[entrypoint] running migrations"-php artisan migrate --force --graceful || true+php artisan migrate --force# 8) storage:link if missing.if [ ! -L public/storage ]; then@@ -73,17 +84,31 @@ if [ ! -L public/storage ]; thenphp artisan storage:link --force || truefi-# 9) Passport keys on first boot.-if [ ! -f storage/oauth-private.key ]; then- echo "[entrypoint] generating Passport keys"- php artisan passport:keys --force || true+# 9) Passport keys. Prefer PASSPORT_PRIVATE_KEY / PASSPORT_PUBLIC_KEY from+# the environment (required for durable / multi-node deploys — storage/oauth-*+# is not on a persisted volume in compose.prod.yaml). Fall back to generating+# files under storage/ only for local/dev when those env vars are unset.+if [ -n "${PASSPORT_PRIVATE_KEY:-}" ] && [ -n "${PASSPORT_PUBLIC_KEY:-}" ]; then+ echo "[entrypoint] using Passport keys from environment"+elif [ "${TRYPOST_TARGET:-}" = "production" ] || [ "${APP_ENV:-}" = "production" ]; then+ echo "[entrypoint] ERROR: PASSPORT_PRIVATE_KEY and PASSPORT_PUBLIC_KEY must be set in production." >&2+ echo "[entrypoint] Generate once with: php artisan passport:keys --show" >&2+ exit 1+elif [ ! -f storage/oauth-private.key ] || [ ! -f storage/oauth-public.key ]; then+ echo "[entrypoint] generating Passport keys (dev fallback)"+ php artisan passport:keys --forcefi-# 10) Wayfinder TS regen — Vite needs the files before it boots.+# 10) Personal access client for REST API keys. The seeder is idempotent, so+# fresh self-hosted installs and existing deployments are both safe.+echo "[entrypoint] ensuring Passport personal access client"+php artisan db:seed --class='Database\Seeders\PassportSeeder' --force++# 11) Wayfinder TS regen — Vite needs the files before it boots.echo "[entrypoint] regenerating wayfinder helpers"php artisan wayfinder:generate --with-form || true-# 11) Cache strategy: prod = pre-cache; dev = clear.+# 12) Cache strategy: prod = pre-cache; dev = clear.if [ "${TARGET}" = "production" ]; thenphp artisan config:cachephp artisan route:cache@@ -96,7 +121,7 @@ elsephp artisan event:clearfi-# 12) Permissions. Production php-fpm pool runs as www-data (Alpine default),+# 13) Permissions. Production php-fpm pool runs as www-data (Alpine default),# so storage and bootstrap/cache must be writable by that user — Laravel# needs to write session files, view cache, log files, etc.if [ "${TARGET}" = "production" ]; thendiff --git a/lang/ar/mcp.php b/lang/ar/mcp.phpnew file mode 100644index 000000000..266cb93cf--- /dev/null+++ b/lang/ar/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'اربط مساعدي الذكاء الاصطناعي لإنشاء المنشورات وإدارتها بحساب TryPost الخاص بك.',+ 'copy_step' => 'انسخ عنوان خادم TryPost',+ 'open_step' => 'افتح مساعد الذكاء الاصطناعي',+ 'copy' => 'نسخ الرابط',+ 'connect' => 'الاتصال عبر :client',+ 'step_add' => 'الصق الاسم أو الرابط أو الإعداد أدناه في تطبيقك. يفتح تسجيل الدخول في المتصفح عند أول اتصال.',+ 'name_label' => 'الاسم',+ 'url_label' => 'رابط الخادم',+ 'config_label' => 'الإعداد',+ 'connected_title' => 'التطبيقات المتصلة',+ 'connected_description' => 'المساعدون الذين سجّلت الدخول إليهم. يمكنك قطع اتصال ما لم تعد تستخدمه.',+ 'connected_empty' => 'لا يوجد اتصال بعد. استخدم Claude أو ChatGPT أو عميلًا آخر أعلاه.',+ 'disconnect' => 'قطع الاتصال',+ 'disconnect_title' => 'قطع اتصال التطبيق',+ 'disconnect_confirm' => 'يؤدي هذا إلى تسجيل خروج التطبيق من TryPost. سيحتاج إلى إعادة الاتصال قبل استخدام MCP مجددًا.',+ 'disconnected' => 'تم قطع اتصال التطبيق.',+ 'copied' => 'تم النسخ',+ 'last_used' => 'آخر استخدام',+ 'never' => 'أبدًا',+ 'documentation_title' => 'التوثيق',+ 'documentation_description' => 'أدلة الإعداد لكل عميل، والأدوات المتاحة، وحل المشكلات.',+ 'view_docs' => 'عرض التوثيق',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'تطبيقات أخرى',+ 'other_clients_description' => 'Cursor وVS Code وClaude Code وأي تطبيق يدعم MCP.',++ 'clients' => [+ 'claude' => 'افتح Settings → Connectors، أضِف موصلًا مخصصًا، ثم الصق الرابط أعلاه.',+ 'chatgpt' => 'افتح Settings → Apps & Connectors، أنشئ موصلًا مخصصًا، ثم الصق الرابط أعلاه.',+ 'cursor' => 'أضف TryPost كخادم MCP بعيد في Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'الصق الإعداد أدناه في إعدادات MCP في VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'الصق الإعداد أدناه في إعدادات MCP في Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'يعمل مع أي عميل يقرأ إعداد mcpServers.',+ 'other_name' => 'أخرى',+ ],+];diff --git a/lang/ar/settings.php b/lang/ar/settings.phpindex 36c2ecad1..d3dc72c88 100644--- a/lang/ar/settings.php+++ b/lang/ar/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'العلامة التجارية','users' => 'الأعضاء','api_keys' => 'مفاتيح API',+ 'mcp' => 'MCP',],'title' => 'إعدادات مساحة العمل','logo_heading' => 'شعار مساحة العمل',diff --git a/lang/ar/sidebar.php b/lang/ar/sidebar.phpindex 7203369ae..08691c29b 100644--- a/lang/ar/sidebar.php+++ b/lang/ar/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'التوقيعات','labels' => 'التسميات','assets' => 'الوسائط',+ 'mcp' => 'MCP','api_keys' => 'مفاتيح API',],diff --git a/lang/de/mcp.php b/lang/de/mcp.phpnew file mode 100644index 000000000..f81312267--- /dev/null+++ b/lang/de/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Verbinde KI-Assistenten mit deinem TryPost-Workspace. Sie nutzen dieselben Berechtigungen wie jeder angemeldete Nutzer.',+ 'copy_step' => 'Kopiere deine TryPost-Server-URL',+ 'open_step' => 'Öffne deinen KI-Assistenten',+ 'copy' => 'URL kopieren',+ 'connect' => 'Mit :client verbinden',+ 'step_add' => 'Füge Name, URL oder Config unten in deine App ein. Die Anmeldung öffnet sich beim ersten Verbinden im Browser.',+ 'name_label' => 'Name',+ 'url_label' => 'Server-URL',+ 'config_label' => 'Config',+ 'connected_title' => 'Verbundene Apps',+ 'connected_description' => 'Assistenten, mit denen du dich angemeldet hast. Trenne Verbindungen, die du nicht mehr brauchst.',+ 'connected_empty' => 'Noch nichts verbunden. Nutze Claude, ChatGPT oder einen anderen Client oben.',+ 'disconnect' => 'Trennen',+ 'disconnect_title' => 'App trennen',+ 'disconnect_confirm' => 'Dadurch wird die App von TryPost abgemeldet. Sie muss sich neu verbinden, bevor sie MCP wieder nutzen kann.',+ 'disconnected' => 'App getrennt.',+ 'copied' => 'Kopiert',+ 'last_used' => 'Zuletzt verwendet',+ 'never' => 'Nie',+ 'documentation_title' => 'Dokumentation',+ 'documentation_description' => 'Einrichtungsguides pro Client, verfügbare Tools und Fehlerhilfe.',+ 'view_docs' => 'Dokumentation ansehen',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Andere Apps',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code und alles andere, das MCP spricht.',++ 'clients' => [+ 'claude' => 'Öffne Settings → Connectors, füge einen benutzerdefinierten Connector hinzu und füge die URL oben ein.',+ 'chatgpt' => 'Öffne Settings → Apps & Connectors, erstelle einen benutzerdefinierten Connector und füge die URL oben ein.',+ 'cursor' => 'Füge TryPost in Cursor als Remote-MCP-Server hinzu.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Füge die Konfiguration unten in die MCP-Einstellungen von VS Code ein.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Füge die Konfiguration unten in die MCP-Einstellungen von Claude Code ein.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Funktioniert mit jedem Client, der eine mcpServers-Config liest.',+ 'other_name' => 'Andere',+ ],+];diff --git a/lang/de/settings.php b/lang/de/settings.phpindex 9ef23eb1b..e1bfc9991 100644--- a/lang/de/settings.php+++ b/lang/de/settings.php@@ -131,6 +131,7 @@ return ['brand' => 'Marke','users' => 'Mitglieder','api_keys' => 'API-Keys',+ 'mcp' => 'MCP',],'title' => 'Workspace-Einstellungen','logo_heading' => 'Workspace-Logo',diff --git a/lang/de/sidebar.php b/lang/de/sidebar.phpindex d6cb835c1..35872c7d1 100644--- a/lang/de/sidebar.php+++ b/lang/de/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Signaturen','labels' => 'Labels','assets' => 'Assets',+ 'mcp' => 'MCP','api_keys' => 'API-Keys',],diff --git a/lang/el/mcp.php b/lang/el/mcp.phpnew file mode 100644index 000000000..7fc07e3ed--- /dev/null+++ b/lang/el/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Συνδέστε βοηθούς AI για να δημιουργούν και να διαχειρίζονται αναρτήσεις με τον λογαριασμό TryPost σας.',+ 'copy_step' => 'Αντίγραψε το URL του διακομιστή TryPost',+ 'open_step' => 'Άνοιξε τον βοηθό AI σου',+ 'copy' => 'Αντιγραφή URL',+ 'connect' => 'Σύνδεση με :client',+ 'step_add' => 'Επικολλήστε το όνομα, το URL ή το config παρακάτω στην εφαρμογή σας. Η σύνδεση ανοίγει στο πρόγραμμα περιήγησης την πρώτη φορά.',+ 'name_label' => 'Όνομα',+ 'url_label' => 'URL διακομιστή',+ 'config_label' => 'Config',+ 'connected_title' => 'Συνδεδεμένες εφαρμογές',+ 'connected_description' => 'Βοηθοί στους οποίους έχετε συνδεθεί. Μπορείτε να αποσυνδέσετε όσους δεν χρησιμοποιείτε πλέον.',+ 'connected_empty' => 'Τίποτα συνδεδεμένο ακόμα. Χρησιμοποιήστε Claude, ChatGPT ή άλλο client παραπάνω.',+ 'disconnect' => 'Αποσύνδεση',+ 'disconnect_title' => 'Αποσύνδεση εφαρμογής',+ 'disconnect_confirm' => 'Αυτό αποσυνδέει την εφαρμογή από το TryPost. Θα χρειαστεί να συνδεθεί ξανά πριν χρησιμοποιήσει το MCP.',+ 'disconnected' => 'Η εφαρμογή αποσυνδέθηκε.',+ 'copied' => 'Αντιγράφηκε',+ 'last_used' => 'Τελευταία χρήση',+ 'never' => 'Ποτέ',+ 'documentation_title' => 'Τεκμηρίωση',+ 'documentation_description' => 'Οδηγοί ανά client, διαθέσιμα tools και αντιμετώπιση προβλημάτων.',+ 'view_docs' => 'Δείτε την τεκμηρίωση',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Άλλες εφαρμογές',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code και ό,τι άλλο μιλάει MCP.',++ 'clients' => [+ 'claude' => 'Άνοιξε Settings → Connectors, πρόσθεσε έναν προσαρμοσμένο connector και επικόλλησε το παραπάνω URL.',+ 'chatgpt' => 'Άνοιξε Settings → Apps & Connectors, δημιούργησε έναν προσαρμοσμένο connector και επικόλλησε το παραπάνω URL.',+ 'cursor' => 'Προσθέστε το TryPost ως απομακρυσμένο MCP server στο Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Επικολλήστε το config παρακάτω στις ρυθμίσεις MCP του VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Επικολλήστε το config παρακάτω στις ρυθμίσεις MCP του Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Λειτουργεί με κάθε client που διαβάζει config mcpServers.',+ 'other_name' => 'Άλλα',+ ],+];diff --git a/lang/el/settings.php b/lang/el/settings.phpindex 29dda286d..3ce5941f8 100644--- a/lang/el/settings.php+++ b/lang/el/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Μάρκα','users' => 'Μέλη','api_keys' => 'Κλειδιά API',+ 'mcp' => 'MCP',],'title' => 'Ρυθμίσεις workspace','logo_heading' => 'Λογότυπο workspace',diff --git a/lang/el/sidebar.php b/lang/el/sidebar.phpindex 5c011ccc1..de0a14c74 100644--- a/lang/el/sidebar.php+++ b/lang/el/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Υπογραφές','labels' => 'Ετικέτες','assets' => 'Στοιχεία',+ 'mcp' => 'MCP','api_keys' => 'Κλειδιά API',],diff --git a/lang/en/mcp.php b/lang/en/mcp.phpnew file mode 100644index 000000000..5bfe9ef2d--- /dev/null+++ b/lang/en/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Connect AI assistants to your TryPost workspace. They use the same permissions as each signed-in user.',+ 'copy_step' => 'Copy your TryPost server URL',+ 'open_step' => 'Open your AI assistant',+ 'copy' => 'Copy URL',+ 'connect' => 'Connect with :client',+ 'step_add' => 'Paste the name, URL, or config below into your app. Sign-in opens in the browser the first time it connects.',+ 'name_label' => 'Name',+ 'url_label' => 'Server URL',+ 'config_label' => 'Config',+ 'connected_title' => 'Connected apps',+ 'connected_description' => 'Assistants you\'ve signed in with. You can disconnect any you no longer use.',+ 'connected_empty' => 'Nothing connected yet. Use Claude, ChatGPT, or another client above.',+ 'disconnect' => 'Disconnect',+ 'disconnect_title' => 'Disconnect app',+ 'disconnect_confirm' => 'This signs the app out of TryPost. It will need to reconnect before it can use MCP again.',+ 'disconnected' => 'App disconnected.',+ 'copied' => 'Copied',+ 'last_used' => 'Last used',+ 'never' => 'Never',+ 'documentation_title' => 'Documentation',+ 'documentation_description' => 'Client setup guides, available tools, and troubleshooting.',+ 'view_docs' => 'View docs',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Other apps',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code, and anything else that speaks MCP.',++ 'clients' => [+ 'claude' => 'Open Settings → Connectors, add a custom connector, then paste the URL above.',+ 'chatgpt' => 'Open Settings → Apps & Connectors, create a custom connector, then paste the URL above.',+ 'cursor' => 'Add TryPost as a remote MCP server in Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Paste the config below into VS Code\'s MCP settings.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Paste the config below into Claude Code\'s MCP settings.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Works with any client that reads an mcpServers config.',+ 'other_name' => 'Other',+ ],+];diff --git a/lang/en/settings.php b/lang/en/settings.phpindex 52556caae..b4b7dc806 100644--- a/lang/en/settings.php+++ b/lang/en/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Brand','users' => 'Members','api_keys' => 'API Keys',+ 'mcp' => 'MCP',],'title' => 'Workspace settings','logo_heading' => 'Workspace logo',diff --git a/lang/en/sidebar.php b/lang/en/sidebar.phpindex eef5ebbc2..0e2b2a04a 100644--- a/lang/en/sidebar.php+++ b/lang/en/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Signatures','labels' => 'Labels','assets' => 'Assets',+ 'mcp' => 'MCP','api_keys' => 'API Keys',],diff --git a/lang/es/mcp.php b/lang/es/mcp.phpnew file mode 100644index 000000000..5a4a82f56--- /dev/null+++ b/lang/es/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Conecta asistentes de IA a tu workspace de TryPost. Usan los mismos permisos que cada usuario conectado.',+ 'copy_step' => 'Copia la URL del servidor TryPost',+ 'open_step' => 'Abre tu asistente de IA',+ 'copy' => 'Copiar URL',+ 'connect' => 'Conectar con :client',+ 'step_add' => 'Pega el nombre, la URL o la config abajo en tu app. El inicio de sesión se abre en el navegador la primera vez.',+ 'name_label' => 'Nombre',+ 'url_label' => 'URL del servidor',+ 'config_label' => 'Config',+ 'connected_title' => 'Apps conectadas',+ 'connected_description' => 'Asistentes con los que has iniciado sesión. Puedes desconectar los que ya no uses.',+ 'connected_empty' => 'Nada conectado aún. Usa Claude, ChatGPT u otro cliente arriba.',+ 'disconnect' => 'Desconectar',+ 'disconnect_title' => 'Desconectar app',+ 'disconnect_confirm' => 'Esto cierra la sesión de la app en TryPost. Tendrá que reconectar para usar MCP otra vez.',+ 'disconnected' => 'App desconectada.',+ 'copied' => 'Copiado',+ 'last_used' => 'Último uso',+ 'never' => 'Nunca',+ 'documentation_title' => 'Documentación',+ 'documentation_description' => 'Guías por cliente, tools disponibles y solución de problemas.',+ 'view_docs' => 'Ver documentación',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Otras apps',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code y cualquier app que hable MCP.',++ 'clients' => [+ 'claude' => 'Abre Settings → Connectors, añade un conector personalizado y pega la URL de arriba.',+ 'chatgpt' => 'Abre Settings → Apps & Connectors, crea un conector personalizado y pega la URL de arriba.',+ 'cursor' => 'Añade TryPost como servidor MCP remoto en Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Pega la configuración de abajo en los ajustes MCP de VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Pega la configuración de abajo en los ajustes MCP de Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Funciona con cualquier cliente que lea una config mcpServers.',+ 'other_name' => 'Otros',+ ],+];diff --git a/lang/es/settings.php b/lang/es/settings.phpindex 466776ab1..44310f2b3 100644--- a/lang/es/settings.php+++ b/lang/es/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Marca','users' => 'Miembros','api_keys' => 'API Keys',+ 'mcp' => 'MCP',],'title' => 'Configuración del workspace','logo_heading' => 'Logo del workspace',diff --git a/lang/es/sidebar.php b/lang/es/sidebar.phpindex 82a4559a3..b5804ae65 100644--- a/lang/es/sidebar.php+++ b/lang/es/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Firmas','labels' => 'Etiquetas','assets' => 'Medios',+ 'mcp' => 'MCP','api_keys' => 'API Keys',],diff --git a/lang/fr/mcp.php b/lang/fr/mcp.phpnew file mode 100644index 000000000..9cf541e54--- /dev/null+++ b/lang/fr/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Connectez des assistants IA à votre workspace TryPost. Ils utilisent les mêmes permissions que chaque utilisateur connecté.',+ 'copy_step' => 'Copiez l’URL du serveur TryPost',+ 'open_step' => 'Ouvrez votre assistant IA',+ 'copy' => 'Copier l’URL',+ 'connect' => 'Connecter avec :client',+ 'step_add' => 'Collez le nom, l’URL ou la config ci-dessous dans votre app. La connexion s’ouvre dans le navigateur la première fois.',+ 'name_label' => 'Nom',+ 'url_label' => 'URL du serveur',+ 'config_label' => 'Config',+ 'connected_title' => 'Apps connectées',+ 'connected_description' => 'Assistants auxquels vous vous êtes connecté. Déconnectez ceux dont vous n’avez plus besoin.',+ 'connected_empty' => 'Rien de connecté pour l’instant. Utilisez Claude, ChatGPT ou un autre client ci-dessus.',+ 'disconnect' => 'Déconnecter',+ 'disconnect_title' => 'Déconnecter l’app',+ 'disconnect_confirm' => 'Cela déconnecte l’app de TryPost. Elle devra se reconnecter pour utiliser MCP à nouveau.',+ 'disconnected' => 'App déconnectée.',+ 'copied' => 'Copié',+ 'last_used' => 'Dernière utilisation',+ 'never' => 'Jamais',+ 'documentation_title' => 'Documentation',+ 'documentation_description' => 'Guides par client, tools disponibles et dépannage.',+ 'view_docs' => 'Voir la documentation',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Autres apps',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code et toute app qui parle MCP.',++ 'clients' => [+ 'claude' => 'Ouvrez Settings → Connectors, ajoutez un connecteur personnalisé, puis collez l’URL ci-dessus.',+ 'chatgpt' => 'Ouvrez Settings → Apps & Connectors, créez un connecteur personnalisé, puis collez l’URL ci-dessus.',+ 'cursor' => 'Ajoutez TryPost comme serveur MCP distant dans Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Collez la configuration ci-dessous dans les paramètres MCP de VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Collez la configuration ci-dessous dans les paramètres MCP de Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Fonctionne avec tout client qui lit une config mcpServers.',+ 'other_name' => 'Autres',+ ],+];diff --git a/lang/fr/settings.php b/lang/fr/settings.phpindex 8bfad5800..2cede7c15 100644--- a/lang/fr/settings.php+++ b/lang/fr/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Marque','users' => 'Membres','api_keys' => 'Clés API',+ 'mcp' => 'MCP',],'title' => 'Paramètres de l\'espace de travail','logo_heading' => 'Logo de l\'espace de travail',diff --git a/lang/fr/sidebar.php b/lang/fr/sidebar.phpindex e3fc1fd00..fa9b76d61 100644--- a/lang/fr/sidebar.php+++ b/lang/fr/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Signatures','labels' => 'Étiquettes','assets' => 'Médias',+ 'mcp' => 'MCP','api_keys' => 'Clés API',],diff --git a/lang/it/mcp.php b/lang/it/mcp.phpnew file mode 100644index 000000000..9c5fd6629--- /dev/null+++ b/lang/it/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Collega assistenti IA al tuo workspace TryPost. Usano le stesse autorizzazioni di ogni utente connesso.',+ 'copy_step' => 'Copia l’URL del server TryPost',+ 'open_step' => 'Apri il tuo assistente IA',+ 'copy' => 'Copia URL',+ 'connect' => 'Collega con :client',+ 'step_add' => 'Incolla nome, URL o config qui sotto nella tua app. Il login si apre nel browser al primo collegamento.',+ 'name_label' => 'Nome',+ 'url_label' => 'URL del server',+ 'config_label' => 'Config',+ 'connected_title' => 'App collegate',+ 'connected_description' => 'Assistenti a cui hai effettuato l’accesso. Puoi disconnettere quelli che non usi più.',+ 'connected_empty' => 'Nessuna connessione ancora. Usa Claude, ChatGPT o un altro client sopra.',+ 'disconnect' => 'Scollega',+ 'disconnect_title' => 'Scollega app',+ 'disconnect_confirm' => 'Questo scollega l’app da TryPost. Dovrà riconnettersi prima di usare di nuovo MCP.',+ 'disconnected' => 'App scollegata.',+ 'copied' => 'Copiato',+ 'last_used' => 'Ultimo uso',+ 'never' => 'Mai',+ 'documentation_title' => 'Documentazione',+ 'documentation_description' => 'Guide per client, tools disponibili e risoluzione problemi.',+ 'view_docs' => 'Vedi documentazione',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Altre app',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code e qualsiasi app che parla MCP.',++ 'clients' => [+ 'claude' => 'Apri Settings → Connectors, aggiungi un connettore personalizzato e incolla l’URL qui sopra.',+ 'chatgpt' => 'Apri Settings → Apps & Connectors, crea un connettore personalizzato e incolla l’URL qui sopra.',+ 'cursor' => 'Aggiungi TryPost come server MCP remoto in Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Incolla la config qui sotto nelle impostazioni MCP di VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Incolla la config qui sotto nelle impostazioni MCP di Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Funziona con qualsiasi client che legge una config mcpServers.',+ 'other_name' => 'Altri',+ ],+];diff --git a/lang/it/settings.php b/lang/it/settings.phpindex 3c3708c1f..08f8e3417 100644--- a/lang/it/settings.php+++ b/lang/it/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Brand','users' => 'Membri','api_keys' => 'Chiavi API',+ 'mcp' => 'MCP',],'title' => 'Impostazioni del workspace','logo_heading' => 'Logo del workspace',diff --git a/lang/it/sidebar.php b/lang/it/sidebar.phpindex 2412acca7..3bf70c495 100644--- a/lang/it/sidebar.php+++ b/lang/it/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Firme','labels' => 'Etichette','assets' => 'Risorse',+ 'mcp' => 'MCP','api_keys' => 'Chiavi API',],diff --git a/lang/ja/mcp.php b/lang/ja/mcp.phpnew file mode 100644index 000000000..6d62d16e4--- /dev/null+++ b/lang/ja/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'TryPostアカウントで投稿の作成・管理ができるよう、AIアシスタントを接続します。',+ 'copy_step' => 'TryPostサーバーURLをコピー',+ 'open_step' => 'AIアシスタントを開く',+ 'copy' => 'URLをコピー',+ 'connect' => ':clientで接続',+ 'step_add' => '下の名前・URL・設定をアプリに貼り付けてください。初回接続時はブラウザでログインが開きます。',+ 'name_label' => '名前',+ 'url_label' => 'サーバーURL',+ 'config_label' => '設定',+ 'connected_title' => '接続済みアプリ',+ 'connected_description' => 'サインインしたアシスタントです。不要な接続は切断できます。',+ 'connected_empty' => 'まだ接続がありません。上の Claude、ChatGPT、または他のクライアントを使ってください。',+ 'disconnect' => '切断',+ 'disconnect_title' => 'アプリを切断',+ 'disconnect_confirm' => 'TryPostからアプリを切断します。再度MCPを使うには再接続が必要です。',+ 'disconnected' => 'アプリを切断しました。',+ 'copied' => 'コピーしました',+ 'last_used' => '最終使用',+ 'never' => 'なし',+ 'documentation_title' => 'ドキュメント',+ 'documentation_description' => 'クライアント別のセットアップ、利用可能なツール、トラブルシューティング。',+ 'view_docs' => 'ドキュメントを見る',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'その他のアプリ',+ 'other_clients_description' => 'Cursor、VS Code、Claude Code、その他MCP対応アプリ。',++ 'clients' => [+ 'claude' => 'Settings → Connectors を開き、カスタムコネクタを追加して上のURLを貼り付けます。',+ 'chatgpt' => 'Settings → Apps & Connectors を開き、カスタムコネクタを作成して上のURLを貼り付けます。',+ 'cursor' => 'CursorでTryPostをリモートMCPサーバーとして追加します。',+ 'cursor_name' => 'Cursor',+ 'vscode' => '下の設定をVS CodeのMCP設定に貼り付けます。',+ 'vscode_name' => 'VS Code',+ 'claude_code' => '下の設定をClaude CodeのMCP設定に貼り付けます。',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'mcpServers設定を読むクライアントならどれでも使えます。',+ 'other_name' => 'その他',+ ],+];diff --git a/lang/ja/settings.php b/lang/ja/settings.phpindex cdf5aa5c8..94e76beb7 100644--- a/lang/ja/settings.php+++ b/lang/ja/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'ブランド','users' => 'メンバー','api_keys' => 'API キー',+ 'mcp' => 'MCP',],'title' => 'ワークスペース設定','logo_heading' => 'ワークスペースのロゴ',diff --git a/lang/ja/sidebar.php b/lang/ja/sidebar.phpindex 5afd811c1..4c55a7993 100644--- a/lang/ja/sidebar.php+++ b/lang/ja/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => '署名','labels' => 'ラベル','assets' => 'アセット',+ 'mcp' => 'MCP','api_keys' => 'API キー',],diff --git a/lang/ko/mcp.php b/lang/ko/mcp.phpnew file mode 100644index 000000000..54583ff18--- /dev/null+++ b/lang/ko/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'TryPost 계정으로 게시물을 만들고 관리할 수 있도록 AI 어시스턴트를 연결하세요.',+ 'copy_step' => 'TryPost 서버 URL 복사',+ 'open_step' => 'AI 어시스턴트 열기',+ 'copy' => 'URL 복사',+ 'connect' => ':client로 연결',+ 'step_add' => '아래 이름, URL 또는 설정을 앱에 붙여넣으세요. 처음 연결할 때 브라우저에서 로그인이 열립니다.',+ 'name_label' => '이름',+ 'url_label' => '서버 URL',+ 'config_label' => '설정',+ 'connected_title' => '연결된 앱',+ 'connected_description' => '로그인한 어시스턴트입니다. 더 이상 쓰지 않는 연결은 해제할 수 있습니다.',+ 'connected_empty' => '아직 연결된 앱이 없습니다. 위의 Claude, ChatGPT 또는 다른 클라이언트를 사용하세요.',+ 'disconnect' => '연결 해제',+ 'disconnect_title' => '앱 연결 해제',+ 'disconnect_confirm' => 'TryPost에서 앱 로그인을 해제합니다. MCP를 다시 쓰려면 다시 연결해야 합니다.',+ 'disconnected' => '앱 연결이 해제되었습니다.',+ 'copied' => '복사됨',+ 'last_used' => '최근 사용',+ 'never' => '없음',+ 'documentation_title' => '문서',+ 'documentation_description' => '클라이언트별 설정 가이드, 사용 가능한 도구, 문제 해결.',+ 'view_docs' => '문서 보기',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => '다른 앱',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code 및 MCP를 지원하는 모든 앱.',++ 'clients' => [+ 'claude' => 'Settings → Connectors를 열고 커스텀 커넥터를 추가한 뒤 위 URL을 붙여넣으세요.',+ 'chatgpt' => 'Settings → Apps & Connectors를 열고 커스텀 커넥터를 만든 뒤 위 URL을 붙여넣으세요.',+ 'cursor' => 'Cursor에서 TryPost를 원격 MCP 서버로 추가하세요.',+ 'cursor_name' => 'Cursor',+ 'vscode' => '아래 설정을 VS Code MCP 설정에 붙여넣으세요.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => '아래 설정을 Claude Code MCP 설정에 붙여넣으세요.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'mcpServers 설정을 읽는 모든 클라이언트에서 동작합니다.',+ 'other_name' => '기타',+ ],+];diff --git a/lang/ko/settings.php b/lang/ko/settings.phpindex d20f1cdf9..77fb6569b 100644--- a/lang/ko/settings.php+++ b/lang/ko/settings.php@@ -129,6 +129,7 @@ return ['brand' => '브랜드','users' => '멤버','api_keys' => 'API 키',+ 'mcp' => 'MCP',],'title' => '워크스페이스 설정','logo_heading' => '워크스페이스 로고',diff --git a/lang/ko/sidebar.php b/lang/ko/sidebar.phpindex 28c4995e4..4c935cd10 100644--- a/lang/ko/sidebar.php+++ b/lang/ko/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => '서명','labels' => '라벨','assets' => '에셋',+ 'mcp' => 'MCP','api_keys' => 'API 키',],diff --git a/lang/nl/mcp.php b/lang/nl/mcp.phpnew file mode 100644index 000000000..a5e296792--- /dev/null+++ b/lang/nl/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Koppel AI-assistenten aan je TryPost-workspace. Ze gebruiken dezelfde rechten als elke ingelogde gebruiker.',+ 'copy_step' => 'Kopieer je TryPost-server-URL',+ 'open_step' => 'Open je AI-assistent',+ 'copy' => 'URL kopiëren',+ 'connect' => 'Verbinden met :client',+ 'step_add' => 'Plak de naam, URL of config hieronder in je app. Inloggen opent in de browser bij de eerste verbinding.',+ 'name_label' => 'Naam',+ 'url_label' => 'Server-URL',+ 'config_label' => 'Config',+ 'connected_title' => 'Gekoppelde apps',+ 'connected_description' => 'Assistenten waarmee je bent ingelogd. Koppel apps los die je niet meer gebruikt.',+ 'connected_empty' => 'Nog niets gekoppeld. Gebruik Claude, ChatGPT of een andere client hierboven.',+ 'disconnect' => 'Ontkoppelen',+ 'disconnect_title' => 'App ontkoppelen',+ 'disconnect_confirm' => 'Dit logt de app uit bij TryPost. Hij moet opnieuw verbinden om MCP weer te gebruiken.',+ 'disconnected' => 'App ontkoppeld.',+ 'copied' => 'Gekopieerd',+ 'last_used' => 'Laatst gebruikt',+ 'never' => 'Nooit',+ 'documentation_title' => 'Documentatie',+ 'documentation_description' => 'Handleidingen per client, beschikbare tools en probleemoplossing.',+ 'view_docs' => 'Documentatie bekijken',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Andere apps',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code en alles wat MCP spreekt.',++ 'clients' => [+ 'claude' => 'Open Settings → Connectors, voeg een aangepaste connector toe en plak de URL hierboven.',+ 'chatgpt' => 'Open Settings → Apps & Connectors, maak een aangepaste connector aan en plak de URL hierboven.',+ 'cursor' => 'Voeg TryPost toe als remote MCP-server in Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Plak de config hieronder in de MCP-instellingen van VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Plak de config hieronder in de MCP-instellingen van Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Werkt met elke client die een mcpServers-config leest.',+ 'other_name' => 'Overig',+ ],+];diff --git a/lang/nl/settings.php b/lang/nl/settings.phpindex 78d7e05a1..46c1eb79d 100644--- a/lang/nl/settings.php+++ b/lang/nl/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Merk','users' => 'Leden','api_keys' => 'API-sleutels',+ 'mcp' => 'MCP',],'title' => 'Workspace-instellingen','logo_heading' => 'Workspace-logo',diff --git a/lang/nl/sidebar.php b/lang/nl/sidebar.phpindex fd8efbebe..86505bc07 100644--- a/lang/nl/sidebar.php+++ b/lang/nl/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Handtekeningen','labels' => 'Labels','assets' => 'Assets',+ 'mcp' => 'MCP','api_keys' => 'API-sleutels',],diff --git a/lang/pl/mcp.php b/lang/pl/mcp.phpnew file mode 100644index 000000000..91ab7033b--- /dev/null+++ b/lang/pl/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Połącz asystentów AI, aby tworzyli i zarządzali postami na koncie TryPost.',+ 'copy_step' => 'Skopiuj URL serwera TryPost',+ 'open_step' => 'Otwórz asystenta AI',+ 'copy' => 'Kopiuj URL',+ 'connect' => 'Połącz z :client',+ 'step_add' => 'Wklej nazwę, URL lub config poniżej do swojej aplikacji. Logowanie otworzy się w przeglądarce przy pierwszym połączeniu.',+ 'name_label' => 'Nazwa',+ 'url_label' => 'URL serwera',+ 'config_label' => 'Config',+ 'connected_title' => 'Połączone aplikacje',+ 'connected_description' => 'Asystenci, z którymi się zalogowałeś. Możesz rozłączyć te, których już nie używasz.',+ 'connected_empty' => 'Nic jeszcze nie połączono. Użyj Claude, ChatGPT lub innego klienta powyżej.',+ 'disconnect' => 'Rozłącz',+ 'disconnect_title' => 'Rozłącz aplikację',+ 'disconnect_confirm' => 'To wyloguje aplikację z TryPost. Musi połączyć się ponownie, zanim znów użyje MCP.',+ 'disconnected' => 'Aplikacja rozłączona.',+ 'copied' => 'Skopiowano',+ 'last_used' => 'Ostatnie użycie',+ 'never' => 'Nigdy',+ 'documentation_title' => 'Dokumentacja',+ 'documentation_description' => 'Przewodniki per klient, dostępne tools i rozwiązywanie problemów.',+ 'view_docs' => 'Zobacz dokumentację',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Inne aplikacje',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code i wszystko, co mówi MCP.',++ 'clients' => [+ 'claude' => 'Otwórz Settings → Connectors, dodaj niestandardowy connector, a następnie wklej powyższy URL.',+ 'chatgpt' => 'Otwórz Settings → Apps & Connectors, utwórz niestandardowy connector, a następnie wklej powyższy URL.',+ 'cursor' => 'Dodaj TryPost jako zdalny serwer MCP w Cursorze.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Wklej poniższą konfigurację w ustawieniach MCP VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Wklej poniższą konfigurację w ustawieniach MCP Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Działa z każdym klientem, który czyta config mcpServers.',+ 'other_name' => 'Inne',+ ],+];diff --git a/lang/pl/settings.php b/lang/pl/settings.phpindex bde5ddc37..89520348f 100644--- a/lang/pl/settings.php+++ b/lang/pl/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Marka','users' => 'Członkowie','api_keys' => 'Klucze API',+ 'mcp' => 'MCP',],'title' => 'Ustawienia przestrzeni roboczej','logo_heading' => 'Logo przestrzeni roboczej',diff --git a/lang/pl/sidebar.php b/lang/pl/sidebar.phpindex 1018dd8ed..5c3041d1a 100644--- a/lang/pl/sidebar.php+++ b/lang/pl/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Sygnatury','labels' => 'Etykiety','assets' => 'Zasoby',+ 'mcp' => 'MCP','api_keys' => 'Klucze API',],diff --git a/lang/pt-BR/mcp.php b/lang/pt-BR/mcp.phpnew file mode 100644index 000000000..977e39d64--- /dev/null+++ b/lang/pt-BR/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Conecte assistentes de IA ao seu workspace TryPost. Eles usam as mesmas permissões de cada usuário conectado.',+ 'copy_step' => 'Copie a URL do servidor TryPost',+ 'open_step' => 'Abra seu assistente de IA',+ 'copy' => 'Copiar URL',+ 'connect' => 'Conectar com :client',+ 'step_add' => 'Cole o nome, a URL ou o config abaixo no seu app. O login abre no navegador na primeira conexão.',+ 'name_label' => 'Nome',+ 'url_label' => 'URL do servidor',+ 'config_label' => 'Config',+ 'connected_title' => 'Apps conectados',+ 'connected_description' => 'Assistentes que você conectou. Desconecte os que não quiser mais usar.',+ 'connected_empty' => 'Nada conectado ainda. Use Claude, ChatGPT ou outro cliente acima.',+ 'disconnect' => 'Desconectar',+ 'disconnect_title' => 'Desconectar app',+ 'disconnect_confirm' => 'Isso desconecta o app do TryPost. Ele precisa reconectar pra usar o MCP de novo.',+ 'disconnected' => 'App desconectado.',+ 'copied' => 'Copiado',+ 'last_used' => 'Último uso',+ 'never' => 'Nunca',+ 'documentation_title' => 'Documentação',+ 'documentation_description' => 'Guias por cliente, tools disponíveis e solução de problemas.',+ 'view_docs' => 'Ver documentação',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Conectado como:',++ 'other_clients_title' => 'Outros apps',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code e qualquer app que fale MCP.',++ 'clients' => [+ 'claude' => 'Abra Settings → Connectors, adicione um connector customizado e cole a URL acima.',+ 'chatgpt' => 'Abra Settings → Apps & Connectors, crie um connector customizado e cole a URL acima.',+ 'cursor' => 'Adicione o TryPost como servidor MCP remoto no Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Cole o config abaixo nas configurações MCP do VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Cole o config abaixo nas configurações MCP do Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Funciona com qualquer cliente que leia um config mcpServers.',+ 'other_name' => 'Outros',+ ],+];diff --git a/lang/pt-BR/settings.php b/lang/pt-BR/settings.phpindex 3ba148481..1ec2a7936 100644--- a/lang/pt-BR/settings.php+++ b/lang/pt-BR/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Marca','users' => 'Membros','api_keys' => 'API Keys',+ 'mcp' => 'MCP',],'title' => 'Configurações do workspace','logo_heading' => 'Logo do workspace',diff --git a/lang/pt-BR/sidebar.php b/lang/pt-BR/sidebar.phpindex b090575ae..2edbfe599 100644--- a/lang/pt-BR/sidebar.php+++ b/lang/pt-BR/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Assinaturas','labels' => 'Etiquetas','assets' => 'Mídias',+ 'mcp' => 'MCP','api_keys' => 'API Keys',],diff --git a/lang/ru/mcp.php b/lang/ru/mcp.phpnew file mode 100644index 000000000..b00961cab--- /dev/null+++ b/lang/ru/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Подключите ИИ-ассистентов, чтобы они создавали и управляли постами в вашем аккаунте TryPost.',+ 'copy_step' => 'Скопируйте URL сервера TryPost',+ 'open_step' => 'Откройте ИИ-ассистента',+ 'copy' => 'Копировать URL',+ 'connect' => 'Подключить через :client',+ 'step_add' => 'Вставьте имя, URL или config ниже в своё приложение. Вход откроется в браузере при первом подключении.',+ 'name_label' => 'Имя',+ 'url_label' => 'URL сервера',+ 'config_label' => 'Config',+ 'connected_title' => 'Подключённые приложения',+ 'connected_description' => 'Ассистенты, в которые вы вошли. Отключите те, которыми больше не пользуетесь.',+ 'connected_empty' => 'Пока ничего не подключено. Используйте Claude, ChatGPT или другого клиента выше.',+ 'disconnect' => 'Отключить',+ 'disconnect_title' => 'Отключить приложение',+ 'disconnect_confirm' => 'Это выйдет из аккаунта TryPost в приложении. Нужно будет подключиться снова, чтобы снова использовать MCP.',+ 'disconnected' => 'Приложение отключено.',+ 'copied' => 'Скопировано',+ 'last_used' => 'Последнее использование',+ 'never' => 'Никогда',+ 'documentation_title' => 'Документация',+ 'documentation_description' => 'Гайды по клиентам, доступные tools и решение проблем.',+ 'view_docs' => 'Открыть документацию',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Другие приложения',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code и всё, что говорит на MCP.',++ 'clients' => [+ 'claude' => 'Откройте Settings → Connectors, добавьте свой connector и вставьте URL выше.',+ 'chatgpt' => 'Откройте Settings → Apps & Connectors, создайте свой connector и вставьте URL выше.',+ 'cursor' => 'Добавьте TryPost как удалённый MCP-сервер в Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Вставьте конфиг ниже в настройки MCP VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Вставьте конфиг ниже в настройки MCP Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Работает с любым клиентом, который читает config mcpServers.',+ 'other_name' => 'Другие',+ ],+];diff --git a/lang/ru/settings.php b/lang/ru/settings.phpindex 63b69024c..79cf9d15f 100644--- a/lang/ru/settings.php+++ b/lang/ru/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Бренд','users' => 'Участники','api_keys' => 'API-ключи',+ 'mcp' => 'MCP',],'title' => 'Настройки рабочего пространства','logo_heading' => 'Логотип рабочего пространства',diff --git a/lang/ru/sidebar.php b/lang/ru/sidebar.phpindex 8416f1c23..b6c0638b8 100644--- a/lang/ru/sidebar.php+++ b/lang/ru/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Подписи','labels' => 'Метки','assets' => 'Медиафайлы',+ 'mcp' => 'MCP','api_keys' => 'API-ключи',],diff --git a/lang/tr/mcp.php b/lang/tr/mcp.phpnew file mode 100644index 000000000..d77f75409--- /dev/null+++ b/lang/tr/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'TryPost hesabınızla gönderi oluşturup yönetmeleri için yapay zeka asistanlarını bağlayın.',+ 'copy_step' => 'TryPost sunucu URL’ini kopyala',+ 'open_step' => 'AI asistanını aç',+ 'copy' => 'URL’yi kopyala',+ 'connect' => ':client ile bağlan',+ 'step_add' => 'Adı, URL’yi veya config’i aşağıdaki gibi uygulamanıza yapıştırın. İlk bağlantıda oturum açma tarayıcıda açılır.',+ 'name_label' => 'Ad',+ 'url_label' => 'Sunucu URL’si',+ 'config_label' => 'Config',+ 'connected_title' => 'Bağlı uygulamalar',+ 'connected_description' => 'Giriş yaptığınız asistanlar. Artık kullanmadıklarınızın bağlantısını kesebilirsiniz.',+ 'connected_empty' => 'Henüz bağlı bir şey yok. Yukarıdan Claude, ChatGPT veya başka bir istemci kullanın.',+ 'disconnect' => 'Bağlantıyı kes',+ 'disconnect_title' => 'Uygulama bağlantısını kes',+ 'disconnect_confirm' => 'Bu, uygulamayı TryPost’tan çıkarır. MCP’yi yeniden kullanmak için tekrar bağlanması gerekir.',+ 'disconnected' => 'Uygulama bağlantısı kesildi.',+ 'copied' => 'Kopyalandı',+ 'last_used' => 'Son kullanım',+ 'never' => 'Hiç',+ 'documentation_title' => 'Dokümantasyon',+ 'documentation_description' => 'İstemci kurulum rehberleri, kullanılabilir tools ve sorun giderme.',+ 'view_docs' => 'Dokümantasyonu görüntüle',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Diğer uygulamalar',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code ve MCP konuşan diğer her şey.',++ 'clients' => [+ 'claude' => 'Settings → Connectors’ı aç, özel bir connector ekle ve yukarıdaki URL’yi yapıştır.',+ 'chatgpt' => 'Settings → Apps & Connectors’ı aç, özel bir connector oluştur ve yukarıdaki URL’yi yapıştır.',+ 'cursor' => 'Cursor’da TryPost’u uzak MCP sunucusu olarak ekleyin.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Aşağıdaki yapılandırmayı VS Code\'un MCP ayarlarına yapıştırın.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Aşağıdaki yapılandırmayı Claude Code\'un MCP ayarlarına yapıştırın.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'mcpServers config okuyan her istemciyle çalışır.',+ 'other_name' => 'Diğer',+ ],+];diff --git a/lang/tr/settings.php b/lang/tr/settings.phpindex 359d60eff..f2852da05 100644--- a/lang/tr/settings.php+++ b/lang/tr/settings.php@@ -131,6 +131,7 @@ return ['brand' => 'Marka','users' => 'Üyeler','api_keys' => 'API Anahtarları',+ 'mcp' => 'MCP',],'title' => 'Çalışma alanı ayarları','logo_heading' => 'Çalışma alanı logosu',diff --git a/lang/tr/sidebar.php b/lang/tr/sidebar.phpindex 8c8ba41c1..6a175752a 100644--- a/lang/tr/sidebar.php+++ b/lang/tr/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'İmzalar','labels' => 'Etiketler','assets' => 'Varlıklar',+ 'mcp' => 'MCP','api_keys' => 'API Anahtarları',],diff --git a/lang/uk/mcp.php b/lang/uk/mcp.phpnew file mode 100644index 000000000..c88094ba6--- /dev/null+++ b/lang/uk/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => 'Підключіть ІІ-асистентів, щоб вони створювали та керували постами у вашому обліковому записі TryPost.',+ 'copy_step' => 'Скопіюйте URL сервера TryPost',+ 'open_step' => 'Відкрийте свого ІІ-асистента',+ 'copy' => 'Скопіювати URL',+ 'connect' => 'Підключити через :client',+ 'step_add' => 'Вставте назву, URL або config нижче у свій застосунок. Вхід відкриється в браузері під час першого підключення.',+ 'name_label' => 'Назва',+ 'url_label' => 'URL сервера',+ 'config_label' => 'Config',+ 'connected_title' => 'Підключені застосунки',+ 'connected_description' => 'Асистенти, у які ви увійшли. Від’єднайте ті, якими більше не користуєтесь.',+ 'connected_empty' => 'Ще нічого не підключено. Скористайтеся Claude, ChatGPT або іншим клієнтом вище.',+ 'disconnect' => 'Від’єднати',+ 'disconnect_title' => 'Від’єднати застосунок',+ 'disconnect_confirm' => 'Це вийде з TryPost у застосунку. Потрібно буде підключитися знову, щоб знову використовувати MCP.',+ 'disconnected' => 'Застосунок від’єднано.',+ 'copied' => 'Скопійовано',+ 'last_used' => 'Востаннє використано',+ 'never' => 'Ніколи',+ 'documentation_title' => 'Документація',+ 'documentation_description' => 'Гайди клієнтів, доступні tools і усунення несправностей.',+ 'view_docs' => 'Відкрити документацію',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => 'Інші застосунки',+ 'other_clients_description' => 'Cursor, VS Code, Claude Code і все, що підтримує MCP.',++ 'clients' => [+ 'claude' => 'Відкрийте Settings → Connectors, додайте власний connector і вставте URL вище.',+ 'chatgpt' => 'Відкрийте Settings → Apps & Connectors, створіть власний connector і вставте URL вище.',+ 'cursor' => 'Додайте TryPost як віддалений MCP-сервер у Cursor.',+ 'cursor_name' => 'Cursor',+ 'vscode' => 'Вставте config нижче в налаштування MCP VS Code.',+ 'vscode_name' => 'VS Code',+ 'claude_code' => 'Вставте config нижче в налаштування MCP Claude Code.',+ 'claude_code_name' => 'Claude Code',+ 'other' => 'Працює з будь-яким клієнтом, що читає config mcpServers.',+ 'other_name' => 'Інше',+ ],+];diff --git a/lang/uk/settings.php b/lang/uk/settings.phpindex c191c37da..b53ab183b 100644--- a/lang/uk/settings.php+++ b/lang/uk/settings.php@@ -129,6 +129,7 @@ return ['brand' => 'Бренд','users' => 'Учасники','api_keys' => 'API-ключі',+ 'mcp' => 'MCP',],'title' => 'Налаштування робочого простору','logo_heading' => 'Логотип робочого простору',diff --git a/lang/uk/sidebar.php b/lang/uk/sidebar.phpindex 0c0f1fc8b..8f0d567c8 100644--- a/lang/uk/sidebar.php+++ b/lang/uk/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => 'Підписи','labels' => 'Мітки','assets' => 'Медіафайли',+ 'mcp' => 'MCP','api_keys' => 'API-ключі',],diff --git a/lang/zh/mcp.php b/lang/zh/mcp.phpnew file mode 100644index 000000000..527072a8a--- /dev/null+++ b/lang/zh/mcp.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++return [+ 'title' => 'MCP',+ 'subtitle' => '连接 AI 助手,让它们用你的 TryPost 账户创建和管理帖子。',+ 'copy_step' => '复制你的 TryPost 服务器 URL',+ 'open_step' => '打开你的 AI 助手',+ 'copy' => '复制 URL',+ 'connect' => '使用 :client 连接',+ 'step_add' => '将下方的名称、URL 或配置粘贴到你的应用中。首次连接时会在浏览器中打开登录。',+ 'name_label' => '名称',+ 'url_label' => '服务器 URL',+ 'config_label' => '配置',+ 'connected_title' => '已连接的应用',+ 'connected_description' => '你已登录的助手。可以断开不再使用的连接。',+ 'connected_empty' => '还没有连接。请使用上方的 Claude、ChatGPT 或其他客户端。',+ 'disconnect' => '断开连接',+ 'disconnect_title' => '断开应用',+ 'disconnect_confirm' => '这将使应用退出 TryPost。再次使用 MCP 前需要重新连接。',+ 'disconnected' => '应用已断开连接。',+ 'copied' => '已复制',+ 'last_used' => '最近使用',+ 'never' => '从未',+ 'documentation_title' => '文档',+ 'documentation_description' => '各客户端设置指南、可用工具和问题排查。',+ 'view_docs' => '查看文档',+ 'connector_name' => 'TryPost',+ 'authorize_logged_in_as' => 'Logged in as:',++ 'other_clients_title' => '其他应用',+ 'other_clients_description' => 'Cursor、VS Code、Claude Code 以及任何支持 MCP 的应用。',++ 'clients' => [+ 'claude' => '打开 Settings → Connectors,添加自定义连接器,然后粘贴上方 URL。',+ 'chatgpt' => '打开 Settings → Apps & Connectors,创建自定义连接器,然后粘贴上方 URL。',+ 'cursor' => '在 Cursor 中将 TryPost 添加为远程 MCP 服务器。',+ 'cursor_name' => 'Cursor',+ 'vscode' => '将下方配置粘贴到 VS Code 的 MCP 设置中。',+ 'vscode_name' => 'VS Code',+ 'claude_code' => '将下方配置粘贴到 Claude Code 的 MCP 设置中。',+ 'claude_code_name' => 'Claude Code',+ 'other' => '适用于任何读取 mcpServers 配置的客户端。',+ 'other_name' => '其他',+ ],+];diff --git a/lang/zh/settings.php b/lang/zh/settings.phpindex 314d8a49e..e830106c5 100644--- a/lang/zh/settings.php+++ b/lang/zh/settings.php@@ -129,6 +129,7 @@ return ['brand' => '品牌','users' => '成员','api_keys' => 'API 密钥',+ 'mcp' => 'MCP',],'title' => '工作区设置','logo_heading' => '工作区徽标',diff --git a/lang/zh/sidebar.php b/lang/zh/sidebar.phpindex 18a0bb02d..61c22ae72 100644--- a/lang/zh/sidebar.php+++ b/lang/zh/sidebar.php@@ -47,6 +47,7 @@ return ['signatures' => '签名','labels' => '标签','assets' => '素材库',+ 'mcp' => 'MCP','api_keys' => 'API 密钥',],diff --git a/public/images/ai/chatgpt-white.svg b/public/images/ai/chatgpt-white.svgnew file mode 100644index 000000000..fb4d0ac4d--- /dev/null+++ b/public/images/ai/chatgpt-white.svg@@ -0,0 +1 @@+<svg fill="#ffffff" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>OpenAI</title><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></svg>\ No newline at end of filediff --git a/public/images/ai/claude.svg b/public/images/ai/claude.svgnew file mode 100644index 000000000..5d8d7461d--- /dev/null+++ b/public/images/ai/claude.svg@@ -0,0 +1 @@+<svg fill="none" height="2500" viewBox="0 -.01 39.5 39.53" width="2500" xmlns="http://www.w3.org/2000/svg"><path d="m7.75 26.27 7.77-4.36.13-.38-.13-.21h-.38l-1.3-.08-4.44-.12-3.85-.16-3.73-.2-.94-.2-.88-1.16.09-.58.79-.53 1.13.1 2.5.17 3.75.26 2.72.16 4.03.42h.64l.09-.26-.22-.16-.17-.16-3.88-2.63-4.2-2.78-2.2-1.6-1.19-.81-.6-.76-.26-1.66 1.08-1.19 1.45.1.37.1 1.47 1.13 3.14 2.43 4.1 3.02.6.5.24-.17.03-.12-.27-.45-2.23-4.03-2.38-4.1-1.06-1.7-.28-1.02c-.1-.42-.17-.77-.17-1.2l1.23-1.67.68-.22 1.64.22.69.6 1.02 2.33 1.65 3.67 2.56 4.99.75 1.48.4 1.37.15.42h.26v-.24l.21-2.81.39-3.45.38-4.44.13-1.25.62-1.5 1.23-.81.96.46.79 1.13-.11.73-.47 3.05-.92 4.78-.6 3.2h.35l.4-.4 1.62-2.15 2.72-3.4 1.2-1.35 1.4-1.49.9-.71h1.7l1.25 1.86-.56 1.92-1.75 2.22-1.45 1.88-2.08 2.8-1.3 2.24.12.18.31-.03 4.7-1 2.54-.46 3.03-.52 1.37.64.15.65-.54 1.33-3.24.8-3.8.76-5.66 1.34-.07.05.08.1 2.55.24 1.09.06h2.67l4.97.37 1.3.86.78 1.05-.13.8-2 1.02-2.7-.64-6.3-1.5-2.16-.54h-.3v.18l1.8 1.76 3.3 2.98 4.13 3.84.21.95-.53.75-.56-.08-3.63-2.73-1.4-1.23-3.17-2.67h-.21v.28l.73 1.07 3.86 5.8.2 1.78-.28.58-1 .35-1.1-.2-2.26-3.17-2.33-3.57-1.88-3.2-.23.13-1.11 11.95-.52.61-1.2.46-1-.76-.53-1.23.53-2.43.64-3.17.52-2.52.47-3.13.28-1.04-.02-.07-.23.03-2.36 3.24-3.59 4.85-2.84 3.04-.68.27-1.18-.61.11-1.09.66-.97 3.93-5 2.37-3.1 1.53-1.79-.01-.26h-.09l-10.44 6.78-1.86.24-.8-.75.1-1.23.38-.4 3.14-2.16z" fill="#d97757"/></svg>\ No newline at end of filediff --git a/public/images/ai/cursor.svg b/public/images/ai/cursor.svgnew file mode 100644index 000000000..a1bb0420c--- /dev/null+++ b/public/images/ai/cursor.svg@@ -0,0 +1,6 @@+<svg viewBox="0 0 466.73 532.09" xmlns="http://www.w3.org/2000/svg">+ <path+ fill="#26251e"+ d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"+ />+</svg>diff --git a/public/images/ai/other-clients.svg b/public/images/ai/other-clients.svgnew file mode 100644index 000000000..c9136d9f5--- /dev/null+++ b/public/images/ai/other-clients.svg@@ -0,0 +1,6 @@+<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path+ fill="#737373"+ d="M6.24904 5C6.24904 2.92893 7.92797 1.25 9.99904 1.25C12.0701 1.25 13.749 2.92893 13.749 5C13.749 5.08751 13.746 5.17439 13.7401 5.26052C14.4775 5.27565 15.1165 5.31322 15.6639 5.40844C16.4468 5.54462 17.1118 5.80948 17.6507 6.34835C18.1896 6.88722 18.4544 7.55227 18.5906 8.33514C18.6858 8.88251 18.7234 9.52155 18.7385 10.2589C18.8247 10.253 18.9115 10.25 18.999 10.25C21.0701 10.25 22.749 11.9289 22.749 14C22.749 16.0711 21.0701 17.75 18.999 17.75C18.9115 17.75 18.8247 17.747 18.7385 17.7411C18.7234 18.4785 18.6858 19.1175 18.5906 19.6649C18.4544 20.4477 18.1896 21.1128 17.6507 21.6517C17.1119 22.1905 16.4469 22.4553 15.6641 22.5915C14.9031 22.7239 13.9648 22.7449 12.8314 22.749C12.5875 22.7499 12.3584 22.6322 12.2172 22.4333C12.076 22.2344 12.0403 21.9793 12.1215 21.7493C12.2039 21.5159 12.249 21.264 12.249 21C12.249 19.7574 11.2417 18.75 9.99904 18.75C8.7564 18.75 7.74904 19.7574 7.74904 21C7.74904 21.264 7.79421 21.5159 7.87663 21.7493C7.95783 21.9793 7.92212 22.2344 7.7809 22.4333C7.63967 22.6322 7.41057 22.7499 7.16667 22.749C6.03327 22.7449 5.095 22.7239 4.33395 22.5915C3.55118 22.4553 2.88621 22.1905 2.34739 21.6517C1.80857 21.1128 1.54372 20.4479 1.40752 19.6651C1.2751 18.904 1.25415 17.9658 1.25001 16.8324C1.24911 16.5885 1.36688 16.3594 1.56574 16.2181C1.76459 16.0769 2.0197 16.0412 2.24969 16.1224C2.48311 16.2048 2.73499 16.25 2.99904 16.25C4.24168 16.25 5.24904 15.2426 5.24904 14C5.24904 12.7574 4.24168 11.75 2.99904 11.75C2.73499 11.75 2.48311 11.7952 2.24969 11.8776C2.0197 11.9588 1.76459 11.9231 1.56574 11.7819C1.36688 11.6406 1.24911 11.4115 1.25001 11.1676C1.25415 10.0342 1.2751 9.09595 1.40752 8.33491C1.54372 7.55214 1.80857 6.88717 2.34739 6.34835C2.88626 5.80948 3.55131 5.54462 4.33418 5.40844C4.88155 5.31322 5.52059 5.27565 6.25798 5.26052C6.25205 5.17439 6.24904 5.08751 6.24904 5Z"+ />+</svg>diff --git a/public/images/ai/vscode.svg b/public/images/ai/vscode.svgnew file mode 100644index 000000000..73df1aefb--- /dev/null+++ b/public/images/ai/vscode.svg@@ -0,0 +1,6 @@+<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">+ <path+ fill="#0098FF"+ d="M23.15 2.587L18.21.21a1.494 1.494 0 0 0-1.705.29l-9.46 8.63-4.12-3.128a.999.999 0 0 0-1.276.057L.327 7.261A1 1 0 0 0 .326 8.74L3.899 12 .326 15.26a1 1 0 0 0 .001 1.479L1.65 17.94a.999.999 0 0 0 1.276.057l4.12-3.128 9.46 8.63a1.492 1.492 0 0 0 1.704.29l4.942-2.377A1.5 1.5 0 0 0 24 20.06V3.939a1.5 1.5 0 0 0-.85-1.352zm-5.146 14.861L10.826 12l7.178-5.448v10.896z"+ />+</svg>diff --git a/resources/js/components/AppSidebar.vue b/resources/js/components/AppSidebar.vueindex 512a7e1f3..458c46a74 100644--- a/resources/js/components/AppSidebar.vue+++ b/resources/js/components/AppSidebar.vue@@ -16,6 +16,7 @@ import {IconLifebuoy,IconPencil,IconPhoto,+ IconPlugConnected,IconSelector,IconTag,} from '@tabler/icons-vue';@@ -53,6 +54,7 @@ import { index as assets } from '@/routes/app/assets';import { index as automations } from '@/routes/app/automations';import { portal } from '@/routes/app/billing';import { index as labels } from '@/routes/app/labels';+import { index as mcp } from '@/routes/app/mcp';import { index as signatures } from '@/routes/app/signatures';import type { NavItem, User } from '@/types';@@ -162,6 +164,11 @@ const workspaceNavItems = computed<NavItem[]>(() => [},]: []),+ {+ title: trans('sidebar.workspace.mcp'),+ href: mcp.url(),+ icon: IconPlugConnected,+ },]);const bottomNavItems = computed(() => [diff --git a/resources/js/components/mcp/McpAdvancedClients.vue b/resources/js/components/mcp/McpAdvancedClients.vuenew file mode 100644index 000000000..a0eb5a5fd--- /dev/null+++ b/resources/js/components/mcp/McpAdvancedClients.vue@@ -0,0 +1,230 @@+<script setup lang="ts">+import { IconChevronDown, IconCopy } from '@tabler/icons-vue';+import { trans } from 'laravel-vue-i18n';+import { computed, ref } from 'vue';++import HeadingSmall from '@/components/HeadingSmall.vue';+import { Button } from '@/components/ui/button';+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from '@/components/ui/collapsible';+import { copyToClipboard } from '@/lib/utils';++const props = defineProps<{+ mcpUrl: string;+}>();++type AdvancedMcpClientKey = 'cursor' | 'vscode' | 'claude_code' | 'other';+type McpConfigRoot = 'servers' | 'mcpServers';++interface AdvancedMcpClient {+ key: AdvancedMcpClientKey;+ name: string;+ description: string;+ logo: string;+ tileClass: string;+ httpType: boolean;+ configRoot: McpConfigRoot;+}++const advancedClients: AdvancedMcpClient[] = [+ {+ key: 'cursor',+ name: 'mcp.clients.cursor_name',+ description: 'mcp.clients.cursor',+ logo: '/images/ai/cursor.svg',+ tileClass: 'bg-white -rotate-1',+ httpType: false,+ configRoot: 'mcpServers',+ },+ {+ key: 'vscode',+ name: 'mcp.clients.vscode_name',+ description: 'mcp.clients.vscode',+ logo: '/images/ai/vscode.svg',+ tileClass: 'bg-sky-100 rotate-2',+ httpType: true,+ configRoot: 'servers',+ },+ {+ key: 'claude_code',+ name: 'mcp.clients.claude_code_name',+ description: 'mcp.clients.claude_code',+ logo: '/images/ai/claude.svg',+ tileClass: 'bg-orange-100 rotate-1',+ httpType: true,+ configRoot: 'mcpServers',+ },+ {+ key: 'other',+ name: 'mcp.clients.other_name',+ description: 'mcp.clients.other',+ logo: '/images/ai/other-clients.svg',+ tileClass: 'bg-amber-100 -rotate-2',+ httpType: false,+ configRoot: 'mcpServers',+ },+];++const openClient = ref<AdvancedMcpClientKey | ''>('');+const connectorName = computed(() => trans('mcp.connector_name'));+const copiedMessage = computed(() => trans('mcp.copied'));++const configSnippet = (client: AdvancedMcpClient): string => {+ const server = client.httpType+ ? { type: 'http', url: props.mcpUrl }+ : { url: props.mcpUrl };++ return JSON.stringify(+ { [client.configRoot]: { [connectorName.value]: server } },+ null,+ 2,+ );+};++const setClientOpen = (client: AdvancedMcpClientKey, open: boolean): void => {+ openClient.value = open ? client : '';+};++const copy = (value: string): void => {+ copyToClipboard(value, copiedMessage.value);+};+</script>++<template>+ <div class="space-y-4">+ <HeadingSmall+ :title="$t('mcp.other_clients_title')"+ :description="$t('mcp.other_clients_description')"+ />++ <div class="flex flex-col gap-4 pb-1">+ <Collapsible+ v-for="client in advancedClients"+ :key="client.key"+ :open="openClient === client.key"+ class="overflow-hidden rounded-xl border-2 border-foreground bg-card shadow-2xs"+ @update:open="(open) => setClientOpen(client.key, open)"+ >+ <CollapsibleTrigger+ class="flex w-full items-start justify-between gap-4 rounded-md px-5 py-4 text-left text-sm font-medium outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50"+ :data-testid="`mcp-advanced-client-${client.key}`"+ >+ <span class="flex items-center gap-4 text-start">+ <span+ class="inline-flex size-12 shrink-0 items-center justify-center rounded-xl border-2 border-foreground shadow-sm"+ :class="client.tileClass"+ >+ <img+ :src="client.logo"+ :alt="$t(client.name)"+ class="size-6 object-contain"+ />+ </span>+ <span class="min-w-0">+ <span class="block font-bold">+ {{ $t(client.name) }}+ </span>+ <span+ class="mt-0.5 block text-sm text-foreground/70"+ >+ {{ $t(client.description) }}+ </span>+ </span>+ </span>+ <IconChevronDown+ class="pointer-events-none size-4 shrink-0 translate-y-0.5 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none"+ :class="openClient === client.key ? 'rotate-180' : ''"+ />+ </CollapsibleTrigger>++ <CollapsibleContent+ class="overflow-hidden px-5 pt-1 pb-5 text-sm data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down motion-reduce:data-[state=closed]:animate-none motion-reduce:data-[state=open]:animate-none"+ >+ <div class="space-y-5">+ <p class="text-sm font-medium text-foreground/70">+ {{ $t('mcp.step_add') }}+ </p>++ <div class="grid gap-2">+ <p class="font-bold">+ {{ $t('mcp.name_label') }}+ </p>+ <div+ class="flex items-center gap-2 rounded-xl border-2 border-foreground bg-background p-2 shadow-2xs"+ >+ <code+ dir="ltr"+ class="min-w-0 flex-1 truncate px-2 text-left font-mono text-sm"+ >+ {{ connectorName }}+ </code>+ <Button+ type="button"+ variant="outline"+ size="icon"+ class="size-9 shrink-0"+ :aria-label="`${$t('common.actions.copy')} ${$t('mcp.name_label')}`"+ @click="copy(connectorName)"+ >+ <IconCopy class="size-4" />+ </Button>+ </div>+ </div>++ <div class="grid gap-2">+ <p class="font-bold">+ {{ $t('mcp.url_label') }}+ </p>+ <div+ class="flex items-center gap-2 rounded-xl border-2 border-foreground bg-background p-2 shadow-2xs"+ >+ <code+ dir="ltr"+ class="min-w-0 flex-1 truncate px-2 text-left font-mono text-sm"+ >+ {{ mcpUrl }}+ </code>+ <Button+ type="button"+ variant="outline"+ size="icon"+ class="size-9 shrink-0"+ :aria-label="`${$t('common.actions.copy')} ${$t('mcp.url_label')}`"+ @click="copy(mcpUrl)"+ >+ <IconCopy class="size-4" />+ </Button>+ </div>+ </div>++ <div class="grid gap-2">+ <p class="font-bold">+ {{ $t('mcp.config_label') }}+ </p>+ <div class="relative">+ <pre+ dir="ltr"+ class="overflow-x-auto rounded-xl border-2 border-foreground bg-background p-3 pe-14 text-left font-mono text-xs shadow-2xs"+ :data-testid="`mcp-config-${client.key}`"+ ><code>{{ configSnippet(client) }}</code></pre>+ <Button+ type="button"+ variant="outline"+ size="icon"+ class="absolute inset-e-2 top-2 size-9"+ :aria-label="`${$t('common.actions.copy')} ${$t('mcp.config_label')}`"+ @click="copy(configSnippet(client))"+ >+ <IconCopy class="size-4" />+ </Button>+ </div>+ </div>+ </div>+ </CollapsibleContent>+ </Collapsible>+ </div>+ </div>+</template>diff --git a/resources/js/components/mcp/McpPrimarySetup.vue b/resources/js/components/mcp/McpPrimarySetup.vuenew file mode 100644index 000000000..cf0f974e2--- /dev/null+++ b/resources/js/components/mcp/McpPrimarySetup.vue@@ -0,0 +1,119 @@+<script setup lang="ts">+import { IconCopy, IconLink } from '@tabler/icons-vue';++import { Button } from '@/components/ui/button';+import { mcpClients } from '@/lib/mcpClients';+import { copyToClipboard } from '@/lib/utils';++const props = defineProps<{+ mcpUrl: string;+ copiedMessage: string;+}>();++const copyMcpUrl = (): void => {+ copyToClipboard(props.mcpUrl, props.copiedMessage);+};+</script>++<template>+ <ol class="space-y-6">+ <li>+ <div class="mb-3 flex items-center gap-3">+ <span+ class="inline-flex size-6 shrink-0 items-center justify-center rounded-full bg-foreground text-xs font-bold text-background"+ >+ 1+ </span>+ <p class="text-sm font-bold">+ {{ $t('mcp.copy_step') }}+ </p>+ </div>+ <div+ class="flex flex-col gap-2 rounded-xl border-2 border-foreground bg-background p-2 shadow-2xs sm:flex-row sm:items-center"+ >+ <div class="flex min-w-0 flex-1 items-center gap-2 px-2">+ <IconLink class="size-4 shrink-0 text-muted-foreground" />+ <code+ dir="ltr"+ class="min-w-0 flex-1 truncate text-left text-sm"+ >+ {{ mcpUrl }}+ </code>+ </div>+ <Button+ type="button"+ variant="outline"+ size="sm"+ class="shrink-0"+ data-testid="copy-mcp-url"+ @click="copyMcpUrl"+ >+ <IconCopy class="size-4" />+ {{ $t('mcp.copy') }}+ </Button>+ </div>+ </li>++ <li>+ <div class="mb-3 flex items-center gap-3">+ <span+ class="inline-flex size-6 shrink-0 items-center justify-center rounded-full bg-foreground text-xs font-bold text-background"+ >+ 2+ </span>+ <p class="text-sm font-bold">+ {{ $t('mcp.open_step') }}+ </p>+ </div>++ <div class="grid gap-4 md:grid-cols-2">+ <article+ v-for="client in mcpClients"+ :key="client.id"+ class="flex flex-col gap-4 rounded-xl border-2 border-foreground bg-card p-4 shadow-2xs"+ >+ <div class="flex items-start gap-4">+ <span+ :class="[+ client.theme.bg,+ client.theme.rotate,+ 'inline-flex size-12 shrink-0 items-center justify-center rounded-xl border-2 border-foreground shadow-sm',+ ]"+ >+ <img+ :src="client.logo"+ :alt="client.label"+ class="size-7 object-contain"+ />+ </span>+ <div class="min-w-0 flex-1">+ <h3 class="font-bold">+ {{ client.label }}+ </h3>+ <p+ class="mt-1 text-xs leading-relaxed text-muted-foreground"+ >+ {{ $t(`mcp.clients.${client.id}`) }}+ </p>+ </div>+ </div>++ <Button as-child class="w-full">+ <a+ :href="client.settingsUrl"+ target="_blank"+ rel="noopener noreferrer"+ :data-testid="`mcp-client-${client.id}`"+ >+ {{+ $t('mcp.connect', {+ client: client.label,+ })+ }}+ </a>+ </Button>+ </article>+ </div>+ </li>+ </ol>+</template>diff --git a/resources/js/components/settings/SettingsTabsNav.vue b/resources/js/components/settings/SettingsTabsNav.vueindex 48c6c4172..3007cbe3e 100644--- a/resources/js/components/settings/SettingsTabsNav.vue+++ b/resources/js/components/settings/SettingsTabsNav.vue@@ -24,7 +24,12 @@ defineProps<{:value="tab.name"as-child>- <Link :href="tab.href">{{ tab.label }}</Link>+ <Link+ :href="tab.href"+ :data-testid="`settings-tab-${tab.name}`"+ >+ {{ tab.label }}+ </Link></TabsTrigger></TabsList></Tabs>diff --git a/resources/js/composables/useWorkspaceSettingsTabs.ts b/resources/js/composables/useWorkspaceSettingsTabs.tsnew file mode 100644index 000000000..158a0b1c0--- /dev/null+++ b/resources/js/composables/useWorkspaceSettingsTabs.ts@@ -0,0 +1,49 @@+import { trans } from 'laravel-vue-i18n';+import { computed } from 'vue';++import { useWorkspaceRole } from '@/composables/useWorkspaceRole';+import { members as membersRoute } from '@/routes/app';+import { index as apiKeysRoute } from '@/routes/app/api-keys';+import { index as mcpRoute } from '@/routes/app/mcp';+import {+ brand as brandRoute,+ settings as workspaceSettings,+} from '@/routes/app/workspace';++export const useWorkspaceSettingsTabs = () => {+ const { isAdminOrAbove } = useWorkspaceRole();++ return computed(() => {+ const tabs = [+ {+ name: 'workspace',+ label: trans('settings.workspace.tabs.workspace'),+ href: workspaceSettings.url(),+ },+ {+ name: 'brand',+ label: trans('settings.workspace.tabs.brand'),+ href: brandRoute.url(),+ },+ {+ name: 'members',+ label: trans('settings.workspace.tabs.users'),+ href: membersRoute.url(),+ },+ {+ name: 'api-keys',+ label: trans('settings.workspace.tabs.api_keys'),+ href: apiKeysRoute.url(),+ },+ {+ name: 'mcp',+ label: trans('settings.workspace.tabs.mcp'),+ href: mcpRoute.url(),+ },+ ];++ return isAdminOrAbove.value+ ? tabs+ : tabs.filter((tab) => tab.name === 'mcp');+ });+};diff --git a/resources/js/lib/mcpClients.ts b/resources/js/lib/mcpClients.tsnew file mode 100644index 000000000..f90b4ed4e--- /dev/null+++ b/resources/js/lib/mcpClients.ts@@ -0,0 +1,31 @@+export type PrimaryMcpClientId = 'claude' | 'chatgpt';++export interface McpClient {+ id: PrimaryMcpClientId;+ label: string;+ logo: string;+ settingsUrl: string;+ theme: { bg: string; rotate: string };+}++/**+ * First-class MCP clients surfaced on workspace MCP settings.+ * `settingsUrl` is the client's connector-management entry point (per the+ * official OpenAI/Anthropic docs), not a deep link into a specific form.+ */+export const mcpClients: McpClient[] = [+ {+ id: 'claude',+ label: 'Claude',+ logo: '/images/ai/claude.svg',+ settingsUrl: 'https://claude.ai/customize/connectors',+ theme: { bg: 'bg-orange-100', rotate: '-rotate-2' },+ },+ {+ id: 'chatgpt',+ label: 'ChatGPT',+ logo: '/images/ai/chatgpt-white.svg',+ settingsUrl: 'https://chatgpt.com/plugins#settings/Connectors?create-connector=true&redirectAfter=%2Fplugins',+ theme: { bg: 'bg-black', rotate: 'rotate-1' },+ },+];diff --git a/resources/js/pages/settings/workspace/ApiKeys.vue b/resources/js/pages/settings/workspace/ApiKeys.vueindex 34a53aebb..139820f6e 100644--- a/resources/js/pages/settings/workspace/ApiKeys.vue+++ b/resources/js/pages/settings/workspace/ApiKeys.vue@@ -27,12 +27,11 @@ import {TableHeader,TableRow,} from '@/components/ui/table';+import { useWorkspaceSettingsTabs } from '@/composables/useWorkspaceSettingsTabs';import date from '@/date';import AppLayout from '@/layouts/AppLayout.vue';import { copyToClipboard } from '@/lib/utils';-import { members as membersRoute } from '@/routes/app';-import { index as apiKeysRoute } from '@/routes/app/api-keys';-import { brand as brandRoute, settings as workspaceSettings } from '@/routes/app/workspace';+interface ApiToken {id: string;name: string;@@ -48,17 +47,19 @@ interface Props {defineProps<Props>();const page = usePage();-const newToken = computed(() => (page.props.flash as Record<string, unknown>)?.plainToken as string | undefined);+const newToken = computed(+ () =>+ (page.props.flash as Record<string, unknown>)?.plainToken as+ | string+ | undefined,+);const createDialogOpen = ref(false);-const confirmDeleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);--const tabs = computed(() => [- { name: 'workspace', label: trans('settings.workspace.tabs.workspace'), href: workspaceSettings.url() },- { name: 'brand', label: trans('settings.workspace.tabs.brand'), href: brandRoute.url() },- { name: 'members', label: trans('settings.workspace.tabs.users'), href: membersRoute.url() },- { name: 'api-keys', label: trans('settings.workspace.tabs.api_keys'), href: apiKeysRoute.url() },-]);+const confirmDeleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(+ null,+);++const tabs = useWorkspaceSettingsTabs();</script><template>@@ -69,11 +70,13 @@ const tabs = computed(() => [<PageHeader:title="$t('settings.hub.title')":description="$t('settings.hub.description')"- />+ /><SettingsTabsNav :tabs="tabs" active="api-keys" />- <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">+ <div+ class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"+ ><HeadingSmall:title="$t('settings.api_keys.heading')":description="$t('settings.api_keys.description')"@@ -92,13 +95,15 @@ const tabs = computed(() => [{{ $t('settings.api_keys.new_token_message') }}</p><div class="flex items-stretch gap-2">- <code class="flex h-9 min-w-0 flex-1 items-center rounded-md border-2 border-foreground bg-card px-3 font-mono text-sm font-bold text-foreground shadow-2xs">+ <code+ class="flex h-9 min-w-0 flex-1 items-center rounded-md border-2 border-foreground bg-card px-3 font-mono text-sm font-bold text-foreground shadow-2xs"+ ><span class="block truncate">{{ newToken }}</span></code><Buttonvariant="outline"class="shrink-0"- @click="copyToClipboard(newToken!, trans('settings.api_keys.copy_success'))"+ @click="copyToClipboard(newToken!)"><IconCopy class="size-4" />{{ $t('settings.api_keys.copy') }}@@ -110,9 +115,15 @@ const tabs = computed(() => [<Table><TableHeader><TableRow>- <TableHead>{{ $t('settings.api_keys.table.name') }}</TableHead>- <TableHead>{{ $t('settings.api_keys.table.expires') }}</TableHead>- <TableHead>{{ $t('settings.api_keys.table.last_used') }}</TableHead>+ <TableHead>{{+ $t('settings.api_keys.table.name')+ }}</TableHead>+ <TableHead>{{+ $t('settings.api_keys.table.expires')+ }}</TableHead>+ <TableHead>{{+ $t('settings.api_keys.table.last_used')+ }}</TableHead><TableHead class="w-10" /></TableRow></TableHeader>@@ -120,32 +131,66 @@ const tabs = computed(() => [<TableRow v-for="token in apiTokens" :key="token.id"><TableCell>{{ token.name }}</TableCell><TableCell>- {{ token.expires_at ? date.formatDateOnly(token.expires_at) : $t('settings.api_keys.table.never') }}+ {{+ token.expires_at+ ? date.formatDate(token.expires_at)+ : $t('settings.api_keys.table.never')+ }}</TableCell><TableCell>- {{ token.last_used_at ? date.diffForHumans(token.last_used_at) : $t('settings.api_keys.table.never') }}+ {{+ token.last_used_at+ ? date.diffForHumans(token.last_used_at)+ : $t('settings.api_keys.table.never')+ }}</TableCell><TableCell><DropdownMenu><DropdownMenuTrigger as-child>- <Button variant="outline" size="icon" class="size-9">+ <Button+ variant="outline"+ size="icon"+ class="size-9"+ ><IconDots class="size-4" /></Button></DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem- @click="copyToClipboard(token.id, trans('settings.api_keys.actions.copy_id_success'))"+ @click="+ copyToClipboard(+ token.id,+ trans(+ 'settings.api_keys.actions.copy_id_success',+ ),+ )+ "><IconCopy class="size-4" />- {{ $t('settings.api_keys.actions.copy_id') }}+ {{+ $t(+ 'settings.api_keys.actions.copy_id',+ )+ }}</DropdownMenuItem><DropdownMenuSeparator /><DropdownMenuItemvariant="destructive"- @click="confirmDeleteModal?.open({ url: ApiKeyController.destroy.url(token.id), confirmText: token.name })"+ @click="+ confirmDeleteModal?.open({+ url: ApiKeyController.destroy.url(+ token.id,+ ),+ confirmText: token.name,+ })+ "><IconTrash class="size-4" />- {{ $t('settings.api_keys.actions.delete') }}+ {{+ $t(+ 'settings.api_keys.actions.delete',+ )+ }}</DropdownMenuItem></DropdownMenuContent></DropdownMenu>diff --git a/resources/js/pages/settings/workspace/Brand.vue b/resources/js/pages/settings/workspace/Brand.vueindex 9e0c5808d..12dfc0bb9 100644--- a/resources/js/pages/settings/workspace/Brand.vue+++ b/resources/js/pages/settings/workspace/Brand.vue@@ -1,15 +1,11 @@<script setup lang="ts">import { Head } from '@inertiajs/vue3';-import { trans } from 'laravel-vue-i18n';-import { computed } from 'vue';import PageHeader from '@/components/PageHeader.vue';import BrandTab from '@/components/settings/BrandTab.vue';import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';+import { useWorkspaceSettingsTabs } from '@/composables/useWorkspaceSettingsTabs';import AppLayout from '@/layouts/AppLayout.vue';-import { members as membersRoute } from '@/routes/app';-import { index as apiKeysRoute } from '@/routes/app/api-keys';-import { brand as brandRoute, settings as workspaceSettings } from '@/routes/app/workspace';import type { ContentLanguageOption } from '@/types';interface Workspace {@@ -34,12 +30,7 @@ defineProps<{availableContentLanguages: ContentLanguageOption[];}>();-const tabs = computed(() => [- { name: 'workspace', label: trans('settings.workspace.tabs.workspace'), href: workspaceSettings.url() },- { name: 'brand', label: trans('settings.workspace.tabs.brand'), href: brandRoute.url() },- { name: 'members', label: trans('settings.workspace.tabs.users'), href: membersRoute.url() },- { name: 'api-keys', label: trans('settings.workspace.tabs.api_keys'), href: apiKeysRoute.url() },-]);+const tabs = useWorkspaceSettingsTabs();</script><template>@@ -50,7 +41,7 @@ const tabs = computed(() => [<PageHeader:title="$t('settings.hub.title')":description="$t('settings.hub.description')"- />+ /><SettingsTabsNav :tabs="tabs" active="brand" />diff --git a/resources/js/pages/settings/workspace/Mcp.vue b/resources/js/pages/settings/workspace/Mcp.vuenew file mode 100644index 000000000..791cd29f0--- /dev/null+++ b/resources/js/pages/settings/workspace/Mcp.vue@@ -0,0 +1,157 @@+<script setup lang="ts">+import { Head, usePoll } from '@inertiajs/vue3';+import { IconExternalLink } from '@tabler/icons-vue';+import { ref } from 'vue';++import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';+import HeadingSmall from '@/components/HeadingSmall.vue';+import McpAdvancedClients from '@/components/mcp/McpAdvancedClients.vue';+import McpPrimarySetup from '@/components/mcp/McpPrimarySetup.vue';+import PageHeader from '@/components/PageHeader.vue';+import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';+import { Button } from '@/components/ui/button';+import { useWorkspaceSettingsTabs } from '@/composables/useWorkspaceSettingsTabs';+import date from '@/date';+import AppLayout from '@/layouts/AppLayout.vue';+import { disconnect as mcpDisconnect } from '@/routes/app/mcp';++interface ConnectedClient {+ client_id: string;+ name: string;+ can_disconnect: boolean;+ last_used_at: string | null;+}++defineProps<{+ mcpUrl: string;+ connectedClients: ConnectedClient[];+}>();++const docsUrl = 'https://docs.trypost.it/ai/introduction';+const tabs = useWorkspaceSettingsTabs();+const deleteModal = ref<InstanceType<typeof ConfirmDeleteModal> | null>(null);++usePoll(1000, {+ only: ['connectedClients'],+});++const confirmDisconnect = (client: ConnectedClient): void => {+ deleteModal.value?.open({+ url: mcpDisconnect.url({ client: client.client_id }),+ confirmText: client.name,+ });+};+</script>++<template>+ <Head :title="$t('mcp.title')" />++ <AppLayout>+ <div class="mx-auto max-w-4xl space-y-8 px-6 py-8">+ <PageHeader+ :title="$t('settings.hub.title')"+ :description="$t('settings.hub.description')"+ />++ <SettingsTabsNav :tabs="tabs" active="mcp" />++ <div class="flex max-w-3xl flex-col gap-10">+ <HeadingSmall+ :title="$t('mcp.title')"+ :description="$t('mcp.subtitle')"+ />++ <section class="space-y-6">+ <McpPrimarySetup+ :mcp-url="mcpUrl"+ :copied-message="$t('mcp.copied')"+ />+ <McpAdvancedClients :mcp-url="mcpUrl" />+ </section>++ <section class="space-y-4">+ <HeadingSmall+ :title="$t('mcp.connected_title')"+ :description="$t('mcp.connected_description')"+ />++ <div+ v-if="connectedClients.length === 0"+ class="rounded-xl border-2 border-dashed border-foreground/25 bg-card/40 px-4 py-6 text-center text-sm font-medium text-foreground/60"+ data-testid="mcp-connected-empty"+ >+ {{ $t('mcp.connected_empty') }}+ </div>++ <div v-else class="grid gap-3">+ <div+ v-for="client in connectedClients"+ :key="client.client_id"+ class="flex items-center justify-between gap-4 rounded-xl border-2 border-foreground bg-card px-4 py-3 shadow-2xs"+ :data-testid="`mcp-connected-client-${client.client_id}`"+ >+ <div class="min-w-0">+ <p+ class="flex items-center gap-2 truncate text-sm font-bold"+ >+ <span+ class="size-2 shrink-0 rounded-full bg-emerald-500"+ aria-hidden="true"+ />+ <span class="truncate">{{+ client.name+ }}</span>+ </p>+ <p+ class="text-xs font-medium text-foreground/60"+ >+ {{ $t('mcp.last_used') }}:+ {{+ client.last_used_at+ ? date.diffForHumans(+ client.last_used_at,+ )+ : $t('mcp.never')+ }}+ </p>+ </div>+ <Button+ v-if="client.can_disconnect"+ variant="outline"+ size="sm"+ @click="confirmDisconnect(client)"+ >+ {{ $t('mcp.disconnect') }}+ </Button>+ </div>+ </div>+ </section>++ <section class="space-y-4">+ <HeadingSmall+ :title="$t('mcp.documentation_title')"+ :description="$t('mcp.documentation_description')"+ />+ <Button+ as="a"+ variant="outline"+ size="sm"+ target="_blank"+ :href="docsUrl"+ >+ <IconExternalLink class="size-4" />+ {{ $t('mcp.view_docs') }}+ </Button>+ </section>+ </div>+ </div>++ <ConfirmDeleteModal+ ref="deleteModal"+ method="delete"+ :title="$t('mcp.disconnect_title')"+ :description="$t('mcp.disconnect_confirm')"+ :action="$t('mcp.disconnect')"+ />+ </AppLayout>+</template>diff --git a/resources/js/pages/settings/workspace/Members.vue b/resources/js/pages/settings/workspace/Members.vueindex 0153aeb22..062d83fec 100644--- a/resources/js/pages/settings/workspace/Members.vue+++ b/resources/js/pages/settings/workspace/Members.vue@@ -1,15 +1,11 @@<script setup lang="ts">import { Head } from '@inertiajs/vue3';-import { trans } from 'laravel-vue-i18n';-import { computed } from 'vue';import PageHeader from '@/components/PageHeader.vue';import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';import UsersTab from '@/components/settings/UsersTab.vue';+import { useWorkspaceSettingsTabs } from '@/composables/useWorkspaceSettingsTabs';import AppLayout from '@/layouts/AppLayout.vue';-import { members as membersRoute } from '@/routes/app';-import { index as apiKeysRoute } from '@/routes/app/api-keys';-import { brand as brandRoute, settings as workspaceSettings } from '@/routes/app/workspace';interface Workspace {id: string;@@ -42,12 +38,7 @@ defineProps<{roles: Role[];}>();-const tabs = computed(() => [- { name: 'workspace', label: trans('settings.workspace.tabs.workspace'), href: workspaceSettings.url() },- { name: 'brand', label: trans('settings.workspace.tabs.brand'), href: brandRoute.url() },- { name: 'members', label: trans('settings.workspace.tabs.users'), href: membersRoute.url() },- { name: 'api-keys', label: trans('settings.workspace.tabs.api_keys'), href: apiKeysRoute.url() },-]);+const tabs = useWorkspaceSettingsTabs();</script><template>@@ -58,11 +49,15 @@ const tabs = computed(() => [<PageHeader:title="$t('settings.hub.title')":description="$t('settings.hub.description')"- />+ /><SettingsTabsNav :tabs="tabs" active="members" />- <UsersTab :members="members" :invitations="invites" :roles="roles" />+ <UsersTab+ :members="members"+ :invitations="invites"+ :roles="roles"+ /></div></AppLayout></template>diff --git a/resources/js/pages/settings/workspace/Workspace.vue b/resources/js/pages/settings/workspace/Workspace.vueindex 56db8152d..e0ffb9c1c 100644--- a/resources/js/pages/settings/workspace/Workspace.vue+++ b/resources/js/pages/settings/workspace/Workspace.vue@@ -1,15 +1,11 @@<script setup lang="ts">import { Head } from '@inertiajs/vue3';-import { trans } from 'laravel-vue-i18n';-import { computed } from 'vue';import PageHeader from '@/components/PageHeader.vue';import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';import WorkspaceTab from '@/components/settings/WorkspaceTab.vue';+import { useWorkspaceSettingsTabs } from '@/composables/useWorkspaceSettingsTabs';import AppLayout from '@/layouts/AppLayout.vue';-import { members as membersRoute } from '@/routes/app';-import { index as apiKeysRoute } from '@/routes/app/api-keys';-import { brand as brandRoute, settings as workspaceSettings } from '@/routes/app/workspace';interface Workspace {id: string;@@ -28,12 +24,7 @@ defineProps<{otherMemberCount: number;}>();-const tabs = computed(() => [- { name: 'workspace', label: trans('settings.workspace.tabs.workspace'), href: workspaceSettings.url() },- { name: 'brand', label: trans('settings.workspace.tabs.brand'), href: brandRoute.url() },- { name: 'members', label: trans('settings.workspace.tabs.users'), href: membersRoute.url() },- { name: 'api-keys', label: trans('settings.workspace.tabs.api_keys'), href: apiKeysRoute.url() },-]);+const tabs = useWorkspaceSettingsTabs();</script><template>@@ -44,7 +35,7 @@ const tabs = computed(() => [<PageHeader:title="$t('settings.hub.title')":description="$t('settings.hub.description')"- />+ /><SettingsTabsNav :tabs="tabs" active="workspace" />diff --git a/routes/ai.php b/routes/ai.phpindex 074de8a67..f615815e4 100644--- a/routes/ai.php+++ b/routes/ai.php@@ -3,9 +3,13 @@declare(strict_types=1);use App\Mcp\Servers\TryPostServer;+use Illuminate\Support\Facades\Route;use Laravel\Mcp\Facades\Mcp;-Mcp::oauthRoutes();+Route::middleware('throttle:mcp-oauth-registration')->group(function () {+ Mcp::oauthRoutes();+});Mcp::web('/mcp/trypost', TryPostServer::class)- ->middleware(['auth:api', 'workspace.token']);+ ->middleware(['auth:api', 'workspace.token:mcp'])+ ->name('mcp.trypost');diff --git a/routes/app.php b/routes/app.phpindex 75969ac03..ebe000594 100644--- a/routes/app.php+++ b/routes/app.php@@ -10,6 +10,7 @@ use App\Http\Controllers\App\BillingController;use App\Http\Controllers\App\DiscordController as AppDiscordController;use App\Http\Controllers\App\GiphyController;use App\Http\Controllers\App\LinkPreviewController;+use App\Http\Controllers\App\McpSettingsController;use App\Http\Controllers\App\NotificationController;use App\Http\Controllers\App\OnboardingController;use App\Http\Controllers\App\PostAiCreateController;@@ -265,6 +266,10 @@ Route::middleware(['auth', EnsureAccountReady::class, EnsureHasWorkspace::class]Route::post('settings/workspace/api-keys', [ApiKeyController::class, 'store'])->name('app.api-keys.store');Route::delete('settings/workspace/api-keys/{tokenId}', [ApiKeyController::class, 'destroy'])->name('app.api-keys.destroy');+ // MCP+ Route::get('settings/workspace/mcp', [McpSettingsController::class, 'index'])->name('app.mcp.index');+ Route::delete('settings/workspace/mcp/{client}', [McpSettingsController::class, 'disconnect'])->name('app.mcp.disconnect');+// Account SettingsRoute::get('settings/account', [AccountController::class, 'edit'])->name('app.account.edit');Route::put('settings/account', [AccountController::class, 'update'])->name('app.account.update');diff --git a/tests/Feature/Actions/Invite/RemoveMemberTest.php b/tests/Feature/Actions/Invite/RemoveMemberTest.phpindex 21852ddf5..5bf43c1b2 100644--- a/tests/Feature/Actions/Invite/RemoveMemberTest.php+++ b/tests/Feature/Actions/Invite/RemoveMemberTest.php@@ -3,7 +3,10 @@declare(strict_types=1);use App\Actions\Invite\RemoveMember;+use App\Enums\UserWorkspace\Role;+use App\Models\AccessToken;use App\Models\User;+use App\Models\Workspace;test('remove member clears current workspace when it was the removed membership', function () {[@@ -14,6 +17,9 @@ test('remove member clears current workspace when it was the removed membership'sharedWorkspaces: 2,setMemberCurrent: true,);+ $result = $member->createToken('Removed Workspace');+ $token = AccessToken::query()->findOrFail($result->token->id);+ $token->forceFill(['workspace_id' => $workspace->id])->saveQuietly();RemoveMember::execute($workspace, $member->id);@@ -22,6 +28,7 @@ test('remove member clears current workspace when it was the removed membership'expect($workspace->members()->where('user_id', $member->id)->exists())->toBeFalse();expect($member->current_workspace_id)->toBe($other->id);expect($member->account_id)->toBe($owner->account_id);+ expect($token->fresh()->revoked)->toBeTrue();});test('remove member deletes a user who loses their last account workspace', function () {@@ -56,3 +63,69 @@ test('remove member prefers another workspace on the same account', function ()expect($member->account_id)->toBe($owner->account_id);expect($member->current_workspace_id)->toBe($sharedB->id);});++test('remove member keeps mcp oauth when create-post access remains elsewhere', function () {+ [+ 'member' => $member,+ 'shared_workspaces' => [$sharedA, $sharedB],+ ] = strandedMemberOnSharedAccount(+ sharedWorkspaces: 2,+ setMemberCurrent: true,+ );+ $oauth = mcpAccessToken($member, mcpOauthClient());++ RemoveMember::execute($sharedA, $member->id);++ expect($oauth->fresh()->revoked)->toBeFalse()+ ->and($member->fresh()->can('createPost', $sharedB))->toBeTrue();+});++test('remove member keeps mcp oauth when the member remains a viewer elsewhere', function () {+ [+ 'member' => $member,+ 'shared_workspaces' => [$sharedA, $sharedB],+ ] = strandedMemberOnSharedAccount(+ sharedWorkspaces: 2,+ setMemberCurrent: true,+ );+ $sharedB->members()->updateExistingPivot($member->id, [+ 'role' => Role::Viewer->value,+ ]);+ $oauth = mcpAccessToken($member, mcpOauthClient());++ RemoveMember::execute($sharedA, $member->id);++ expect($oauth->fresh()->revoked)->toBeFalse()+ ->and($member->fresh()->can('createPost', $sharedB))->toBeFalse()+ ->and($member->fresh()->can('view', $sharedB))->toBeTrue();+});++test('remove member revokes api keys without touching mcp oauth grants on the same workspace id', function () {+ [+ 'member' => $member,+ 'shared_workspaces' => [$workspace],+ ] = strandedMemberOnSharedAccount(+ sharedWorkspaces: 1,+ setMemberCurrent: true,+ );++ $pat = $member->createToken('API Key');+ $patToken = AccessToken::query()->findOrFail($pat->token->id);+ $patToken->forceFill(['workspace_id' => $workspace->id])->saveQuietly();++ // Mis-bound workspace_id must still not classify this as a PAT revoke target.+ $oauth = mcpAccessToken($member, mcpOauthClient());+ $oauth->forceFill(['workspace_id' => $workspace->id])->saveQuietly();++ // Keep the member alive (second workspace) so we only exercise API-key revoke.+ $other = Workspace::factory()->create([+ 'account_id' => $member->account_id,+ 'user_id' => $member->account->owner_id,+ ]);+ $other->members()->attach($member->id, ['role' => Role::Member->value]);++ RemoveMember::execute($workspace, $member->id);++ expect($patToken->fresh()->revoked)->toBeTrue()+ ->and($oauth->fresh()->revoked)->toBeFalse();+});diff --git a/tests/Feature/Api/ApiKeyApiTest.php b/tests/Feature/Api/ApiKeyApiTest.phpindex b85e38c63..00a2fc3f7 100644--- a/tests/Feature/Api/ApiKeyApiTest.php+++ b/tests/Feature/Api/ApiKeyApiTest.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Enums\UserWorkspace\Role;use App\Models\AccessToken;use App\Models\User;use App\Models\Workspace;@@ -14,12 +15,12 @@ function createApiKeyApiToken(array $overrides = []): arraytest('list api keys', function () {$result = createApiKeyApiToken();- // Create two more tokens for the same user/workspace.- AccessToken::factory()->count(2)->state([- 'user_id' => $result['user']->id,- 'workspace_id' => $result['workspace']->id,- 'revoked' => false,- ])->create();+ foreach (['Second', 'Third'] as $name) {+ $token = $result['user']->createToken($name)->token;+ AccessToken::query()->findOrFail($token->id)+ ->forceFill(['workspace_id' => $result['workspace']->id])+ ->saveQuietly();+ }$response = $this->withHeaders(['Authorization' => 'Bearer '.$result['plain_token'],@@ -29,9 +30,35 @@ test('list api keys', function () {);$response->assertOk();- // 1 from auth + 2 created + ? we may also need to ensure factory has client id$response->assertJsonCount(3);-})->skip('AccessToken factory not available; covered by app-level ApiKeyControllerTest.');+});++test('list api keys excludes revoked and other-workspace tokens', function () {+ $result = createApiKeyApiToken();+ $revoked = $result['user']->createToken('Revoked')->token;+ AccessToken::query()->findOrFail($revoked->id)+ ->forceFill([+ 'workspace_id' => $result['workspace']->id,+ 'revoked' => true,+ ])+ ->saveQuietly();++ $otherWorkspace = Workspace::factory()->create([+ 'account_id' => $result['user']->account_id,+ 'user_id' => $result['user']->id,+ ]);+ $other = $result['user']->createToken('Other workspace')->token;+ AccessToken::query()->findOrFail($other->id)+ ->forceFill(['workspace_id' => $otherWorkspace->id])+ ->saveQuietly();++ $this->withHeaders(['Authorization' => 'Bearer '.$result['plain_token']])+ ->getJson(route('api.api-keys.index'))+ ->assertOk()+ ->assertJsonCount(1)+ ->assertJsonMissing(['id' => $revoked->id])+ ->assertJsonMissing(['id' => $other->id]);+});test('create api key returns plain token', function () {$result = createApiKeyApiToken();@@ -53,6 +80,22 @@ test('create api key returns plain token', function () {expect($response->json('plain_token'))->toBeString();});+test('workspace members cannot manage api keys through the api', function () {+ $result = createApiKeyApiToken();+ $member = User::factory()->create(['account_id' => $result['user']->account_id]);+ $result['workspace']->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $result['workspace']->id]);+ $plainToken = passportToken($member, $result['workspace']);++ $this->withHeaders(['Authorization' => "Bearer {$plainToken}"])+ ->getJson(route('api.api-keys.index'))+ ->assertForbidden();++ $this->withHeaders(['Authorization' => "Bearer {$plainToken}"])+ ->postJson(route('api.api-keys.store'), ['name' => 'Escalation Key'])+ ->assertForbidden();+});+test('create api key validation errors', function () {$result = createApiKeyApiToken();@@ -123,6 +166,53 @@ it('validates api key expires_at must be future date', function () {->assertJsonValidationErrors(['expires_at']);});+it('creates an api key without expiration', function () {+ $result = createApiKeyApiToken();++ $response = $this->withHeaders(['Authorization' => 'Bearer '.$result['plain_token']])+ ->postJson(route('api.api-keys.store'), [+ 'name' => 'Never Expires',+ ])+ ->assertCreated();++ expect($response->json('token.expires_at'))->toBeNull()+ ->and(AccessToken::query()->findOrFail($response->json('token.id'))->expires_at)->toBeNull();+});++it('creates an api key with expiration at end of day', function () {+ $result = createApiKeyApiToken();+ $expiresAt = now()->addDays(14)->startOfDay();++ $response = $this->withHeaders(['Authorization' => 'Bearer '.$result['plain_token']])+ ->postJson(route('api.api-keys.store'), [+ 'name' => 'Expiring Key',+ 'expires_at' => $expiresAt->toDateString(),+ ])+ ->assertCreated();++ $token = AccessToken::query()->findOrFail($response->json('token.id'));++ expect($token->expires_at->toDateString())->toBe($expiresAt->toDateString())+ ->and($token->expires_at->format('H:i:s'))->toBe('23:59:59');+});++it('allows an api key expiration of today', function () {+ $result = createApiKeyApiToken();+ $today = now()->toDateString();++ $response = $this->withHeaders(['Authorization' => 'Bearer '.$result['plain_token']])+ ->postJson(route('api.api-keys.store'), [+ 'name' => 'Expires Today',+ 'expires_at' => $today,+ ])+ ->assertCreated();++ $token = AccessToken::query()->findOrFail($response->json('token.id'));++ expect($token->expires_at->toDateString())->toBe($today)+ ->and($token->expires_at->format('H:i:s'))->toBe('23:59:59');+});+it('validates api key name max length', function () {$result = createApiKeyApiToken();diff --git a/tests/Feature/Api/LoadWorkspaceFromTokenTest.php b/tests/Feature/Api/LoadWorkspaceFromTokenTest.phpnew file mode 100644index 000000000..ff5cab307--- /dev/null+++ b/tests/Feature/Api/LoadWorkspaceFromTokenTest.php@@ -0,0 +1,445 @@+<?php++declare(strict_types=1);++use App\Enums\UserWorkspace\Role;+use App\Models\AccessToken;+use App\Models\Account;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\DB;+use Symfony\Component\HttpFoundation\Response;++beforeEach(function () {+ config([+ 'trypost.self_hosted' => false,+ 'trypost.billing.require_card_for_trial' => true,+ ]);++ $result = createApiTestToken();+ $this->user = $result['user'];+ $this->workspace = $result['workspace'];+ $this->plainToken = $result['plain_token'];+});++test('rejects api requests when the account has no app access', function () {+ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.workspace.show'))+ ->assertStatus(Response::HTTP_PAYMENT_REQUIRED)+ ->assertJson(['message' => 'Active subscription required.']);+});++test('allows api requests for subscribed accounts', function () {+ subscribeAccount($this->user->account);++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.workspace.show'))+ ->assertOk();+});++test('rejects a personal access token after its stored expiration', function () {+ subscribeAccount($this->user->account);++ AccessToken::query()+ ->where('user_id', $this->user->id)+ ->where('workspace_id', $this->workspace->id)+ ->firstOrFail()+ ->forceFill(['expires_at' => now()->subMinute()])+ ->saveQuietly();++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.workspace.show'))+ ->assertUnauthorized()+ ->assertJson(['message' => 'Token expired.']);+});++test('allows api requests for generic-trial accounts with app access', function () {+ config(['trypost.billing.require_card_for_trial' => false]);++ $this->user->account->update([+ 'trial_ends_at' => now()->addDays(8),+ ]);++ expect($this->user->account->fresh()->hasAppAccess())->toBeTrue()+ ->and($this->user->account->fresh()->subscribed(Account::SUBSCRIPTION_NAME))->toBeFalse();++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.workspace.show'))+ ->assertOk();+});++test('allows personal access tokens without a subscription in self-hosted mode', function () {+ config(['trypost.self_hosted' => true]);++ expect($this->user->account->subscribed(Account::SUBSCRIPTION_NAME))->toBeFalse();++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.workspace.show'))+ ->assertOk();+});++test('allows scoped mcp oauth without a subscription in self-hosted mode', function () {+ config(['trypost.self_hosted' => true]);++ $result = $this->user->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ])->assertSuccessful();+});++test('rejects a personal token after its owner is demoted from admin', function () {+ subscribeAccount($this->user->account);++ $admin = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($admin->id, ['role' => Role::Admin->value]);+ $admin->update(['current_workspace_id' => $this->workspace->id]);+ $plainToken = passportToken($admin, $this->workspace);++ $this->workspace->members()->updateExistingPivot($admin->id, [+ 'role' => Role::Viewer->value,+ ]);++ $this->withHeaders(['Authorization' => "Bearer {$plainToken}"])+ ->getJson(route('api.workspace.show'))+ ->assertForbidden()+ ->assertJson(['message' => 'Insufficient workspace permissions.']);+});++test('rejects a personal token after its owner is removed from the workspace', function () {+ subscribeAccount($this->user->account);++ $admin = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($admin->id, ['role' => Role::Admin->value]);+ $admin->update(['current_workspace_id' => $this->workspace->id]);+ $plainToken = passportToken($admin, $this->workspace);++ $this->workspace->members()->detach($admin->id);++ $this->withHeaders(['Authorization' => "Bearer {$plainToken}"])+ ->getJson(route('api.workspace.show'))+ ->assertForbidden()+ ->assertJson(['message' => 'Workspace access denied.']);+});++test('rejects mcp oauth grants on api routes for workspace viewers', function () {+ subscribeAccount($this->user->account);++ $viewer = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $this->workspace->id]);+ $result = $viewer->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->withHeaders(['Authorization' => "Bearer {$result->accessToken}"])+ ->getJson(route('api.workspace.show'))+ ->assertForbidden()+ ->assertJson(['message' => 'Personal access token required.']);+});++test('rejects scoped mcp oauth grants on api routes', function () {+ subscribeAccount($this->user->account);++ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $result = $member->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->withHeaders(['Authorization' => "Bearer {$result->accessToken}"])+ ->getJson(route('api.workspace.show'))+ ->assertForbidden()+ ->assertJson(['message' => 'Personal access token required.']);+});++test('rejects unscoped mcp oauth grants on api routes', function () {+ subscribeAccount($this->user->account);++ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $result = $member->createToken('MCP');+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->withHeaders(['Authorization' => "Bearer {$result->accessToken}"])+ ->getJson(route('api.workspace.show'))+ ->assertForbidden()+ ->assertJson(['message' => 'Personal access token required.']);+});++test('rejects personal access tokens on the mcp endpoint', function () {+ subscribeAccount($this->user->account);++ $this->withHeaders([+ 'Authorization' => 'Bearer '.$this->plainToken,+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ])+ ->assertForbidden()+ ->assertJson(['message' => 'MCP OAuth authorization required.']);+});++test('rejects oauth grants without the mcp scope on the mcp endpoint', function () {+ subscribeAccount($this->user->account);++ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);++ $result = $member->createToken('MCP');+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ])->assertForbidden();+});++test('allows scoped oauth grants for workspace members on the mcp endpoint', function () {+ subscribeAccount($this->user->account);++ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);++ $result = $member->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ])->assertSuccessful();+});++test('allows scoped oauth grants for workspace viewers on the mcp endpoint', function () {+ subscribeAccount($this->user->account);++ $viewer = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $this->workspace->id]);++ $result = $viewer->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ])->assertSuccessful();+});++test('rejects a revoked personal access token on api routes', function () {+ subscribeAccount($this->user->account);++ AccessToken::query()+ ->where('user_id', $this->user->id)+ ->where('workspace_id', $this->workspace->id)+ ->firstOrFail()+ ->forceFill(['revoked' => true])+ ->saveQuietly();++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.workspace.show'))+ ->assertUnauthorized();+});++test('does not treat oauth tokens with a revoked client as personal access tokens', function () {+ $result = $this->user->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update([+ 'grant_types' => json_encode(['authorization_code']),+ 'revoked' => true,+ ]);++ $token = $token->fresh();++ expect($token->isPersonalAccessToken())->toBeFalse()+ ->and($token->isActiveMcpGrant())->toBeFalse();+});++test('rejects api requests without a bearer token', function () {+ $this->getJson(route('api.workspace.show'))+ ->assertUnauthorized();+});++test('rejects mcp oauth when no current workspace is selected', function () {+ subscribeAccount($this->user->account);++ $result = $this->user->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $this->user->update(['current_workspace_id' => null]);++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ])+ ->assertUnauthorized()+ ->assertJson(['message' => 'No workspace selected.']);+});++test('allows mcp oauth that follows the users current workspace', function () {+ subscribeAccount($this->user->account);++ $otherWorkspace = Workspace::factory()->create([+ 'account_id' => $this->user->account_id,+ 'user_id' => $this->user->id,+ ]);+ $otherWorkspace->members()->attach($this->user->id, ['role' => Role::Member->value]);++ $result = $this->user->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $payload = [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ];++ $this->user->update(['current_workspace_id' => $otherWorkspace->id]);++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), $payload)->assertSuccessful();++ $this->user->update(['current_workspace_id' => $this->workspace->id]);++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), $payload)->assertSuccessful();+});++test('records last_used_at on the access token after a successful api request', function () {+ subscribeAccount($this->user->account);++ $token = AccessToken::query()+ ->where('user_id', $this->user->id)+ ->where('workspace_id', $this->workspace->id)+ ->firstOrFail();++ expect($token->last_used_at)->toBeNull();++ $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])+ ->getJson(route('api.workspace.show'))+ ->assertOk();++ expect($token->fresh()->last_used_at)->not->toBeNull();+});++test('rejects an expired mcp oauth grant on the mcp endpoint', function () {+ subscribeAccount($this->user->account);++ $result = $this->user->createToken('MCP', ['mcp:use']);+ $token = AccessToken::query()->findOrFail($result->token->id);+ DB::table('oauth_clients')+ ->where('id', $token->client_id)+ ->update(['grant_types' => json_encode(['authorization_code'])]);++ $token->forceFill(['expires_at' => now()->subMinute()])->saveQuietly();++ $this->withHeaders([+ 'Authorization' => "Bearer {$result->accessToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'initialize',+ 'params' => [+ 'protocolVersion' => '2025-03-26',+ 'capabilities' => (object) [],+ 'clientInfo' => ['name' => 'Pest', 'version' => '1.0'],+ ],+ ])+ ->assertUnauthorized()+ ->assertJson(['message' => 'Token expired.']);+});diff --git a/tests/Feature/ApiKeyControllerTest.php b/tests/Feature/ApiKeyControllerTest.phpindex 6d92287f9..a93265a72 100644--- a/tests/Feature/ApiKeyControllerTest.php+++ b/tests/Feature/ApiKeyControllerTest.php@@ -6,6 +6,9 @@ use App\Enums\UserWorkspace\Role;use App\Models\AccessToken;use App\Models\User;use App\Models\Workspace;+use Database\Seeders\PassportSeeder;+use Illuminate\Support\Facades\DB;+use Laravel\Passport\ClientRepository;beforeEach(function () {$this->user = User::factory()->create();@@ -51,15 +54,34 @@ it('creates an api key', function () {expect($tokens)->toHaveCount(1);expect($tokens->first()->name)->toBe('My API Key');expect($tokens->first()->revoked)->toBeFalse();+ expect($tokens->first()->expires_at)->toBeNull();+});++it('bootstraps the personal access client idempotently', function () {+ DB::table('oauth_clients')+ ->whereJsonContains('grant_types', 'personal_access')+ ->delete();++ $seeder = app(PassportSeeder::class);+ $clients = app(ClientRepository::class);++ $seeder->run($clients);+ $seeder->run($clients);++ expect(DB::table('oauth_clients')+ ->whereJsonContains('grant_types', 'personal_access')+ ->count())->toBe(1);++ expect($this->user->createToken('Self-hosted API Key')->accessToken)->toBeString();});it('creates an api key with expiration', function () {- $expiresOn = now()->addDays(30)->format('Y-m-d');+ $expiresAt = now()->addDays(30)->startOfDay();$this->actingAs($this->user)->post(route('app.api-keys.store'), ['name' => 'Expiring Key',- 'expires_at' => $expiresOn,+ 'expires_at' => $expiresAt->format('Y-m-d'),])->assertRedirect();@@ -68,34 +90,42 @@ it('creates an api key with expiration', function () {->first();expect($token->expires_at)->not->toBeNull()- ->and($token->expires_at->toDateString())->toBe($expiresOn);+ ->and($token->expires_at->toDateString())->toBe($expiresAt->toDateString())+ ->and($token->expires_at->format('H:i:s'))->toBe('23:59:59');});-it('passes the chosen expiry calendar day to the api keys page', function () {- $expiresOn = '2026-10-31';-- $result = $this->user->createToken('Expiring Key');- $token = AccessToken::find($result->token->id);- $token->forceFill([- 'workspace_id' => $this->workspace->id,- 'expires_at' => $expiresOn,- ])->saveQuietly();+it('validates name is required', function () {+ $this->actingAs($this->user)+ ->post(route('app.api-keys.store'), [])+ ->assertSessionHasErrors('name');+});+it('rejects an expiration in the past', function () {$this->actingAs($this->user)- ->get(route('app.api-keys.index'))- ->assertOk()- ->assertInertia(fn ($page) => $page- ->component('settings/workspace/ApiKeys')- ->has('apiTokens', 1)- ->where('apiTokens.0.name', 'Expiring Key')- ->where('apiTokens.0.expires_at', fn ($value) => is_string($value) && str_starts_with($value, $expiresOn))- );+ ->post(route('app.api-keys.store'), [+ 'name' => 'Past Key',+ 'expires_at' => now()->subDay()->toDateString(),+ ])+ ->assertSessionHasErrors('expires_at');});-it('validates name is required', function () {+it('allows an expiration of today', function () {+ $today = now()->toDateString();+$this->actingAs($this->user)- ->post(route('app.api-keys.store'), [])- ->assertSessionHasErrors('name');+ ->post(route('app.api-keys.store'), [+ 'name' => 'Expires Today',+ 'expires_at' => $today,+ ])+ ->assertRedirect();++ $token = AccessToken::where('user_id', $this->user->id)+ ->where('workspace_id', $this->workspace->id)+ ->where('name', 'Expires Today')+ ->firstOrFail();++ expect($token->expires_at->toDateString())->toBe($today)+ ->and($token->expires_at->format('H:i:s'))->toBe('23:59:59');});it('revokes an api key', function () {@@ -122,7 +152,7 @@ it('cannot delete api key from another workspace', function () {});it('member cannot create api key', function () {- $member = User::factory()->create();+ $member = User::factory()->create(['account_id' => $this->user->account_id]);$this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);$member->update(['current_workspace_id' => $this->workspace->id]);@@ -132,7 +162,7 @@ it('member cannot create api key', function () {});it('member cannot delete api key', function () {- $member = User::factory()->create();+ $member = User::factory()->create(['account_id' => $this->user->account_id]);$this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);$member->update(['current_workspace_id' => $this->workspace->id]);diff --git a/tests/Feature/Mcp/ApiKeyToolTest.php b/tests/Feature/Mcp/ApiKeyToolTest.phpindex e61bd9404..e646f0d65 100644--- a/tests/Feature/Mcp/ApiKeyToolTest.php+++ b/tests/Feature/Mcp/ApiKeyToolTest.php@@ -87,6 +87,28 @@ test('create api key returns plain token only at creation', function () {->count())->toBe(1);});+test('workspace members cannot manage api keys through mcp', function () {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $token = attachToken($member, $this->workspace);++ TryPostServer::actingAs($member)+ ->tool(ListApiKeysTool::class, [])+ ->assertHasErrors();++ TryPostServer::actingAs($member)+ ->tool(CreateApiKeyTool::class, ['name' => 'Escalation Key'])+ ->assertHasErrors();++ TryPostServer::actingAs($member)+ ->tool(DeleteApiKeyTool::class, ['api_key_id' => $token->id])+ ->assertHasErrors();++ expect($token->fresh()->revoked)->toBeFalse()+ ->and(AccessToken::where('user_id', $member->id)->count())->toBe(1);+});+test('create api key validates name required', function () {$response = TryPostServer::actingAs($this->user)->tool(CreateApiKeyTool::class, []);@@ -104,6 +126,69 @@ test('create api key rejects expires_at in the past', function () {$response->assertHasErrors();});+test('create api key omits expiration when not provided', function () {+ $response = TryPostServer::actingAs($this->user)+ ->tool(CreateApiKeyTool::class, [+ 'name' => 'Never Expires',+ ]);++ $response->assertOk()+ ->assertStructuredContent(function (AssertableJson $json) {+ $json->where('name', 'Never Expires')+ ->where('expires_at', null)+ ->etc();+ });++ expect(AccessToken::query()+ ->where('user_id', $this->user->id)+ ->where('workspace_id', $this->workspace->id)+ ->where('name', 'Never Expires')+ ->firstOrFail()+ ->expires_at)->toBeNull();+});++test('create api key stores expiration at end of day', function () {+ $expiresAt = now()->addDays(14)->startOfDay();++ $response = TryPostServer::actingAs($this->user)+ ->tool(CreateApiKeyTool::class, [+ 'name' => 'Expiring Key',+ 'expires_at' => $expiresAt->toDateString(),+ ]);++ $response->assertOk();++ $token = AccessToken::query()+ ->where('user_id', $this->user->id)+ ->where('workspace_id', $this->workspace->id)+ ->where('name', 'Expiring Key')+ ->firstOrFail();++ expect($token->expires_at->toDateString())->toBe($expiresAt->toDateString())+ ->and($token->expires_at->format('H:i:s'))->toBe('23:59:59');+});++test('create api key allows an expiration of today', function () {+ $today = now()->toDateString();++ $response = TryPostServer::actingAs($this->user)+ ->tool(CreateApiKeyTool::class, [+ 'name' => 'Expires Today',+ 'expires_at' => $today,+ ]);++ $response->assertOk();++ $token = AccessToken::query()+ ->where('user_id', $this->user->id)+ ->where('workspace_id', $this->workspace->id)+ ->where('name', 'Expires Today')+ ->firstOrFail();++ expect($token->expires_at->toDateString())->toBe($today)+ ->and($token->expires_at->format('H:i:s'))->toBe('23:59:59');+});+test('delete api key marks revoked', function () {$token = attachToken($this->user, $this->workspace);diff --git a/tests/Feature/Mcp/McpRoleAuthorizationTest.php b/tests/Feature/Mcp/McpRoleAuthorizationTest.phpnew file mode 100644index 000000000..beb03faac--- /dev/null+++ b/tests/Feature/Mcp/McpRoleAuthorizationTest.php@@ -0,0 +1,204 @@+<?php++declare(strict_types=1);++use App\Enums\SocialAccount\Platform;+use App\Enums\UserWorkspace\Role;+use App\Mcp\Servers\TryPostServer;+use App\Mcp\Tools\Label\CreateLabelTool;+use App\Mcp\Tools\Label\DeleteLabelTool;+use App\Mcp\Tools\Label\ListLabelsTool;+use App\Mcp\Tools\Label\UpdateLabelTool;+use App\Mcp\Tools\Post\AttachMediaFromUploadTool;+use App\Mcp\Tools\Post\AttachMediaFromUrlTool;+use App\Mcp\Tools\Post\PublishPostTool;+use App\Mcp\Tools\Post\RequestMediaUploadTool;+use App\Mcp\Tools\Signature\CreateSignatureTool;+use App\Mcp\Tools\Signature\DeleteSignatureTool;+use App\Mcp\Tools\Signature\ListSignaturesTool;+use App\Mcp\Tools\Signature\UpdateSignatureTool;+use App\Mcp\Tools\SocialAccount\ListDiscordChannelsTool;+use App\Mcp\Tools\SocialAccount\ListPinterestBoardsTool;+use App\Mcp\Tools\SocialAccount\ListSocialAccountsTool;+use App\Mcp\Tools\SocialAccount\ToggleSocialAccountTool;+use App\Models\Media;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Models\WorkspaceLabel;+use App\Models\WorkspaceSignature;+use Illuminate\Support\Str;+use Illuminate\Testing\Fluent\AssertableJson;++beforeEach(function () {+ $this->owner = User::factory()->create();+ $this->workspace = Workspace::factory()->create(['user_id' => $this->owner->id]);+ $this->workspace->members()->attach($this->owner->id, ['role' => Role::Admin->value]);+ $this->owner->update(['current_workspace_id' => $this->workspace->id]);++ $this->viewer = User::factory()->create(['account_id' => $this->owner->account_id]);+ $this->workspace->members()->attach($this->viewer->id, ['role' => Role::Viewer->value]);+ $this->viewer->update(['current_workspace_id' => $this->workspace->id]);++ $this->member = User::factory()->create(['account_id' => $this->owner->account_id]);+ $this->workspace->members()->attach($this->member->id, ['role' => Role::Member->value]);+ $this->member->update(['current_workspace_id' => $this->workspace->id]);++ $this->post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->owner->id,+ ]);+});++test('viewers can list labels signatures and social accounts via mcp', function () {+ WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);+ WorkspaceSignature::factory()->create(['workspace_id' => $this->workspace->id]);+ SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::LinkedIn,+ ]);++ TryPostServer::actingAs($this->viewer)+ ->tool(ListLabelsTool::class, [])+ ->assertOk()+ ->assertStructuredContent(fn (AssertableJson $json) => $json->has('labels', 1)->etc());++ TryPostServer::actingAs($this->viewer)+ ->tool(ListSignaturesTool::class, [])+ ->assertOk()+ ->assertStructuredContent(fn (AssertableJson $json) => $json->has('signatures', 1)->etc());++ TryPostServer::actingAs($this->viewer)+ ->tool(ListSocialAccountsTool::class, [])+ ->assertOk()+ ->assertStructuredContent(fn (AssertableJson $json) => $json->has('social_accounts', 1)->etc());+});++test('viewers cannot publish attach media or request uploads via mcp', function () {+ $uploadToken = (string) Str::uuid();+ Media::factory()->create([+ 'mediable_type' => (new Workspace)->getMorphClass(),+ 'mediable_id' => $this->workspace->id,+ 'collection' => 'assets',+ 'upload_token' => $uploadToken,+ ]);++ TryPostServer::actingAs($this->viewer)+ ->tool(PublishPostTool::class, ['post_id' => $this->post->id])+ ->assertHasErrors(['Not authorized to publish this post.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(AttachMediaFromUrlTool::class, [+ 'post_id' => $this->post->id,+ 'urls' => [['url' => 'https://example.com/photo.jpg']],+ ])+ ->assertHasErrors(['Not authorized to update this post.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(AttachMediaFromUploadTool::class, [+ 'post_id' => $this->post->id,+ 'upload_token' => $uploadToken,+ ])+ ->assertHasErrors(['Not authorized to update this post.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(RequestMediaUploadTool::class, [])+ ->assertHasErrors(['Not authorized to upload media.']);+});++test('viewers cannot manage labels or signatures via mcp', function () {+ $label = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);+ $signature = WorkspaceSignature::factory()->create(['workspace_id' => $this->workspace->id]);++ TryPostServer::actingAs($this->viewer)+ ->tool(CreateLabelTool::class, ['name' => 'Nope', 'color' => '#112233'])+ ->assertHasErrors(['Not authorized to manage labels.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(UpdateLabelTool::class, [+ 'label_id' => $label->id,+ 'name' => 'Nope',+ 'color' => '#112233',+ ])+ ->assertHasErrors(['Not authorized to manage labels.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(DeleteLabelTool::class, ['label_id' => $label->id])+ ->assertHasErrors(['Not authorized to manage labels.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(CreateSignatureTool::class, ['name' => 'Nope', 'content' => 'x'])+ ->assertHasErrors(['Not authorized to manage signatures.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(UpdateSignatureTool::class, [+ 'signature_id' => $signature->id,+ 'name' => 'Nope',+ 'content' => 'x',+ ])+ ->assertHasErrors(['Not authorized to manage signatures.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(DeleteSignatureTool::class, ['signature_id' => $signature->id])+ ->assertHasErrors(['Not authorized to manage signatures.']);++ expect($label->fresh())->not->toBeNull()+ ->and($signature->fresh())->not->toBeNull();+});++test('viewers cannot toggle social accounts or list compose helpers via mcp', function () {+ $linkedin = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::LinkedIn,+ 'is_active' => true,+ ]);+ $discord = SocialAccount::factory()->discord()->create([+ 'workspace_id' => $this->workspace->id,+ ]);+ $pinterest = SocialAccount::factory()->pinterest()->create([+ 'workspace_id' => $this->workspace->id,+ ]);++ TryPostServer::actingAs($this->viewer)+ ->tool(ToggleSocialAccountTool::class, ['account_id' => $linkedin->id])+ ->assertHasErrors(['Not authorized to manage social accounts.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(ListDiscordChannelsTool::class, ['account_id' => $discord->id])+ ->assertHasErrors(['Not authorized to manage posts.']);++ TryPostServer::actingAs($this->viewer)+ ->tool(ListPinterestBoardsTool::class, ['account_id' => $pinterest->id])+ ->assertHasErrors(['Not authorized to manage posts.']);++ expect($linkedin->fresh()->is_active)->toBeTrue();+});++test('members cannot toggle social accounts via mcp', function () {+ $account = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::LinkedIn,+ 'is_active' => true,+ ]);++ TryPostServer::actingAs($this->member)+ ->tool(ToggleSocialAccountTool::class, ['account_id' => $account->id])+ ->assertHasErrors(['Not authorized to manage social accounts.']);++ expect($account->fresh()->is_active)->toBeTrue();+});++test('admins can toggle social accounts via mcp', function () {+ $account = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform' => Platform::LinkedIn,+ 'is_active' => true,+ ]);++ TryPostServer::actingAs($this->owner)+ ->tool(ToggleSocialAccountTool::class, ['account_id' => $account->id])+ ->assertOk();++ expect($account->fresh()->is_active)->toBeFalse();+});diff --git a/tests/Feature/Mcp/OAuthRegistrationTest.php b/tests/Feature/Mcp/OAuthRegistrationTest.phpnew file mode 100644index 000000000..8ba1f83d6--- /dev/null+++ b/tests/Feature/Mcp/OAuthRegistrationTest.php@@ -0,0 +1,83 @@+<?php++declare(strict_types=1);++use App\Enums\UserWorkspace\Role;+use App\Http\Middleware\App\EnsureCanAuthorizeMcp;+use App\Models\Account;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Str;++test('dynamic oauth client registration is rate limited', function () {+ $payload = [+ 'client_name' => 'MCP Client',+ 'redirect_uris' => ['https://client.example/callback'],+ 'grant_types' => ['authorization_code'],+ 'response_types' => ['code'],+ 'token_endpoint_auth_method' => 'none',+ ];++ for ($attempt = 0; $attempt < 30; $attempt++) {+ $this->postJson('/oauth/register', $payload)->assertSuccessful();+ }++ $this->postJson('/oauth/register', $payload)->assertTooManyRequests();+});++test('dynamic oauth registration rejects custom callback schemes', function (string $redirectUri) {+ $this->postJson('/oauth/register', [+ 'client_name' => 'Native MCP Client',+ 'redirect_uris' => [$redirectUri],+ 'grant_types' => ['authorization_code'],+ 'response_types' => ['code'],+ 'token_endpoint_auth_method' => 'none',+ ])->assertBadRequest();+})->with([+ 'cursor' => 'cursor://oauth/callback',+ 'vscode' => 'vscode://oauth/callback',+]);++test('mcp oauth consent view is available for workspace viewers', function () {+ $account = Account::factory()->create();+ $owner = User::factory()->create(['account_id' => $account->id]);+ $account->update(['owner_id' => $owner->id]);+ $workspace = Workspace::factory()->create([+ 'account_id' => $account->id,+ 'user_id' => $owner->id,+ ]);+ $workspace->members()->attach($owner->id, ['role' => Role::Admin->value]);++ $viewer = User::factory()->create(['account_id' => $account->id]);+ $workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $workspace->id]);++ $html = view('mcp.authorize', [+ 'client' => (object) [+ 'id' => (string) Str::uuid(),+ 'name' => 'Viewer Agent',+ ],+ 'user' => $viewer,+ 'scopes' => collect([(object) ['description' => 'Use MCP server']]),+ 'authToken' => 'test-auth-token',+ 'request' => request(),+ ])->render();++ expect($html)+ ->toContain('Authorize Viewer Agent')+ ->toContain($viewer->email)+ ->and(view()->exists('mcp.authorize-denied'))->toBeFalse()+ ->and(class_exists(EnsureCanAuthorizeMcp::class))->toBeFalse();+});++test('passport approve route has no mcp create-post role gate', function () {+ $route = app('router')->getRoutes()->getByName('passport.authorizations.approve');++ expect($route)->not->toBeNull();++ $middleware = collect($route->gatherMiddleware())+ ->map(fn (mixed $middleware): string => is_string($middleware) ? $middleware : $middleware::class)+ ->implode(',');++ expect($middleware)->not->toContain('EnsureCanAuthorizeMcp');+});diff --git a/tests/Feature/Mcp/PostToolTest.php b/tests/Feature/Mcp/PostToolTest.phpindex 663e2824d..57ceeba2f 100644--- a/tests/Feature/Mcp/PostToolTest.php+++ b/tests/Feature/Mcp/PostToolTest.php@@ -476,3 +476,60 @@ test('update post accepts a valid aspect_ratio and persists it', function () {expect($platform->fresh()->meta['aspect_ratio'])->toBe('16:9');});++test('viewers can list and get posts via mcp', function () {+ $viewer = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $this->workspace->id]);++ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'content' => 'Visible to viewers',+ ]);++ TryPostServer::actingAs($viewer)+ ->tool(ListPostsTool::class, [])+ ->assertOk()+ ->assertStructuredContent(function (AssertableJson $json) {+ $json->has('posts', 1)->etc();+ });++ TryPostServer::actingAs($viewer)+ ->tool(GetPostTool::class, ['post_id' => $post->id])+ ->assertOk()+ ->assertStructuredContent(function (AssertableJson $json) use ($post) {+ $json->where('id', $post->id)+ ->where('content', 'Visible to viewers')+ ->etc();+ });+});++test('viewers cannot create update or delete posts via mcp', function () {+ $viewer = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $this->workspace->id]);++ $post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'content' => 'Protected',+ ]);++ TryPostServer::actingAs($viewer)+ ->tool(CreatePostTool::class, ['content' => 'Nope'])+ ->assertHasErrors(['Not authorized to create posts.']);++ TryPostServer::actingAs($viewer)+ ->tool(UpdatePostTool::class, [+ 'post_id' => $post->id,+ 'content' => 'Changed',+ ])+ ->assertHasErrors(['Not authorized to update this post.']);++ TryPostServer::actingAs($viewer)+ ->tool(DeletePostTool::class, ['post_id' => $post->id])+ ->assertHasErrors(['Not authorized to delete this post.']);++ expect($post->fresh()->content)->toBe('Protected');+});diff --git a/tests/Feature/McpSettingsControllerTest.php b/tests/Feature/McpSettingsControllerTest.phpnew file mode 100644index 000000000..1c404b265--- /dev/null+++ b/tests/Feature/McpSettingsControllerTest.php@@ -0,0 +1,289 @@+<?php++declare(strict_types=1);++use App\Enums\UserWorkspace\Role;+use App\Models\AccessToken;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Str;++beforeEach(function (): void {+ config(['trypost.self_hosted' => false]);++ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create([+ 'account_id' => $this->user->account_id,+ 'user_id' => $this->user->id,+ ]);+ $this->workspace->members()->attach($this->user->id, ['role' => Role::Admin->value]);+ $this->user->update(['current_workspace_id' => $this->workspace->id]);+ $this->user->refresh();++ // SaaS mode: the MCP settings live behind EnsureAccountReady.+ subscribeAccount($this->user->account);+});++it('shows the mcp settings page', function (): void {+ $this->actingAs($this->user)+ ->get(route('app.mcp.index'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page+ ->component('settings/workspace/Mcp')+ ->where('mcpUrl', route('mcp.trypost'))+ ->missing('docsUrl')+ ->missing('mcpClients')+ ->has('connectedClients'));+});++it('shows the mcp settings page without a subscription in self-hosted mode', function (): void {+ config(['trypost.self_hosted' => true]);+ $this->user->account->subscriptions()->delete();++ $this->actingAs($this->user->fresh())+ ->get(route('app.mcp.index'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page+ ->component('settings/workspace/Mcp')+ ->where('mcpUrl', route('mcp.trypost')));+});++it('lists only the current users oauth clients as connected, excluding personal access tokens', function (): void {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);++ $ownerClientId = mcpOauthClient('Owner Agent');+ mcpAccessToken($this->user, $ownerClientId);++ $memberClientId = mcpOauthClient('Member Agent');+ mcpAccessToken($member, $memberClientId);++ $pat = $this->user->createToken('API Key');+ AccessToken::query()->findOrFail($pat->token->id)+ ->forceFill(['workspace_id' => $this->workspace->id])+ ->saveQuietly();++ $this->actingAs($this->user)+ ->get(route('app.mcp.index'))+ ->assertInertia(fn ($page) => $page+ ->has('connectedClients', 1)+ ->where('connectedClients.0.name', 'Owner Agent')+ ->where('connectedClients.0.can_disconnect', true)+ ->where('connectedClients', fn ($clients): bool => collect($clients)->every(+ fn (array $client): bool => $client['name'] !== 'Member Agent',+ )));+});++it('excludes unscoped oauth grants from connected clients', function (): void {+ mcpAccessToken($this->user, mcpOauthClient('Unscoped Agent'), scopes: []);++ $this->actingAs($this->user)+ ->get(route('app.mcp.index'))+ ->assertInertia(fn ($page) => $page->where('connectedClients', []));+});++it('lists viewer own oauth grants as connected clients', function (): void {+ $viewer = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $this->workspace->id]);++ mcpAccessToken($viewer, mcpOauthClient('Viewer Agent'));++ $this->actingAs($viewer->fresh())+ ->get(route('app.mcp.index'))+ ->assertInertia(fn ($page) => $page+ ->has('connectedClients', 1)+ ->where('connectedClients.0.name', 'Viewer Agent')+ ->where('connectedClients.0.can_disconnect', true));+});++it('disconnects a client by revoking its tokens', function (): void {+ $clientId = mcpOauthClient();+ $token = mcpAccessToken($this->user, $clientId);++ $this->actingAs($this->user)+ ->delete(route('app.mcp.disconnect', ['client' => $clientId]))+ ->assertRedirect()+ ->assertSessionHas('flash.success', __('mcp.disconnected'));++ expect($token->fresh()->revoked)->toBeTrue();+});++it('disconnects a client when its access token expired but its refresh token is live', function (): void {+ $clientId = mcpOauthClient();+ $token = mcpAccessToken($this->user, $clientId);+ $token->forceFill(['expires_at' => now()->subMinute()])->saveQuietly();+ $refreshTokenId = Str::random(80);+ DB::table('oauth_refresh_tokens')->insert([+ 'id' => $refreshTokenId,+ 'access_token_id' => $token->id,+ 'revoked' => false,+ 'expires_at' => now()->addMonth(),+ ]);++ $this->actingAs($this->user)+ ->delete(route('app.mcp.disconnect', ['client' => $clientId]))+ ->assertRedirect()+ ->assertSessionHas('flash.success');++ expect($token->fresh()->revoked)->toBeTrue()+ ->and(DB::table('oauth_refresh_tokens')->where('id', $refreshTokenId)->value('revoked'))->toBeTrue();+});++it('lists a client when its access token expired but its refresh token is live', function (): void {+ $clientId = mcpOauthClient('Recoverable Agent');+ $token = mcpAccessToken($this->user, $clientId);+ $token->forceFill(['expires_at' => now()->subMinute()])->saveQuietly();+ DB::table('oauth_refresh_tokens')->insert([+ 'id' => Str::random(80),+ 'access_token_id' => $token->id,+ 'revoked' => false,+ 'expires_at' => now()->addMonth(),+ ]);++ $this->actingAs($this->user)+ ->get(route('app.mcp.index'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page+ ->has('connectedClients', 1)+ ->where('connectedClients.0.name', 'Recoverable Agent')+ ->where('connectedClients.0.can_disconnect', true));+});++it('hides a client when both access and refresh tokens are expired', function (): void {+ $clientId = mcpOauthClient('Dead Agent');+ $token = mcpAccessToken($this->user, $clientId);+ $token->forceFill(['expires_at' => now()->subMinute()])->saveQuietly();+ DB::table('oauth_refresh_tokens')->insert([+ 'id' => Str::random(80),+ 'access_token_id' => $token->id,+ 'revoked' => false,+ 'expires_at' => now()->subMinute(),+ ]);++ $this->actingAs($this->user)+ ->get(route('app.mcp.index'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page->where('connectedClients', []));+});++it('does not flash success when disconnecting an unknown client', function (): void {+ $this->actingAs($this->user)+ ->delete(route('app.mcp.disconnect', ['client' => (string) Str::uuid()]))+ ->assertRedirect()+ ->assertSessionMissing('flash.success');+});++it('does not list a teammates mcp connection', function (): void {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);++ mcpAccessToken($this->user, mcpOauthClient('Owner Agent'));++ $this->actingAs($member->fresh())+ ->get(route('app.mcp.index'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page->where('connectedClients', []));+});++it('allows workspace members to view and disconnect their own mcp clients', function (): void {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);++ $clientId = mcpOauthClient('Member Agent');+ $token = mcpAccessToken($member, $clientId);++ $this->actingAs($member->fresh())+ ->get(route('app.mcp.index'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page+ ->has('connectedClients', 1)+ ->where('connectedClients.0.name', 'Member Agent'));++ $this->actingAs($member->fresh())+ ->delete(route('app.mcp.disconnect', ['client' => $clientId]))+ ->assertRedirect()+ ->assertSessionHas('flash.success');++ expect($token->fresh()->revoked)->toBeTrue();+});++it('allows workspace viewers to view and disconnect their own mcp clients', function (): void {+ $viewer = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $this->workspace->id]);++ $clientId = mcpOauthClient('Viewer Agent');+ $token = mcpAccessToken($viewer, $clientId);++ $this->actingAs($viewer->fresh())+ ->get(route('app.mcp.index'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page+ ->component('settings/workspace/Mcp')+ ->has('connectedClients', 1)+ ->where('connectedClients.0.name', 'Viewer Agent')+ ->where('connectedClients.0.can_disconnect', true));++ $this->actingAs($viewer->fresh())+ ->delete(route('app.mcp.disconnect', ['client' => $clientId]))+ ->assertRedirect()+ ->assertSessionHas('flash.success');++ expect($token->fresh()->revoked)->toBeTrue();+});++it('does not revoke another users mcp client tokens', function (): void {+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);++ $clientId = mcpOauthClient('Owner Agent');+ $token = mcpAccessToken($this->user, $clientId);++ $this->actingAs($member->fresh())+ ->delete(route('app.mcp.disconnect', ['client' => $clientId]))+ ->assertRedirect()+ ->assertSessionMissing('flash.success');++ expect($token->fresh()->revoked)->toBeFalse();+});++it('does not revoke personal access tokens via disconnect', function (): void {+ $pat = $this->user->createToken('API Key');+ $token = AccessToken::query()->findOrFail($pat->token->id);+ $token->forceFill(['workspace_id' => $this->workspace->id])->saveQuietly();++ $this->actingAs($this->user)+ ->delete(route('app.mcp.disconnect', ['client' => $token->client_id]))+ ->assertRedirect()+ ->assertSessionMissing('flash.success');++ expect($token->fresh()->revoked)->toBeFalse();+});++it('requires authentication', function (): void {+ $this->get(route('app.mcp.index'))->assertRedirect();+});++it('forbids users without workspace access', function (): void {+ $outsider = User::factory()->create();+ subscribeAccount($outsider->account);+ $outsider->update(['current_workspace_id' => $this->workspace->id]);++ $this->actingAs($outsider->fresh())+ ->get(route('app.mcp.index'))+ ->assertForbidden();+});++it('redirects to onboarding when the account has no app access', function (): void {+ $this->user->account->subscriptions()->delete();++ $this->actingAs($this->user->fresh())+ ->get(route('app.mcp.index'))+ ->assertRedirect(route('app.onboarding'));+});diff --git a/tests/Feature/WorkspaceInviteControllerTest.php b/tests/Feature/WorkspaceInviteControllerTest.phpindex ed1b6ef27..c9d396aff 100644--- a/tests/Feature/WorkspaceInviteControllerTest.php+++ b/tests/Feature/WorkspaceInviteControllerTest.php@@ -4,11 +4,14 @@ declare(strict_types=1);use App\Enums\UserWorkspace\Role as WorkspaceRole;use App\Mail\WorkspaceInvite as WorkspaceInviteMail;+use App\Models\AccessToken;use App\Models\Account;use App\Models\Invite;use App\Models\User;use App\Models\Workspace;+use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Mail;+use Illuminate\Support\Str;beforeEach(function () {Mail::fake();@@ -303,6 +306,9 @@ test('update role changes admin to member', function () {'account_id' => $this->account->id,]);$this->workspace->members()->attach($member->id, ['role' => WorkspaceRole::Admin->value]);+ $result = $member->createToken('Admin Key');+ $token = AccessToken::query()->findOrFail($result->token->id);+ $token->forceFill(['workspace_id' => $this->workspace->id])->saveQuietly();$response = $this->actingAs($this->user)->put(route('app.members.update-role', $member), ['role' => WorkspaceRole::Member->value,@@ -310,6 +316,57 @@ test('update role changes admin to member', function () {$response->assertRedirect();expect($this->workspace->members()->where('user_id', $member->id)->first()->pivot->role)->toBe(WorkspaceRole::Member->value);+ expect($token->fresh()->revoked)->toBeTrue();+});++test('demoting a member to viewer keeps their mcp oauth grants', function () {+ $member = User::factory()->create([+ 'account_id' => $this->account->id,+ ]);+ $this->workspace->members()->attach($member->id, ['role' => WorkspaceRole::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);++ $oauth = mcpAccessToken($member, mcpOauthClient());+ $refreshTokenId = (string) Str::uuid();+ DB::table('oauth_refresh_tokens')->insert([+ 'id' => $refreshTokenId,+ 'access_token_id' => $oauth->id,+ 'revoked' => false,+ 'expires_at' => now()->addDay(),+ ]);++ $response = $this->actingAs($this->user)->put(route('app.members.update-role', $member), [+ 'role' => WorkspaceRole::Viewer->value,+ ]);++ $response->assertRedirect();+ expect($oauth->fresh()->revoked)->toBeFalse()+ ->and(DB::table('oauth_refresh_tokens')->where('id', $refreshTokenId)->value('revoked'))->toBeFalse()+ ->and($member->fresh()->can('createPost', $this->workspace))->toBeFalse()+ ->and($member->fresh()->can('view', $this->workspace))->toBeTrue();+});++test('demoting to viewer on one workspace keeps mcp when they remain a member elsewhere', function () {+ $member = User::factory()->create([+ 'account_id' => $this->account->id,+ ]);+ $other = Workspace::factory()->create([+ 'user_id' => $this->user->id,+ 'account_id' => $this->account->id,+ ]);+ $this->workspace->members()->attach($member->id, ['role' => WorkspaceRole::Member->value]);+ $other->members()->attach($member->id, ['role' => WorkspaceRole::Member->value]);+ $member->update(['current_workspace_id' => $this->workspace->id]);+ $oauth = mcpAccessToken($member, mcpOauthClient());++ $response = $this->actingAs($this->user)->put(route('app.members.update-role', $member), [+ 'role' => WorkspaceRole::Viewer->value,+ ]);++ $response->assertRedirect();+ expect($oauth->fresh()->revoked)->toBeFalse()+ ->and($member->fresh()->can('createPost', $other))->toBeTrue()+ ->and($member->fresh()->can('createPost', $this->workspace))->toBeFalse();});test('update role fails for workspace owner', function () {diff --git a/tests/Pest.php b/tests/Pest.phpindex 715b1e072..1397c2aa7 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -9,6 +9,8 @@ use App\Models\Plan;use App\Models\User;use App\Models\Workspace;use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Str;use Tests\BrowserTestCase;use Tests\TestCase;@@ -161,6 +163,49 @@ function subscribeAccount(Account $account): void]);}+/**+ * Insert an OAuth client suitable for MCP connection tests.+ */+function mcpOauthClient(string $name = 'My Agent'): string+{+ $id = (string) Str::uuid();++ DB::table('oauth_clients')->insert([+ 'id' => $id,+ 'name' => $name,+ 'secret' => null,+ 'provider' => null,+ 'redirect_uris' => '[]',+ 'grant_types' => json_encode(['authorization_code']),+ 'revoked' => false,+ 'created_at' => now(),+ 'updated_at' => now(),+ ]);++ return $id;+}++/**+ * Create an active OAuth access token for MCP connection tests.+ *+ * @param list<string> $scopes+ */+function mcpAccessToken(User $user, string $clientId, array $scopes = ['mcp:use']): AccessToken+{+ $token = new AccessToken;+ $token->forceFill([+ 'id' => Str::random(80),+ 'user_id' => $user->id,+ 'client_id' => $clientId,+ 'workspace_id' => null,+ 'name' => 'MCP',+ 'scopes' => $scopes,+ 'revoked' => false,+ ])->save();++ return $token->refresh();+}+/*** Move a member onto a shared account (stranded-member / invitee fixture).*diff --git a/tests/Unit/AuthorizesMcpToolTest.php b/tests/Unit/AuthorizesMcpToolTest.phpnew file mode 100644index 000000000..e88e021bc--- /dev/null+++ b/tests/Unit/AuthorizesMcpToolTest.php@@ -0,0 +1,211 @@+<?php++declare(strict_types=1);++use App\Enums\UserWorkspace\Role;+use App\Mcp\Concerns\AuthorizesMcpTool;+use App\Models\User;+use App\Models\Workspace;+use Laravel\Mcp\Request;+use Laravel\Mcp\Response;+use Laravel\Mcp\ResponseFactory;++it('denies when the mcp request has no authenticated user', function () {+ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request, Workspace $workspace): Response|ResponseFactory|null+ {+ return $this->denyUnlessCan($request, 'view', $workspace, 'Not authorized.');+ }+ };++ $workspace = Workspace::factory()->create();+ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->once()->andReturn(null);++ $denied = $tool->probe($request, $workspace);++ expect($denied)->toBeInstanceOf(Response::class)+ ->and($denied->isError())->toBeTrue()+ ->and((string) $denied->content())->toBe('Not authorized.');+});++it('denies when the policy argument is null', function () {+ $owner = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $owner->id]);+ $workspace->members()->attach($owner->id, ['role' => Role::Admin->value]);+ $owner->update(['current_workspace_id' => $workspace->id]);++ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request): Response|ResponseFactory|null+ {+ return $this->denyUnlessCan($request, 'createPost', null, 'Not authorized to create posts.');+ }+ };++ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->once()->andReturn($owner->fresh());++ $denied = $tool->probe($request);++ expect($denied)->toBeInstanceOf(Response::class)+ ->and($denied->isError())->toBeTrue()+ ->and((string) $denied->content())->toBe('Not authorized to create posts.');+});++it('authorizeCurrentWorkspace fails closed without a user', function () {+ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request): Workspace|Response|ResponseFactory+ {+ return $this->authorizeCurrentWorkspace($request, 'createPost', 'Not authorized to create posts.');+ }+ };++ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->twice()->andReturn(null);++ $denied = $tool->probe($request);++ expect($denied)->not->toBeInstanceOf(Workspace::class)+ ->and($denied)->toBeInstanceOf(Response::class)+ ->and($denied->isError())->toBeTrue()+ ->and((string) $denied->content())->toBe('Not authorized to create posts.');+});++it('authorizeCurrentWorkspace denies when the user has no current workspace', function () {+ $owner = User::factory()->create(['current_workspace_id' => null]);++ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request): Workspace|Response|ResponseFactory+ {+ return $this->authorizeCurrentWorkspace($request, 'createPost', 'Not authorized to create posts.');+ }+ };++ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->twice()->andReturn($owner->fresh());++ $denied = $tool->probe($request);++ expect($denied)->not->toBeInstanceOf(Workspace::class)+ ->and($denied)->toBeInstanceOf(Response::class)+ ->and($denied->isError())->toBeTrue()+ ->and((string) $denied->content())->toBe('Not authorized to create posts.');+});++it('denies when the user lacks the ability', function () {+ $owner = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $owner->id]);+ $workspace->members()->attach($owner->id, ['role' => Role::Admin->value]);++ $viewer = User::factory()->create(['account_id' => $owner->account_id]);+ $workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $workspace->id]);++ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request, Workspace $workspace): Response|ResponseFactory|null+ {+ return $this->denyUnlessCan($request, 'createPost', $workspace, 'Not authorized to create posts.');+ }+ };++ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->once()->andReturn($viewer->fresh());++ $denied = $tool->probe($request, $workspace);++ expect($denied)->toBeInstanceOf(Response::class)+ ->and($denied->isError())->toBeTrue()+ ->and((string) $denied->content())->toBe('Not authorized to create posts.');+});++it('allows when the user has the ability', function () {+ $owner = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $owner->id]);+ $workspace->members()->attach($owner->id, ['role' => Role::Admin->value]);+ $owner->update(['current_workspace_id' => $workspace->id]);++ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request, Workspace $workspace): Response|ResponseFactory|null+ {+ return $this->denyUnlessCan($request, 'createPost', $workspace, 'Not authorized to create posts.');+ }+ };++ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->once()->andReturn($owner->fresh());++ expect($tool->probe($request, $workspace))->toBeNull();+});++it('authorizeCurrentWorkspace denies when the user lacks the ability', function () {+ $owner = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $owner->id]);+ $workspace->members()->attach($owner->id, ['role' => Role::Admin->value]);++ $viewer = User::factory()->create(['account_id' => $owner->account_id]);+ $workspace->members()->attach($viewer->id, ['role' => Role::Viewer->value]);+ $viewer->update(['current_workspace_id' => $workspace->id]);++ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request): Workspace|Response|ResponseFactory+ {+ return $this->authorizeCurrentWorkspace($request, 'createPost', 'Not authorized to create posts.');+ }+ };++ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->twice()->andReturn($viewer->fresh());++ $denied = $tool->probe($request);++ expect($denied)->not->toBeInstanceOf(Workspace::class)+ ->and($denied)->toBeInstanceOf(Response::class)+ ->and($denied->isError())->toBeTrue()+ ->and((string) $denied->content())->toBe('Not authorized to create posts.');+});++it('authorizeCurrentWorkspace returns the current workspace when allowed', function () {+ $owner = User::factory()->create();+ $workspace = Workspace::factory()->create(['user_id' => $owner->id]);+ $workspace->members()->attach($owner->id, ['role' => Role::Admin->value]);+ $owner->update(['current_workspace_id' => $workspace->id]);++ $tool = new class+ {+ use AuthorizesMcpTool;++ public function probe(Request $request): Workspace|Response|ResponseFactory+ {+ return $this->authorizeCurrentWorkspace($request, 'createPost', 'Not authorized to create posts.');+ }+ };++ $request = Mockery::mock(Request::class);+ $request->shouldReceive('user')->twice()->andReturn($owner->fresh());++ $result = $tool->probe($request);++ expect($result)->toBeInstanceOf(Workspace::class)+ ->and($result->is($workspace))->toBeTrue();+});diff --git a/tests/Unit/Models/AccountTest.php b/tests/Unit/Models/AccountTest.phpindex a0ae0782c..313e76102 100644--- a/tests/Unit/Models/AccountTest.php+++ b/tests/Unit/Models/AccountTest.php@@ -187,3 +187,108 @@ test('activeTrialEndsAt returns null for paying customer post-trial', function (expect($account->activeTrialEndsAt())->toBeNull();expect($account->isOnTrial())->toBeFalse();});++test('hasAppAccess is always true when self-hosted', function () {+ config(['trypost.self_hosted' => true]);++ $account = Account::factory()->create(['trial_ends_at' => null]);++ expect($account->hasAppAccess())->toBeTrue();+});++test('hasAppAccess is false without a subscription on saas', function () {+ config(['trypost.self_hosted' => false]);++ $account = Account::factory()->create(['trial_ends_at' => null]);++ expect($account->hasAppAccess())->toBeFalse();+});++test('hasAppAccess is true for an active subscription', function () {+ config(['trypost.self_hosted' => false]);++ $account = Account::factory()->create([+ 'trial_ends_at' => null,+ 'stripe_id' => 'cus_test_'.fake()->uuid(),+ ]);+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_test_'.fake()->uuid(),+ 'stripe_status' => 'active',+ 'stripe_price' => 'price_123',+ ]);++ expect($account->fresh()->hasAppAccess())->toBeTrue();+});++test('hasAppAccess is true for a trialing subscription', function () {+ config(['trypost.self_hosted' => false]);++ $account = Account::factory()->create([+ 'trial_ends_at' => null,+ 'stripe_id' => 'cus_test_'.fake()->uuid(),+ ]);+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_test_'.fake()->uuid(),+ 'stripe_status' => 'trialing',+ 'stripe_price' => 'price_123',+ 'trial_ends_at' => now()->addDays(5),+ ]);++ expect($account->fresh()->hasAppAccess())->toBeTrue();+});++test('hasAppAccess is true for a past_due subscription', function () {+ config(['trypost.self_hosted' => false]);++ $account = Account::factory()->create([+ 'trial_ends_at' => null,+ 'stripe_id' => 'cus_test_'.fake()->uuid(),+ ]);+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_test_'.fake()->uuid(),+ 'stripe_status' => 'past_due',+ 'stripe_price' => 'price_123',+ ]);++ expect($account->fresh()->hasAppAccess())->toBeTrue();+});++test('hasAppAccess ignores generic trial when card is required', function () {+ config([+ 'trypost.self_hosted' => false,+ 'trypost.billing.require_card_for_trial' => true,+ ]);++ $account = Account::factory()->create(['trial_ends_at' => now()->addDays(7)]);++ expect($account->hasAppAccess())->toBeFalse()+ ->and($account->isOnTrial())->toBeFalse();+});++test('hasAppAccess allows generic trial when card is not required', function () {+ config([+ 'trypost.self_hosted' => false,+ 'trypost.billing.require_card_for_trial' => false,+ ]);++ $account = Account::factory()->create(['trial_ends_at' => now()->addDays(7)]);++ expect($account->hasAppAccess())->toBeTrue()+ ->and($account->isOnTrial())->toBeTrue()+ ->and($account->subscribed(Account::SUBSCRIPTION_NAME))->toBeFalse();+});++test('hasAppAccess denies expired generic trial when card is not required', function () {+ config([+ 'trypost.self_hosted' => false,+ 'trypost.billing.require_card_for_trial' => false,+ ]);++ $account = Account::factory()->create(['trial_ends_at' => now()->subDay()]);++ expect($account->hasAppAccess())->toBeFalse()+ ->and($account->isOnTrial())->toBeFalse();+});diff --git a/tests/Unit/TryPostServerTest.php b/tests/Unit/TryPostServerTest.phpnew file mode 100644index 000000000..f78fb5a7b--- /dev/null+++ b/tests/Unit/TryPostServerTest.php@@ -0,0 +1,18 @@+<?php++declare(strict_types=1);++use App\Mcp\Servers\TryPostServer;+use Laravel\Mcp\Server\Attributes\Icon;++it('exposes the trypost logo as the mcp server icon', function () {+ $icons = (new ReflectionClass(TryPostServer::class))->getAttributes(Icon::class);++ expect($icons)->toHaveCount(1);++ $icon = $icons[0]->newInstance();++ expect($icon->src)->toBe('images/trypost/icon.png')+ ->and($icon->mimeType)->toBe('image/png')+ ->and($icon->theme)->toBeNull();+});