Skip to content

Beautiful Open-Source Form Builder

Ship the complete guest-first OpnForm MCP and Agent Plugin (#1261)

Julien Nahum599847748ec8
diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml
index 67a44e950..d50ce725d 100644
--- a/.github/workflows/ci-cd.yml
+++ b/.github/workflows/ci-cd.yml
@@ -315,14 +315,6 @@ jobs:
cache: npm
cache-dependency-path: client/package-lock.json
- - name: Cache Playwright Browsers
- uses: actions/cache@v4
- with:
- path: ~/.cache/ms-playwright
- key: ${{ runner.os }}-playwright-${{ hashFiles('client/package-lock.json') }}
- restore-keys: |
- ${{ runner.os }}-playwright-
-
- name: Install composer dependencies
working-directory: ./api
run: composer install --prefer-dist --no-interaction --no-progress --ignore-platform-reqs --optimize-autoloader
@@ -337,9 +329,21 @@ jobs:
name: nuxt-output
path: client/.output
- - name: Install Playwright Browsers
+ - name: Configure stable Ubuntu package mirror
+ run: |
+ if [ -f /etc/apt/apt-mirrors.txt ]; then
+ sudo sed -i 's|http://azure.archive.ubuntu.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' /etc/apt/apt-mirrors.txt
+ fi
+
+ - name: Install Playwright system dependencies
+ timeout-minutes: 5
+ working-directory: ./client
+ run: npx playwright install-deps chromium
+
+ - name: Install Playwright Chromium
+ timeout-minutes: 5
working-directory: ./client
- run: npx playwright install --with-deps chromium
+ run: npx playwright install chromium
- name: Start E2E Stack
run: ./scripts/e2e-up.sh
diff --git a/README.md b/README.md
index 031290a3f..4faec7600 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,10 @@ The easiest way to get started with OpnForm is to sign up for our [managed servi
For a complete list of features and detailed documentation, visit our [Technical Documentation](https://docs.opnform.com).
+## AI agents and MCP
+
+OpnForm's remote MCP server lets AI agents create and preview a private form draft without requiring a login. OAuth adds workspace-aware form management and read-only submission search, statistics, and exports. The installable portable and native plugin package lives in [`plugins/opnform/`](./plugins/opnform). See the [MCP integration guide](https://docs.opnform.com/integrations/mcp).
+
## Quick Start
The easiest way to get started with OpnForm is through our [official managed service in the Cloud](https://opnform.com/).
diff --git a/api/.env.example b/api/.env.example
index 3e2549af9..bfb967312 100644
--- a/api/.env.example
+++ b/api/.env.example
@@ -128,6 +128,33 @@ TELEGRAM_BOT_TOKEN=
ZAPIER_ENABLED=false
+# MCP is always enabled on OpnForm Cloud. On self-hosted instances this value
+# is the default until an admin saves an override in Settings > MCP & AI agents.
+MCP_ENABLED=false
+MCP_OBSERVABILITY_ENABLED=true
+MCP_RATE_LIMIT_PER_MINUTE=120
+MCP_RATE_LIMIT_PER_HOUR=3000
+MCP_DRAFT_CREATES_PER_MINUTE=20
+MCP_DRAFT_CREATES_PER_HOUR=200
+MCP_SUBMISSION_EXPORTS_PER_MINUTE=5
+MCP_SUBMISSION_EXPORTS_PER_HOUR=30
+# Comma-separated OAuth callback origins. Keep this allowlist explicit.
+MCP_OAUTH_REDIRECT_DOMAINS=https://chatgpt.com,https://chat.openai.com,https://claude.ai,http://localhost,http://127.0.0.1,http://[::1]
+MCP_OAUTH_CUSTOM_SCHEMES=chatgpt,claude,cursor,vscode
+# Optional issuer override. Defaults to APP_URL.
+MCP_AUTHORIZATION_SERVER=
+# Stable Passport keys are required on serverless deployments. Keep them in an encrypted environment file.
+PASSPORT_PRIVATE_KEY=
+PASSPORT_PUBLIC_KEY=
+
+FORM_SUMMARY_RATE_LIMIT_PER_MINUTE=30
+
+# Passport OAuth 2.1 is enabled by default so self-hosted admins can activate
+# MCP at runtime. Set this to false only to disable the OAuth infrastructure.
+# OAUTH_ENABLED=true
+OAUTH_ACCESS_TOKEN_TTL=10080
+OAUTH_REFRESH_TOKEN_TTL_DAYS=30
+
STRIPE_CLIENT_ID=
STRIPE_CLIENT_SECRET=
diff --git a/api/app/Console/Commands/CheckMcpOAuthKeys.php b/api/app/Console/Commands/CheckMcpOAuthKeys.php
new file mode 100644
index 000000000..74e6b9665
--- /dev/null
+++ b/api/app/Console/Commands/CheckMcpOAuthKeys.php
@@ -0,0 +1,27 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Support\Mcp\McpOAuthKeyValidator;
+use Illuminate\Console\Command;
+
+class CheckMcpOAuthKeys extends Command
+{
+ protected $signature = 'mcp:check-oauth-keys {--environment-only : Require keys from PASSPORT_PRIVATE_KEY and PASSPORT_PUBLIC_KEY}';
+
+ protected $description = 'Fail when the stable Passport key pair required by MCP OAuth is missing or invalid';
+
+ public function handle(McpOAuthKeyValidator $keys): int
+ {
+ $blockers = $keys->blockers((bool) $this->option('environment-only'));
+ if ($blockers !== []) {
+ $this->components->error($blockers[0]['message']);
+
+ return self::FAILURE;
+ }
+
+ $this->components->info('Passport OAuth keys are configured and valid.');
+
+ return self::SUCCESS;
+ }
+}
diff --git a/api/app/Console/Commands/PurgeExpiredAgentFormDrafts.php b/api/app/Console/Commands/PurgeExpiredAgentFormDrafts.php
new file mode 100644
index 000000000..cf4daa07b
--- /dev/null
+++ b/api/app/Console/Commands/PurgeExpiredAgentFormDrafts.php
@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Console\Commands;
+
+use App\Models\Forms\AgentFormDraft;
+use Illuminate\Console\Command;
+
+class PurgeExpiredAgentFormDrafts extends Command
+{
+ protected $signature = 'agent-drafts:purge-expired';
+
+ protected $description = 'Purge expired guest form drafts created through MCP and agent integrations';
+
+ public function handle(): int
+ {
+ $deleted = 0;
+
+ AgentFormDraft::query()
+ ->where('expires_at', '<=', now())
+ ->select('id')
+ ->chunkById(500, function ($drafts) use (&$deleted) {
+ $ids = $drafts->pluck('id');
+ $deleted += AgentFormDraft::query()->whereKey($ids)->delete();
+ });
+
+ $this->info("Purged {$deleted} expired agent form draft(s).");
+
+ return Command::SUCCESS;
+ }
+}
diff --git a/api/app/Console/Kernel.php b/api/app/Console/Kernel.php
index 0550cd828..807f7c5a8 100644
--- a/api/app/Console/Kernel.php
+++ b/api/app/Console/Kernel.php
@@ -27,6 +27,7 @@ class Kernel extends ConsoleKernel
$schedule->command('forms:purge-expired-submissions')->hourly()->withoutOverlapping();
$schedule->command('forms:retry-pending-submission-file-deletions')->everyFifteenMinutes()->withoutOverlapping();
$schedule->command('forms:integration-events-cleanup')->daily();
+ $schedule->command('agent-drafts:purge-expired')->hourly()->withoutOverlapping();
if (config('app.self_hosted')) {
$schedule->command('app:scheduler-status --mode=record')->everyMinute();
$schedule->command('telemetry:ping')->hourly();
diff --git a/api/app/Enums/SettingsKey.php b/api/app/Enums/SettingsKey.php
index 5a5d5cfd5..1274834c5 100644
--- a/api/app/Enums/SettingsKey.php
+++ b/api/app/Enums/SettingsKey.php
@@ -7,6 +7,7 @@ enum SettingsKey: string
case INSTANCE_ID = 'instance_id';
case INSTANCE_CREATED_AT = 'instance_created_at';
case SELF_HOSTED_LICENSE = 'self_hosted_license';
+ case MCP_ENABLED = 'mcp_enabled';
public function value(): string
{
diff --git a/api/app/Exceptions/Handler.php b/api/app/Exceptions/Handler.php
index fd3912832..3c58f6e36 100644
--- a/api/app/Exceptions/Handler.php
+++ b/api/app/Exceptions/Handler.php
@@ -42,6 +42,10 @@ class Handler extends ExceptionHandler
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
+ if ($request->routeIs('passport.authorizations.authorize')) {
+ return redirect(app(\App\Service\OAuth\McpOAuthSessionService::class)->beginAuthorization($request));
+ }
+
return response()->json(['message' => $exception->getMessage()], 401);
}
diff --git a/api/app/Http/Controllers/AgentFormDraftController.php b/api/app/Http/Controllers/AgentFormDraftController.php
new file mode 100644
index 000000000..4306f4ed3
--- /dev/null
+++ b/api/app/Http/Controllers/AgentFormDraftController.php
@@ -0,0 +1,104 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Http\Resources\FormResource;
+use App\Models\Forms\AgentFormDraft;
+use App\Models\Workspace;
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+class AgentFormDraftController extends Controller
+{
+ public const SESSION_HEADER = 'x-agent-draft-session';
+
+ public function preview(AgentFormDraft $draft, AgentFormDraftService $drafts): JsonResponse
+ {
+ abort_unless($draft->isAvailable(), Response::HTTP_NOT_FOUND);
+
+ return response()->json([
+ 'draft' => $drafts->serialize($draft),
+ ])->header('Cache-Control', 'private, no-store, max-age=0');
+ }
+
+ public function consume(Request $request, AgentFormDraftService $drafts): JsonResponse
+ {
+ $this->assertTrustedFrontend($request);
+ $validated = $request->validate([
+ 'handoff_token' => ['required', 'string', 'size:43'],
+ ]);
+ $result = $drafts->consumeEditorHandoff($validated['handoff_token']);
+
+ return response()->json([
+ 'editor_session' => $result['editor_session'],
+ 'draft' => $drafts->serialize($result['draft']),
+ ])->header('Cache-Control', 'private, no-store, max-age=0');
+ }
+
+ public function current(Request $request, AgentFormDraftService $drafts): JsonResponse
+ {
+ $this->assertTrustedFrontend($request);
+
+ return response()->json([
+ 'draft' => $drafts->serialize($drafts->getForEditor($this->editorSession($request))),
+ ])->header('Cache-Control', 'private, no-store, max-age=0');
+ }
+
+ public function replace(Request $request, AgentFormDraftService $drafts): JsonResponse
+ {
+ $this->assertTrustedFrontend($request);
+ $validated = $request->validate([
+ 'expected_version' => ['required', 'integer', 'min:1'],
+ 'definition' => ['required', 'array'],
+ ]);
+
+ $draft = $drafts->replaceFromEditor(
+ $this->editorSession($request),
+ $validated['expected_version'],
+ $validated['definition'],
+ );
+
+ return response()->json(['draft' => $drafts->serialize($draft)]);
+ }
+
+ public function claim(Request $request, AgentFormDraftService $drafts): JsonResponse
+ {
+ $this->assertTrustedFrontend($request);
+ $validated = $request->validate([
+ 'expected_version' => ['required', 'integer', 'min:1'],
+ 'workspace_id' => ['required', 'integer', 'exists:workspaces,id'],
+ ]);
+ $workspace = Workspace::query()->findOrFail($validated['workspace_id']);
+ $claimed = $drafts->claim(
+ $this->editorSession($request),
+ $validated['expected_version'],
+ $workspace,
+ $request->user(),
+ );
+
+ return response()->json([
+ 'form' => (new FormResource($claimed['form']))->setCleanings($claimed['cleanings']),
+ 'cleanings' => $claimed['cleanings'],
+ 'already_claimed' => $claimed['already_claimed'],
+ 'editor_url' => front_url('/forms/'.$claimed['form']->slug.'/edit'),
+ ]);
+ }
+
+ private function assertTrustedFrontend(Request $request): void
+ {
+ $configuredSecret = (string) config('app.front_api_secret');
+ $providedSecret = (string) $request->header('x-api-secret');
+
+ abort_unless(
+ $configuredSecret !== '' && hash_equals($configuredSecret, $providedSecret),
+ Response::HTTP_FORBIDDEN,
+ );
+ }
+
+ private function editorSession(Request $request): string
+ {
+ return (string) $request->header(self::SESSION_HEADER);
+ }
+}
diff --git a/api/app/Http/Controllers/Forms/FormController.php b/api/app/Http/Controllers/Forms/FormController.php
index 821af1291..2da51cf08 100644
--- a/api/app/Http/Controllers/Forms/FormController.php
+++ b/api/app/Http/Controllers/Forms/FormController.php
@@ -15,6 +15,8 @@ use App\Models\Workspace;
use App\Notifications\Forms\MobileEditorEmail;
use App\Service\Billing\Feature;
use App\Service\Forms\FormCleaner;
+use App\Service\Forms\FormCreationService;
+use App\Service\Forms\FormUpdateService;
use App\Service\Storage\FileUploadPathService;
use App\Service\Storage\StorageFileNameParser;
use App\Service\Storage\UploadSecurityService;
@@ -30,8 +32,10 @@ class FormController extends Controller
private FormCleaner $formCleaner;
- public function __construct()
- {
+ public function __construct(
+ private readonly FormCreationService $formCreation,
+ private readonly FormUpdateService $formUpdate,
+ ) {
$this->middleware('auth', ['except' => ['uploadAsset']]);
$this->formCleaner = new FormCleaner();
}
@@ -133,21 +137,10 @@ class FormController extends Controller
$this->authorize('ownsWorkspace', $workspace);
$this->authorize('create', [Form::class, $workspace]);
- $formData = $this->formCleaner
- ->processRequest($request)
- ->simulateCleaning($workspace)
- ->getData();
-
- $form = Form::create(array_merge($formData, [
- 'creator_id' => $request->user()->id,
- ]));
-
- if (config('app.self_hosted') && !empty($formData['slug'])) {
- $form->slug = $formData['slug'];
- $form->save();
- }
+ $created = $this->formCreation->create($request->validated(), $request->user(), $workspace);
+ $form = $created['form'];
- if ($this->formCleaner->hasCleaned()) {
+ if ($created['has_cleaned']) {
$formStatus = $form->workspace->is_trialing ? 'Non-trial' : 'Pro';
$message = 'Form successfully created, but the ' . $formStatus . ' features you used will be disabled when sharing your form:';
} else {
@@ -156,7 +149,7 @@ class FormController extends Controller
return $this->success([
'message' => $message . ($form->visibility == 'draft' ? ' But other people won\'t be able to see the form since it\'s currently in draft mode' : ''),
- 'form' => (new FormResource($form))->setCleanings($this->formCleaner->getPerformedCleanings()),
+ 'form' => (new FormResource($form))->setCleanings($created['cleanings']),
'users_first_form' => $request->user()->forms()->count() == 1,
]);
}
@@ -165,26 +158,11 @@ class FormController extends Controller
{
$this->authorize('update', $form);
- $formData = $this->formCleaner
- ->processRequest($request)
- ->simulateCleaning($form->workspace)
- ->getData();
-
- // Set Removed Properties (pre-compute lookup set to avoid O(n²) complexity)
- $newPropertyIds = collect($formData['properties'])->pluck('id')->flip()->all();
- $formData['removed_properties'] = array_merge(
- $form->removed_properties,
- collect($form->properties)->filter(function ($field) use ($newPropertyIds) {
- return !Str::of($field['type'])->startsWith('nf-') && !isset($newPropertyIds[$field['id']]);
- })->toArray()
- );
-
- $form->slug = (config('app.self_hosted') && !empty($formData['slug'])) ? $formData['slug'] : $form->slug;
-
- $form->update($formData);
+ $updated = $this->formUpdate->update($form, $request->validated());
+ $form = $updated['form'];
- if ($this->formCleaner->hasCleaned()) {
- $requiredUpgrade = collect($this->formCleaner->getCleaningKeys())
+ if ($updated['has_cleaned']) {
+ $requiredUpgrade = collect($updated['cleaning_keys'])
->flatten()
->map(fn (string $feature) => app(\App\Service\Billing\PlanAccessService::class)->getFormFeatureRequiredTier($feature))
->filter()
@@ -200,7 +178,7 @@ class FormController extends Controller
return $this->success([
'message' => $message . ($form->visibility == 'draft' ? ' But other people won\'t be able to see the form since it\'s currently in draft mode' : ''),
- 'form' => (new FormResource($form))->setCleanings($this->formCleaner->getPerformedCleanings()),
+ 'form' => (new FormResource($form))->setCleanings($updated['cleanings']),
]);
}
diff --git a/api/app/Http/Controllers/McpOAuthRegisterController.php b/api/app/Http/Controllers/McpOAuthRegisterController.php
new file mode 100644
index 000000000..0c8979e43
--- /dev/null
+++ b/api/app/Http/Controllers/McpOAuthRegisterController.php
@@ -0,0 +1,37 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Laravel\Mcp\Server\Http\Controllers\OAuthRegisterController;
+
+class McpOAuthRegisterController extends OAuthRegisterController
+{
+ protected function isValidRedirectUri(string $value): bool
+ {
+ // Passport 12 persists multiple redirects as a comma-delimited string.
+ // A literal comma inside one URI would become an unvalidated redirect
+ // when Passport reads the client back from storage.
+ return strlen($value) <= 2048
+ && ! str_contains($value, ',')
+ && parent::isValidRedirectUri($value);
+ }
+
+ protected function isLocalhostUrl(string $url): bool
+ {
+ if (strtolower((string) parse_url($url, PHP_URL_SCHEME)) !== 'http') {
+ return false;
+ }
+
+ if (parse_url($url, PHP_URL_USER) !== null || parse_url($url, PHP_URL_PASS) !== null) {
+ return false;
+ }
+
+ $host = parse_url($url, PHP_URL_HOST);
+
+ return is_string($host) && in_array(
+ strtolower(trim($host, '[]')),
+ ['localhost', '127.0.0.1', '::1'],
+ true,
+ );
+ }
+}
diff --git a/api/app/Http/Controllers/McpOAuthSessionController.php b/api/app/Http/Controllers/McpOAuthSessionController.php
new file mode 100644
index 000000000..02b83b842
--- /dev/null
+++ b/api/app/Http/Controllers/McpOAuthSessionController.php
@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Models\User;
+use App\Service\OAuth\McpOAuthSessionService;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\Request;
+
+class McpOAuthSessionController extends Controller
+{
+ public function __invoke(Request $request, McpOAuthSessionService $sessions): JsonResponse
+ {
+ $validated = $request->validate([
+ 'authorization_request_token' => ['required', 'string', 'size:64'],
+ ]);
+
+ /** @var User $user */
+ $user = $request->user();
+
+ return response()->json([
+ 'authorization_url' => $sessions->issueLoginTicket(
+ $validated['authorization_request_token'],
+ $user
+ ),
+ ]);
+ }
+}
diff --git a/api/app/Http/Controllers/RevokeMcpOAuthSessionController.php b/api/app/Http/Controllers/RevokeMcpOAuthSessionController.php
new file mode 100644
index 000000000..747187526
--- /dev/null
+++ b/api/app/Http/Controllers/RevokeMcpOAuthSessionController.php
@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Models\User;
+use Illuminate\Auth\AuthenticationException;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+use Laravel\Passport\Token;
+use Symfony\Component\HttpFoundation\Response;
+
+class RevokeMcpOAuthSessionController extends Controller
+{
+ public function __invoke(Request $request): Response
+ {
+ $user = $request->user();
+ $token = $user instanceof User ? $user->currentAccessToken() : null;
+
+ if (! $token instanceof Token || ! $token->can('mcp:use')) {
+ throw new AuthenticationException('A valid MCP access token is required.', ['oauth']);
+ }
+
+ DB::transaction(function () use ($token): void {
+ $token->refreshToken()->update(['revoked' => true]);
+ $token->revoke();
+ });
+
+ return response()->noContent();
+ }
+}
diff --git a/api/app/Http/Controllers/Settings/LicenseController.php b/api/app/Http/Controllers/Settings/LicenseController.php
index d426180bb..273439d65 100644
--- a/api/app/Http/Controllers/Settings/LicenseController.php
+++ b/api/app/Http/Controllers/Settings/LicenseController.php
@@ -3,10 +3,10 @@
namespace App\Http\Controllers\Settings;
use App\Http\Controllers\Controller;
-use App\Models\User;
use App\Service\License\LicenseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
class LicenseController extends Controller
{
@@ -91,10 +91,7 @@ class LicenseController extends Controller
private function authorizeLicenseManagement(Request $request): void
{
- $user = $request->user();
- if (!$user || !$user->workspaces()->wherePivot('role', User::ROLE_ADMIN)->exists()) {
- abort(403, 'You need to be a workspace admin to manage the instance license.');
- }
+ Gate::authorize('manage-instance-settings');
}
private function activationFailureMessage(string $status): string
diff --git a/api/app/Http/Controllers/Settings/McpSettingsController.php b/api/app/Http/Controllers/Settings/McpSettingsController.php
new file mode 100644
index 000000000..ca795e7ca
--- /dev/null
+++ b/api/app/Http/Controllers/Settings/McpSettingsController.php
@@ -0,0 +1,61 @@
+<?php
+
+namespace App\Http\Controllers\Settings;
+
+use App\Enums\SettingsKey;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\Settings\UpdateMcpSettingsRequest;
+use App\Models\Setting;
+use App\Support\Mcp\McpAvailability;
+use App\Support\Mcp\McpConnectionConfiguration;
+use App\Support\Mcp\McpOAuthReadiness;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Support\Facades\Gate;
+
+final class McpSettingsController extends Controller
+{
+ public function show(
+ McpAvailability $availability,
+ McpConnectionConfiguration $connection,
+ ): JsonResponse {
+ Gate::authorize('manage-instance-settings');
+
+ return response()->json($this->payload($availability, $connection));
+ }
+
+ public function update(
+ UpdateMcpSettingsRequest $request,
+ McpAvailability $availability,
+ McpOAuthReadiness $readiness,
+ McpConnectionConfiguration $connection,
+ ): JsonResponse {
+ $enabled = (bool) $request->validated('enabled');
+ $readinessResult = $readiness->inspect();
+
+ if ($enabled && ! $readinessResult['ready']) {
+ return response()->json([
+ 'message' => 'Complete the MCP OAuth prerequisites before enabling MCP.',
+ 'blockers' => $readinessResult['blockers'],
+ ], 422);
+ }
+
+ Setting::set(SettingsKey::MCP_ENABLED, $enabled);
+
+ return response()->json($this->payload($availability, $connection, $readinessResult));
+ }
+
+ /**
+ * @param array{ready: bool, blockers: array<int, array{code: string, message: string}>}|null $readiness
+ */
+ private function payload(
+ McpAvailability $availability,
+ McpConnectionConfiguration $connection,
+ ?array $readiness = null,
+ ): array {
+ $status = $availability->status($readiness);
+
+ return array_merge($status, [
+ 'source' => $status['configured_value'] === null ? 'environment' : 'settings',
+ ], $connection->forSelfHostedInstance());
+ }
+}
diff --git a/api/app/Http/Kernel.php b/api/app/Http/Kernel.php
index aeac22fcd..c604a04ac 100644
--- a/api/app/Http/Kernel.php
+++ b/api/app/Http/Kernel.php
@@ -19,6 +19,12 @@ use Illuminate\Routing\Router;
use App\Http\Middleware\CheckUserIsBlocked;
use App\Http\Middleware\EnsureCloudInstance;
use App\Http\Middleware\EnsureSelfHostedInstance;
+use App\Http\Middleware\ConsumeMcpOAuthLoginTicket;
+use App\Http\Middleware\AuthenticateOptionalMcpOAuth;
+use App\Http\Middleware\RecordMcpUsage;
+use App\Http\Middleware\ThrottleFormSummary;
+use App\Http\Middleware\EnsureMcpEnabled;
+use App\Http\Middleware\EnsureMcpGuestDraftsEnabled;
class Kernel extends HttpKernel
{
@@ -57,6 +63,8 @@ class Kernel extends HttpKernel
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
+ EnsureMcpEnabled::class,
+ EnsureMcpGuestDraftsEnabled::class,
AuthenticateJWT::class,
AuthenticateWithJwtOrSanctum::class,
\Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
@@ -78,6 +86,7 @@ class Kernel extends HttpKernel
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
+ ConsumeMcpOAuthLoginTicket::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
@@ -132,6 +141,11 @@ class Kernel extends HttpKernel
'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
'auth.multi' => \App\Http\Middleware\AuthenticateWithJwtOrSanctum::class,
+ 'auth.mcp.optional' => AuthenticateOptionalMcpOAuth::class,
+ 'observe.mcp' => RecordMcpUsage::class,
+ 'mcp.enabled' => EnsureMcpEnabled::class,
+ 'mcp.guest-drafts' => EnsureMcpGuestDraftsEnabled::class,
+ 'throttle.form-summary' => ThrottleFormSummary::class,
'cloud' => EnsureCloudInstance::class, // Allow cloud instances only
'self-hosted' => EnsureSelfHostedInstance::class, // Allow self-hosted instances only
diff --git a/api/app/Http/Middleware/AuthenticateOptionalMcpOAuth.php b/api/app/Http/Middleware/AuthenticateOptionalMcpOAuth.php
new file mode 100644
index 000000000..17b881c10
--- /dev/null
+++ b/api/app/Http/Middleware/AuthenticateOptionalMcpOAuth.php
@@ -0,0 +1,37 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Auth\AuthenticationException;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+use Symfony\Component\HttpFoundation\Response;
+
+class AuthenticateOptionalMcpOAuth
+{
+ public function handle(Request $request, Closure $next): Response
+ {
+ if (! $request->bearerToken()) {
+ return $next($request);
+ }
+
+ $guard = Auth::guard('oauth');
+ $user = $guard->user();
+
+ if (! $user || ! $user->tokenCan('mcp:use')) {
+ throw new AuthenticationException('Invalid or insufficient MCP access token.', ['oauth']);
+ }
+
+ if ($user->is_blocked) {
+ return response()->json([
+ 'message' => 'Your account has been blocked. Please contact support.',
+ ], 403);
+ }
+
+ Auth::shouldUse('oauth');
+ Auth::setUser($user);
+
+ return $next($request);
+ }
+}
diff --git a/api/app/Http/Middleware/ConsumeMcpOAuthLoginTicket.php b/api/app/Http/Middleware/ConsumeMcpOAuthLoginTicket.php
new file mode 100644
index 000000000..2bb25c3d0
--- /dev/null
+++ b/api/app/Http/Middleware/ConsumeMcpOAuthLoginTicket.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use App\Service\OAuth\McpOAuthSessionService;
+use Closure;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+class ConsumeMcpOAuthLoginTicket
+{
+ public function __construct(private readonly McpOAuthSessionService $sessions)
+ {
+ }
+
+ public function handle(Request $request, Closure $next): Response
+ {
+ if ($request->routeIs('passport.authorizations.authorize') && $request->filled('mcp_login_ticket')) {
+ $this->sessions->consumeLoginTicket(
+ (string) $request->query('mcp_login_ticket'),
+ $request
+ );
+
+ return redirect($this->sessions->withoutLoginTicket($request));
+ }
+
+ return $next($request);
+ }
+}
diff --git a/api/app/Http/Middleware/EnsureMcpEnabled.php b/api/app/Http/Middleware/EnsureMcpEnabled.php
new file mode 100644
index 000000000..111fcc97c
--- /dev/null
+++ b/api/app/Http/Middleware/EnsureMcpEnabled.php
@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use App\Support\Mcp\McpAvailability;
+use Closure;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+final class EnsureMcpEnabled
+{
+ public function __construct(private readonly McpAvailability $availability)
+ {
+ }
+
+ public function handle(Request $request, Closure $next): Response
+ {
+ abort_unless($this->availability->available(), Response::HTTP_NOT_FOUND);
+
+ return $next($request);
+ }
+}
diff --git a/api/app/Http/Middleware/EnsureMcpGuestDraftsEnabled.php b/api/app/Http/Middleware/EnsureMcpGuestDraftsEnabled.php
new file mode 100644
index 000000000..9a04b9fa1
--- /dev/null
+++ b/api/app/Http/Middleware/EnsureMcpGuestDraftsEnabled.php
@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use App\Support\Mcp\McpAvailability;
+use Closure;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+final class EnsureMcpGuestDraftsEnabled
+{
+ public function __construct(private readonly McpAvailability $availability)
+ {
+ }
+
+ public function handle(Request $request, Closure $next): Response
+ {
+ abort_unless($this->availability->guestDraftsEnabled(), Response::HTTP_NOT_FOUND);
+
+ return $next($request);
+ }
+}
diff --git a/api/app/Http/Middleware/RecordMcpUsage.php b/api/app/Http/Middleware/RecordMcpUsage.php
new file mode 100644
index 000000000..5e84f5997
--- /dev/null
+++ b/api/app/Http/Middleware/RecordMcpUsage.php
@@ -0,0 +1,108 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use App\Service\Telemetry\TelemetryEvent;
+use Closure;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Log;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
+use Throwable;
+
+class RecordMcpUsage
+{
+ public function handle(Request $request, Closure $next): Response
+ {
+ if (! config('opnform.mcp.observability_enabled', true)) {
+ return $next($request);
+ }
+
+ $startedAt = hrtime(true);
+ try {
+ [$method, $tool] = $this->operation($request);
+ } catch (Throwable) {
+ [$method, $tool] = ['unknown', null];
+ }
+
+ try {
+ $response = $next($request);
+ } catch (Throwable $exception) {
+ $status = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;
+ $this->recordSafely($request, $method, $tool, $status, 'error', $startedAt);
+
+ throw $exception;
+ }
+
+ $this->recordSafely(
+ $request,
+ $method,
+ $tool,
+ $response->getStatusCode(),
+ $this->outcome($response),
+ $startedAt,
+ );
+
+ return $response;
+ }
+
+ /**
+ * @return array{0: string, 1: string|null}
+ */
+ private function operation(Request $request): array
+ {
+ $payload = $request->json()->all();
+ $method = is_string($payload['method'] ?? null) ? $payload['method'] : 'unknown';
+ $tool = $method === 'tools/call' && is_string($payload['params']['name'] ?? null)
+ ? $payload['params']['name']
+ : null;
+
+ return [$method, $tool];
+ }
+
+ private function outcome(Response $response): string
+ {
+ if ($response->getStatusCode() >= 400) {
+ return 'error';
+ }
+
+ $content = $response->getContent();
+ if (! is_string($content)) {
+ return 'success';
+ }
+
+ $payload = json_decode($content, true);
+ if (! is_array($payload)) {
+ return 'success';
+ }
+
+ return isset($payload['error']) || ($payload['result']['isError'] ?? false) === true
+ ? 'error'
+ : 'success';
+ }
+
+ private function recordSafely(
+ Request $request,
+ string $method,
+ ?string $tool,
+ int $status,
+ string $outcome,
+ int $startedAt,
+ ): void {
+ try {
+ $properties = array_filter([
+ 'method' => $method,
+ 'tool' => $tool,
+ 'auth_mode' => $request->user() ? 'oauth' : 'guest',
+ 'outcome' => $outcome,
+ 'status' => $status,
+ 'duration_ms' => (int) round((hrtime(true) - $startedAt) / 1_000_000),
+ ], fn (mixed $value): bool => $value !== null);
+
+ Log::info('MCP request completed', $properties);
+ telemetry(TelemetryEvent::MCP_REQUEST, $properties);
+ } catch (Throwable) {
+ // Observability must never interrupt an MCP request.
+ }
+ }
+}
diff --git a/api/app/Http/Middleware/RequireOAuthS256.php b/api/app/Http/Middleware/RequireOAuthS256.php
new file mode 100644
index 000000000..668883fdc
--- /dev/null
+++ b/api/app/Http/Middleware/RequireOAuthS256.php
@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+final class RequireOAuthS256
+{
+ public function handle(Request $request, Closure $next): Response
+ {
+ if (! hash_equals('S256', (string) $request->query('code_challenge_method'))) {
+ return new JsonResponse([
+ 'error' => 'invalid_request',
+ 'error_description' => 'The code_challenge_method must be S256.',
+ ], 400);
+ }
+
+ return $next($request);
+ }
+}
diff --git a/api/app/Http/Middleware/SecureOAuthConsent.php b/api/app/Http/Middleware/SecureOAuthConsent.php
new file mode 100644
index 000000000..feec68a6d
--- /dev/null
+++ b/api/app/Http/Middleware/SecureOAuthConsent.php
@@ -0,0 +1,22 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+final class SecureOAuthConsent
+{
+ public function handle(Request $request, Closure $next): Response
+ {
+ $response = $next($request);
+ $response->headers->set('Content-Security-Policy', "frame-ancestors 'none'");
+ $response->headers->set('X-Frame-Options', 'DENY');
+ $response->headers->set('Referrer-Policy', 'no-referrer');
+ $response->headers->set('Cache-Control', 'no-store, private');
+ $response->headers->set('Pragma', 'no-cache');
+
+ return $response;
+ }
+}
diff --git a/api/app/Http/Middleware/ThrottleFormSummary.php b/api/app/Http/Middleware/ThrottleFormSummary.php
new file mode 100644
index 000000000..d9c62398f
--- /dev/null
+++ b/api/app/Http/Middleware/ThrottleFormSummary.php
@@ -0,0 +1,46 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use App\Service\Forms\FormSummaryRateLimiter;
+use Closure;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+class ThrottleFormSummary
+{
+ public function __construct(private readonly FormSummaryRateLimiter $rateLimiter)
+ {
+ }
+
+ public function handle(Request $request, Closure $next): Response
+ {
+ $userId = (int) $request->user()->getAuthIdentifier();
+ if (! $this->rateLimiter->attempt($userId)) {
+ $retryAfter = max(1, $this->rateLimiter->availableIn($userId));
+
+ return new JsonResponse([
+ 'message' => 'Too many submission statistics requests. Try again later.',
+ 'retry_after' => $retryAfter,
+ ], 429, $this->headers($userId, $retryAfter));
+ }
+
+ $response = $next($request);
+ foreach ($this->headers($userId) as $name => $value) {
+ $response->headers->set($name, (string) $value);
+ }
+
+ return $response;
+ }
+
+ /** @return array<string, int> */
+ private function headers(int $userId, ?int $retryAfter = null): array
+ {
+ return array_filter([
+ 'X-RateLimit-Limit' => $this->rateLimiter->limit(),
+ 'X-RateLimit-Remaining' => $this->rateLimiter->remaining($userId),
+ 'Retry-After' => $retryAfter,
+ ], fn (?int $value) => $value !== null);
+ }
+}
diff --git a/api/app/Http/Requests/Settings/UpdateMcpSettingsRequest.php b/api/app/Http/Requests/Settings/UpdateMcpSettingsRequest.php
new file mode 100644
index 000000000..9158eda2f
--- /dev/null
+++ b/api/app/Http/Requests/Settings/UpdateMcpSettingsRequest.php
@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Http\Requests\Settings;
+
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Support\Facades\Gate;
+
+final class UpdateMcpSettingsRequest extends FormRequest
+{
+ public function authorize(): bool
+ {
+ return Gate::allows('manage-instance-settings');
+ }
+
+ public function rules(): array
+ {
+ return [
+ 'enabled' => ['required', 'boolean'],
+ ];
+ }
+}
diff --git a/api/app/Http/Requests/UserFormRequest.php b/api/app/Http/Requests/UserFormRequest.php
index fc8f96ab4..216525b2a 100644
--- a/api/app/Http/Requests/UserFormRequest.php
+++ b/api/app/Http/Requests/UserFormRequest.php
@@ -13,8 +13,7 @@ use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use App\Rules\CssOnlyRule;
-use Illuminate\Support\Str;
-use Stevebauman\Purify\Facades\Purify;
+use App\Service\Forms\FormDataNormalizer;
/**
* Abstract class to validate create/update forms
@@ -33,64 +32,7 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest
protected function prepareForValidation()
{
- $data = $this->all();
-
- if (isset($data['title']) && is_string($data['title'])) {
- $data['title'] = Str::substr(trim($data['title']), 0, 255);
- }
-
- if (isset($data['properties']) && is_array($data['properties'])) {
- $data['properties'] = array_map(function ($property) {
- if (!is_array($property)) {
- return $property;
- }
-
- if (isset($property['name']) && is_string($property['name'])) {
- $property['name'] = trim(strip_tags($property['name']));
- }
-
- if (isset($property['help']) && is_string($property['help'])) {
- $property['help'] = Purify::clean($property['help']);
- if (strip_tags($property['help']) === '') {
- $property['help'] = null;
- }
- }
- $property = $this->normalizeSelectOptionIds($property);
- return $property;
- }, $data['properties']);
- }
-
- $this->merge($data);
- }
-
- /**
- * Backfill option ids for legacy select fields before strict property validation runs.
- */
- private function normalizeSelectOptionIds(array $property): array
- {
- $type = $property['type'] ?? null;
-
- if (!in_array($type, ['select', 'multi_select'], true)) {
- return $property;
- }
-
- if (!isset($property[$type]['options']) || !is_array($property[$type]['options'])) {
- return $property;
- }
-
- $property[$type]['options'] = array_map(function ($option) {
- if (!is_array($option) || !empty($option['id'] ?? null)) {
- return $option;
- }
-
- if (!empty($option['name'] ?? null) && is_string($option['name'])) {
- $option['id'] = $option['name'];
- }
-
- return $option;
- }, $property[$type]['options']);
-
- return $property;
+ $this->merge(app(FormDataNormalizer::class)->normalize($this->all()));
}
/**
diff --git a/api/app/Mcp/Apps/FormDraftPreviewApp.php b/api/app/Mcp/Apps/FormDraftPreviewApp.php
new file mode 100644
index 000000000..395aaef13
--- /dev/null
+++ b/api/app/Mcp/Apps/FormDraftPreviewApp.php
@@ -0,0 +1,67 @@
+<?php
+
+namespace App\Mcp\Apps;
+
+use App\Support\Mcp\McpAvailability;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\Server\AppResource;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Attributes\Uri;
+use Laravel\Mcp\Server\Ui\AppMeta;
+use Laravel\Mcp\Server\Ui\Csp;
+
+#[Name('form_draft_preview')]
+#[Description('Interactive preview of a guest OpnForm draft with a secure editor handoff.')]
+#[Uri('ui://opnform/form-draft-preview-v3')]
+class FormDraftPreviewApp extends AppResource
+{
+ public function shouldRegister(McpAvailability $availability): bool
+ {
+ return $availability->guestDraftsEnabled();
+ }
+
+ public function handle(Request $request): Response
+ {
+ $response = Response::view('mcp.form-draft-preview-app');
+ $origin = $this->frontOrigin();
+
+ if ($origin !== null) {
+ $response->withMeta('openai/widgetCSP', [
+ 'connect_domains' => [],
+ 'resource_domains' => [$origin],
+ 'frame_domains' => [$origin],
+ 'redirect_domains' => [$origin],
+ ]);
+ }
+
+ return $response;
+ }
+
+ public function appMeta(): AppMeta
+ {
+ $origin = $this->frontOrigin();
+ if ($origin === null) {
+ return AppMeta::make();
+ }
+
+ return AppMeta::make()->csp(
+ Csp::make()
+ ->resourceDomains([$origin])
+ ->frameDomains([$origin]),
+ );
+ }
+
+ private function frontOrigin(): ?string
+ {
+ $frontUrl = parse_url(front_url());
+ if (! is_array($frontUrl) || ! isset($frontUrl['scheme'], $frontUrl['host'])) {
+ return null;
+ }
+
+ $origin = $frontUrl['scheme'].'://'.$frontUrl['host'];
+
+ return isset($frontUrl['port']) ? $origin.':'.$frontUrl['port'] : $origin;
+ }
+}
diff --git a/api/app/Mcp/Methods/CallTool.php b/api/app/Mcp/Methods/CallTool.php
new file mode 100644
index 000000000..7bf0313ff
--- /dev/null
+++ b/api/app/Mcp/Methods/CallTool.php
@@ -0,0 +1,36 @@
+<?php
+
+namespace App\Mcp\Methods;
+
+use Illuminate\Auth\AuthenticationException;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Transport\JsonRpcRequest;
+use Throwable;
+
+class CallTool extends \Laravel\Mcp\Server\Methods\CallTool
+{
+ protected function callHandler(callable $handler, JsonRpcRequest $request): mixed
+ {
+ try {
+ return $handler();
+ } catch (AuthenticationException $exception) {
+ return $this->authenticationRequired($exception);
+ } catch (Throwable $throwable) {
+ return $this->toErrorResponse($throwable);
+ }
+ }
+
+ protected function authenticationRequired(AuthenticationException $exception): ResponseFactory
+ {
+ $resourceMetadata = route('mcp.oauth.protected-resource.nested', ['path' => 'mcp']);
+ $challenge = sprintf(
+ 'Bearer resource_metadata="%s", scope="mcp:use", error="insufficient_scope", error_description="%s"',
+ $resourceMetadata,
+ 'Connect your OpnForm account to continue',
+ );
+
+ return Response::make(Response::error($exception->getMessage()))
+ ->withMeta('mcp/www_authenticate', [$challenge]);
+ }
+}
diff --git a/api/app/Mcp/Resources/FormDefinitionSchemaResource.php b/api/app/Mcp/Resources/FormDefinitionSchemaResource.php
new file mode 100644
index 000000000..f99854fd8
--- /dev/null
+++ b/api/app/Mcp/Resources/FormDefinitionSchemaResource.php
@@ -0,0 +1,24 @@
+<?php
+
+namespace App\Mcp\Resources;
+
+use App\Service\Forms\AgentFormDefinition;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\MimeType;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Attributes\Uri;
+use Laravel\Mcp\Server\Resource;
+
+#[Name('form_definition_schema')]
+#[Description('Versioned JSON Schema for OpnForm agent form definitions.')]
+#[Uri('opnform://schemas/agent-form-definition/v1')]
+#[MimeType('application/schema+json')]
+class FormDefinitionSchemaResource extends Resource
+{
+ public function handle(Request $request, AgentFormDefinition $definition): Response
+ {
+ return Response::json($definition->jsonSchema());
+ }
+}
diff --git a/api/app/Mcp/Resources/FormFieldCatalogResource.php b/api/app/Mcp/Resources/FormFieldCatalogResource.php
new file mode 100644
index 000000000..aa3c787c3
--- /dev/null
+++ b/api/app/Mcp/Resources/FormFieldCatalogResource.php
@@ -0,0 +1,24 @@
+<?php
+
+namespace App\Mcp\Resources;
+
+use App\Service\Forms\AgentFormFieldCatalog;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\MimeType;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Attributes\Uri;
+use Laravel\Mcp\Server\Resource;
+
+#[Name('form_field_catalog')]
+#[Description('Canonical OpnForm field, presentation, media, and layout reference, including focused-mode guidance, aliases, and plan behavior.')]
+#[Uri('opnform://reference/form-fields/v1')]
+#[MimeType('application/json')]
+class FormFieldCatalogResource extends Resource
+{
+ public function handle(Request $request): Response
+ {
+ return Response::json(AgentFormFieldCatalog::reference());
+ }
+}
diff --git a/api/app/Mcp/Servers/OpnFormServer.php b/api/app/Mcp/Servers/OpnFormServer.php
new file mode 100644
index 000000000..2ea1e330e
--- /dev/null
+++ b/api/app/Mcp/Servers/OpnFormServer.php
@@ -0,0 +1,76 @@
+<?php
+
+namespace App\Mcp\Servers;
+
+use App\Mcp\Apps\FormDraftPreviewApp;
+use App\Mcp\Methods\CallTool;
+use App\Mcp\Resources\FormDefinitionSchemaResource;
+use App\Mcp\Resources\FormFieldCatalogResource;
+use App\Mcp\Tools\CreateFormDraftTool;
+use App\Mcp\Tools\GetFormDraftTool;
+use App\Mcp\Tools\GetAccountContextTool;
+use App\Mcp\Tools\ListWorkspacesTool;
+use App\Mcp\Tools\GetWorkspaceTool;
+use App\Mcp\Tools\ListFormsTool;
+use App\Mcp\Tools\GetFormTool;
+use App\Mcp\Tools\CreateFormTool;
+use App\Mcp\Tools\UpdateFormTool;
+use App\Mcp\Tools\PublishFormTool;
+use App\Mcp\Tools\TrashFormTool;
+use App\Mcp\Tools\ListSubmissionsTool;
+use App\Mcp\Tools\GetSubmissionTool;
+use App\Mcp\Tools\GetSubmissionStatsTool;
+use App\Mcp\Tools\ExportSubmissionsTool;
+use App\Mcp\Tools\GetSubmissionExportTool;
+use App\Mcp\Tools\PatchFormDraftTool;
+use App\Mcp\Tools\PreviewFormDraftTool;
+use App\Mcp\Tools\OpenFormDraftInEditorTool;
+use App\Mcp\Tools\ValidateFormDefinitionTool;
+use Laravel\Mcp\Server;
+use Laravel\Mcp\Server\Attributes\Instructions;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Attributes\Version;
+
+#[Name('OpnForm')]
+#[Version('1.0.0')]
+#[Instructions('Use OpnForm MCP tools directly. Never invoke Codex or ChatGPT recursively, run `codex exec`, use shell or raw HTTP, inspect repositories or caches, or switch connectors. If the tools required for the active workflow are unexpectedly missing, stop and ask the user to start a new conversation with OpnForm selected before the first message. All account, form, and submission tools require OAuth. Enabling the plugin is not OAuth authentication. In local Codex, start a new conversation after OAuth so the MCP client loads the stored credential. When guest draft tools are available, they need no login. When they are unavailable, authenticate and use create_form to save an unpublished draft in a writable workspace. If an account tool challenges, ask the user to authenticate the OpnForm MCP server in the host; do not repeatedly retry from the guest conversation. Read the schema and field catalog before generating a form or changing its presentation, fields, layout, or media, then validate before saving. Focused presentation creates one step per block automatically: use full-width blocks, no page breaks or standalone media blocks, and attach optional media through the block image property. Use only durable public HTTPS asset URLs, never localhost or temporary tunnel URLs.')]
+class OpnFormServer extends Server
+{
+ public int $maxPaginationLength = 100;
+
+ public int $defaultPaginationLength = 50;
+
+ protected array $tools = [
+ ValidateFormDefinitionTool::class,
+ CreateFormDraftTool::class,
+ GetFormDraftTool::class,
+ PatchFormDraftTool::class,
+ PreviewFormDraftTool::class,
+ OpenFormDraftInEditorTool::class,
+ GetAccountContextTool::class,
+ ListWorkspacesTool::class,
+ GetWorkspaceTool::class,
+ ListFormsTool::class,
+ GetFormTool::class,
+ CreateFormTool::class,
+ UpdateFormTool::class,
+ PublishFormTool::class,
+ TrashFormTool::class,
+ ListSubmissionsTool::class,
+ GetSubmissionTool::class,
+ GetSubmissionStatsTool::class,
+ ExportSubmissionsTool::class,
+ GetSubmissionExportTool::class,
+ ];
+
+ protected array $resources = [
+ FormDefinitionSchemaResource::class,
+ FormFieldCatalogResource::class,
+ FormDraftPreviewApp::class,
+ ];
+
+ protected function boot(): void
+ {
+ $this->addMethod('tools/call', CallTool::class);
+ }
+}
diff --git a/api/app/Mcp/Tools/AuthenticatedMcpTool.php b/api/app/Mcp/Tools/AuthenticatedMcpTool.php
new file mode 100644
index 000000000..64f8f536d
--- /dev/null
+++ b/api/app/Mcp/Tools/AuthenticatedMcpTool.php
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Models\User;
+use Illuminate\Auth\AuthenticationException;
+use Laravel\Mcp\Request;
+
+abstract class AuthenticatedMcpTool extends McpTool
+{
+ /**
+ * @return list<array{type: string, scopes: list<string>}>
+ */
+ protected function securitySchemes(): array
+ {
+ return [
+ [
+ 'type' => 'oauth2',
+ 'scopes' => ['mcp:use'],
+ ],
+ ];
+ }
+
+ protected function user(Request $request): User
+ {
+ $user = $request->user('oauth');
+
+ if (! $user instanceof User) {
+ throw new AuthenticationException('Connect your OpnForm account with OAuth to use this tool.');
+ }
+
+ return $user;
+ }
+}
diff --git a/api/app/Mcp/Tools/CreateFormDraftTool.php b/api/app/Mcp/Tools/CreateFormDraftTool.php
new file mode 100644
index 000000000..05b30319b
--- /dev/null
+++ b/api/app/Mcp/Tools/CreateFormDraftTool.php
@@ -0,0 +1,55 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\AgentFormDraftRateLimiter;
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('create_form_draft')]
+#[Description('Create a private server-side OpnForm draft that expires after seven days. Works without login. Returns a capability token once; keep it private and use it with get_form_draft and patch_form_draft. The form remains an unpublished draft.')]
+#[IsOpenWorld(false)]
+class CreateFormDraftTool extends GuestDraftMcpTool
+{
+ public function handle(
+ Request $request,
+ AgentFormDraftService $drafts,
+ AgentFormDraftRateLimiter $rateLimiter,
+ ): ResponseFactory {
+ $validated = $request->validate([
+ 'definition' => ['required', 'array'],
+ ]);
+
+ $identifier = $request->user()
+ ? 'user:'.$request->user()->getAuthIdentifier()
+ : 'ip:'.request()->ip();
+ $rateLimiter->hit($identifier);
+
+ $created = $drafts->create($validated['definition']);
+
+ return Response::structured([
+ 'draft_token' => $created['token'],
+ 'draft' => $drafts->serialize($created['draft']),
+ 'next_steps' => [
+ 'Keep draft_token private; it grants access to this draft.',
+ 'Use patch_form_draft with expected_version for changes.',
+ 'Render a preview before asking the user to claim or publish the form.',
+ ],
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'definition' => $schema->object()
+ ->description('Form definition following opnform://schemas/agent-form-definition/v1. The server normalizes defaults, aliases, IDs, and visibility.')
+ ->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/CreateFormTool.php b/api/app/Mcp/Tools/CreateFormTool.php
new file mode 100644
index 000000000..a1acf18cf
--- /dev/null
+++ b/api/app/Mcp/Tools/CreateFormTool.php
@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('create_form')]
+#[Description('Create a form in an accessible writable workspace from the canonical definition. It is always saved as an unpublished draft. If the account has exactly one workspace, workspace_id may be omitted.')]
+#[IsOpenWorld(false)]
+class CreateFormTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'workspace_id' => ['nullable', 'integer', 'min:1'],
+ 'definition' => ['required', 'array'],
+ ]);
+
+ return Response::structured($forms->create(
+ $this->user($request),
+ $validated['workspace_id'] ?? null,
+ $validated['definition'],
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'workspace_id' => $schema->integer()->description('Required only when the account has multiple workspaces.')->min(1),
+ 'definition' => $schema->object()->description('Canonical OpnForm agent form definition v1.')->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/ExportSubmissionsTool.php b/api/app/Mcp/Tools/ExportSubmissionsTool.php
new file mode 100644
index 000000000..0ab3c13b8
--- /dev/null
+++ b/api/app/Mcp/Tools/ExportSubmissionsTool.php
@@ -0,0 +1,44 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpSubmissionService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('export_submissions')]
+#[Description('Queue a private CSV export for all submissions in an accessible form, or up to 1,000 selected submission IDs. Poll get_submission_export for its temporary download URL.')]
+#[IsOpenWorld(false)]
+class ExportSubmissionsTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpSubmissionService $submissions): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'submission_ids' => ['nullable', 'array', 'max:1000'],
+ 'submission_ids.*' => ['required', 'integer', 'min:1', 'distinct'],
+ ]);
+
+ return Response::structured($submissions->startExport(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['submission_ids'] ?? [],
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'submission_ids' => $schema->array()
+ ->description('Optional selected IDs. Omit to export all submissions.')
+ ->items($schema->integer()->min(1))
+ ->max(1000),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/GetAccountContextTool.php b/api/app/Mcp/Tools/GetAccountContextTool.php
new file mode 100644
index 000000000..3f3e18da5
--- /dev/null
+++ b/api/app/Mcp/Tools/GetAccountContextTool.php
@@ -0,0 +1,35 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('get_account_context')]
+#[Description('Confirm the connected OpnForm account and summarize its accessible workspaces. Use this before account-scoped work when the current context is unclear.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class GetAccountContextTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $user = $this->user($request);
+ $workspaces = $forms->listWorkspaces($user);
+
+ return Response::structured([
+ 'account' => [
+ 'id' => $user->id,
+ 'name' => $user->name,
+ 'email' => $user->email,
+ ],
+ 'workspaces' => $workspaces,
+ 'workspace_selection_required' => count($workspaces) > 1,
+ ]);
+ }
+}
diff --git a/api/app/Mcp/Tools/GetFormDraftTool.php b/api/app/Mcp/Tools/GetFormDraftTool.php
new file mode 100644
index 000000000..e2d70a964
--- /dev/null
+++ b/api/app/Mcp/Tools/GetFormDraftTool.php
@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('get_form_draft')]
+#[Description('Fetch the current canonical definition and version of a private guest draft. Use this after a version conflict or whenever the current state is uncertain.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class GetFormDraftTool extends GuestDraftMcpTool
+{
+ public function handle(Request $request, AgentFormDraftService $drafts): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'draft_token' => ['required', 'string', 'size:43'],
+ ]);
+
+ return Response::structured([
+ 'draft' => $drafts->serialize($drafts->get($validated['draft_token'])),
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'draft_token' => $schema->string()
+ ->description('Private capability token returned by create_form_draft.')
+ ->min(43)
+ ->max(43)
+ ->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/GetFormTool.php b/api/app/Mcp/Tools/GetFormTool.php
new file mode 100644
index 000000000..e658469a7
--- /dev/null
+++ b/api/app/Mcp/Tools/GetFormTool.php
@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('get_form')]
+#[Description('Fetch an accessible form as the canonical agent form definition. Use its revision value when calling update_form, publish_form, or trash_form.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class GetFormTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $validated = $request->validate(['form_id' => ['required', 'integer', 'min:1']]);
+ $form = $forms->form($this->user($request), $validated['form_id']);
+
+ return Response::structured(['form' => $forms->serializeForm($form)]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return ['form_id' => $schema->integer()->min(1)->required()];
+ }
+}
diff --git a/api/app/Mcp/Tools/GetSubmissionExportTool.php b/api/app/Mcp/Tools/GetSubmissionExportTool.php
new file mode 100644
index 000000000..76f1a6895
--- /dev/null
+++ b/api/app/Mcp/Tools/GetSubmissionExportTool.php
@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpSubmissionService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('get_submission_export')]
+#[Description('Check a queued submission export. When completed, returns a temporary private CSV download URL and its expiration time.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class GetSubmissionExportTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpSubmissionService $submissions): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'job_id' => ['required', 'uuid'],
+ ]);
+
+ return Response::structured($submissions->exportStatus(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['job_id'],
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'job_id' => $schema->string()->description('Export job UUID returned by export_submissions.')->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/GetSubmissionStatsTool.php b/api/app/Mcp/Tools/GetSubmissionStatsTool.php
new file mode 100644
index 000000000..ac09e3e36
--- /dev/null
+++ b/api/app/Mcp/Tools/GetSubmissionStatsTool.php
@@ -0,0 +1,49 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpSubmissionService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Illuminate\Validation\Rule;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('get_submission_stats')]
+#[Description('Analyze submissions for an accessible form using the same bounded field summaries available in OpnForm. Returns all-time views/completion overview plus a status/date-filtered summary.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class GetSubmissionStatsTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpSubmissionService $submissions): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'status' => ['nullable', Rule::in(['all', 'completed', 'partial'])],
+ 'date_from' => ['nullable', 'date', Rule::when($request->filled('date_to'), 'before_or_equal:date_to')],
+ 'date_to' => ['nullable', 'date', Rule::when($request->filled('date_from'), 'after_or_equal:date_from')],
+ ]);
+
+ return Response::structured($submissions->stats(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['status'] ?? 'completed',
+ $validated['date_from'] ?? null,
+ $validated['date_to'] ?? null,
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'status' => $schema->string()->enum(['all', 'completed', 'partial'])->default('completed'),
+ 'date_from' => $schema->string()->description('Inclusive ISO 8601 date.'),
+ 'date_to' => $schema->string()->description('Inclusive ISO 8601 date.'),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/GetSubmissionTool.php b/api/app/Mcp/Tools/GetSubmissionTool.php
new file mode 100644
index 000000000..38e464812
--- /dev/null
+++ b/api/app/Mcp/Tools/GetSubmissionTool.php
@@ -0,0 +1,44 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpSubmissionService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('get_submission')]
+#[Description('Read one submission from an accessible form, with response values labeled by form field. This tool never changes the submission.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class GetSubmissionTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpSubmissionService $submissions): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'submission_id' => ['required', 'integer', 'min:1'],
+ ]);
+
+ return Response::structured([
+ 'submission' => $submissions->get(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['submission_id'],
+ ),
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'submission_id' => $schema->integer()->min(1)->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/GetWorkspaceTool.php b/api/app/Mcp/Tools/GetWorkspaceTool.php
new file mode 100644
index 000000000..833f4d67b
--- /dev/null
+++ b/api/app/Mcp/Tools/GetWorkspaceTool.php
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('get_workspace')]
+#[Description('Read one accessible OpnForm workspace and the connected account role. This integration never changes workspace settings or members.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class GetWorkspaceTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $validated = $request->validate(['workspace_id' => ['required', 'integer', 'min:1']]);
+
+ return Response::structured([
+ 'workspace' => $forms->serializeWorkspace($forms->workspace($this->user($request), $validated['workspace_id'])),
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return ['workspace_id' => $schema->integer()->min(1)->required()];
+ }
+}
diff --git a/api/app/Mcp/Tools/GuestDraftMcpTool.php b/api/app/Mcp/Tools/GuestDraftMcpTool.php
new file mode 100644
index 000000000..4dfab4fed
--- /dev/null
+++ b/api/app/Mcp/Tools/GuestDraftMcpTool.php
@@ -0,0 +1,13 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Support\Mcp\McpAvailability;
+
+abstract class GuestDraftMcpTool extends GuestMcpTool
+{
+ public function shouldRegister(McpAvailability $availability): bool
+ {
+ return $availability->guestDraftsEnabled();
+ }
+}
diff --git a/api/app/Mcp/Tools/GuestMcpTool.php b/api/app/Mcp/Tools/GuestMcpTool.php
new file mode 100644
index 000000000..1820d0a10
--- /dev/null
+++ b/api/app/Mcp/Tools/GuestMcpTool.php
@@ -0,0 +1,16 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+abstract class GuestMcpTool extends McpTool
+{
+ /**
+ * @return list<array{type: string}>
+ */
+ protected function securitySchemes(): array
+ {
+ return [
+ ['type' => 'noauth'],
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/ListFormsTool.php b/api/app/Mcp/Tools/ListFormsTool.php
new file mode 100644
index 000000000..323def33b
--- /dev/null
+++ b/api/app/Mcp/Tools/ListFormsTool.php
@@ -0,0 +1,53 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Models\Forms\Form;
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Illuminate\Validation\Rule;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('list_forms')]
+#[Description('List forms accessible to the connected account. Filter by workspace, title, or visibility; results are paginated and exclude trashed forms.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class ListFormsTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'workspace_id' => ['nullable', 'integer', 'min:1'],
+ 'search' => ['nullable', 'string', 'max:255'],
+ 'visibility' => ['nullable', Rule::in(Form::VISIBILITY)],
+ 'page' => ['nullable', 'integer', 'min:1'],
+ 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
+ ]);
+
+ return Response::structured($forms->listForms(
+ $this->user($request),
+ $validated['workspace_id'] ?? null,
+ $validated['search'] ?? null,
+ $validated['visibility'] ?? null,
+ $validated['page'] ?? 1,
+ $validated['per_page'] ?? 20,
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'workspace_id' => $schema->integer()->min(1),
+ 'search' => $schema->string()->max(255),
+ 'visibility' => $schema->string()->enum(Form::VISIBILITY),
+ 'page' => $schema->integer()->min(1)->default(1),
+ 'per_page' => $schema->integer()->min(1)->max(100)->default(20),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/ListSubmissionsTool.php b/api/app/Mcp/Tools/ListSubmissionsTool.php
new file mode 100644
index 000000000..729f31618
--- /dev/null
+++ b/api/app/Mcp/Tools/ListSubmissionsTool.php
@@ -0,0 +1,58 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpSubmissionService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Illuminate\Validation\Rule;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('list_submissions')]
+#[Description('List and search submissions for an accessible form. Search matches response values, not field names. Filter by completed/partial status and date; results are paginated.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class ListSubmissionsTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpSubmissionService $submissions): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'search' => ['nullable', 'string', 'max:255'],
+ 'status' => ['nullable', Rule::in(['all', 'completed', 'partial'])],
+ 'date_from' => ['nullable', 'date', Rule::when($request->filled('date_to'), 'before_or_equal:date_to')],
+ 'date_to' => ['nullable', 'date', Rule::when($request->filled('date_from'), 'after_or_equal:date_from')],
+ 'page' => ['nullable', 'integer', 'min:1'],
+ 'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
+ ]);
+
+ return Response::structured($submissions->list(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['search'] ?? null,
+ $validated['status'] ?? 'completed',
+ $validated['date_from'] ?? null,
+ $validated['date_to'] ?? null,
+ $validated['page'] ?? 1,
+ $validated['per_page'] ?? 50,
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'search' => $schema->string()->max(255),
+ 'status' => $schema->string()->enum(['all', 'completed', 'partial'])->default('completed'),
+ 'date_from' => $schema->string()->description('Inclusive ISO 8601 date.'),
+ 'date_to' => $schema->string()->description('Inclusive ISO 8601 date.'),
+ 'page' => $schema->integer()->min(1)->default(1),
+ 'per_page' => $schema->integer()->min(1)->max(100)->default(50),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/ListWorkspacesTool.php b/api/app/Mcp/Tools/ListWorkspacesTool.php
new file mode 100644
index 000000000..3e32c13b7
--- /dev/null
+++ b/api/app/Mcp/Tools/ListWorkspacesTool.php
@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('list_workspaces')]
+#[Description('List workspaces available to the connected account, including its role and whether forms can be changed. Workspace management is intentionally not available.')]
+#[IsReadOnly]
+#[IsOpenWorld(false)]
+class ListWorkspacesTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ return Response::structured([
+ 'workspaces' => $forms->listWorkspaces($this->user($request)),
+ ]);
+ }
+}
diff --git a/api/app/Mcp/Tools/McpTool.php b/api/app/Mcp/Tools/McpTool.php
new file mode 100644
index 000000000..dfe61f422
--- /dev/null
+++ b/api/app/Mcp/Tools/McpTool.php
@@ -0,0 +1,24 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use Laravel\Mcp\Server\Tool;
+
+abstract class McpTool extends Tool
+{
+ /**
+ * @return list<array{type: string, scopes?: list<string>}>
+ */
+ abstract protected function securitySchemes(): array;
+
+ /**
+ * @return array<string, mixed>
+ */
+ public function toArray(): array
+ {
+ return [
+ ...parent::toArray(),
+ 'securitySchemes' => $this->securitySchemes(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php b/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
new file mode 100644
index 000000000..fb93f645f
--- /dev/null
+++ b/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('open_form_draft_in_editor')]
+#[Description('Create a reusable OpnForm editor link that remains valid until the guest draft expires.')]
+#[IsOpenWorld]
+class OpenFormDraftInEditorTool extends GuestDraftMcpTool
+{
+ public function handle(Request $request, AgentFormDraftService $drafts): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'draft_token' => ['required', 'string', 'size:43'],
+ ]);
+
+ return Response::structured($drafts->issueEditorHandoff($validated['draft_token']));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'draft_token' => $schema->string()->min(43)->max(43)->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/PatchFormDraftTool.php b/api/app/Mcp/Tools/PatchFormDraftTool.php
new file mode 100644
index 000000000..cfe55d517
--- /dev/null
+++ b/api/app/Mcp/Tools/PatchFormDraftTool.php
@@ -0,0 +1,71 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('patch_form_draft')]
+#[Description('Apply validated semantic operations to a private draft. Requires expected_version, so concurrent agent or editor changes cannot be silently overwritten. Supported ops: set_form_values, add_block, update_block, remove_block, move_block. Before changing presentation_style, fields, layout, or media, read opnform://reference/form-fields/v1; focused mode derives one step per block and media belongs in the block image property.')]
+#[IsOpenWorld(false)]
+class PatchFormDraftTool extends GuestDraftMcpTool
+{
+ public function handle(Request $request, AgentFormDraftService $drafts): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'draft_token' => ['required', 'string', 'size:43'],
+ 'expected_version' => ['required', 'integer', 'min:1'],
+ 'operations' => ['required', 'array', 'min:1', 'max:100'],
+ 'operations.*' => ['required', 'array'],
+ 'operations.*.op' => ['required', 'string'],
+ ]);
+
+ $draft = $drafts->patch(
+ $validated['draft_token'],
+ $validated['expected_version'],
+ $validated['operations'],
+ );
+
+ return Response::structured([
+ 'draft' => $drafts->serialize($draft),
+ 'next_step' => 'Render or refresh the preview before presenting the result to the user.',
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'draft_token' => $schema->string()
+ ->description('Private capability token returned by create_form_draft.')
+ ->min(43)
+ ->max(43)
+ ->required(),
+ 'expected_version' => $schema->integer()
+ ->description('Version returned by the most recent create, get, or patch call.')
+ ->min(1)
+ ->required(),
+ 'operations' => $schema->array()
+ ->description('Ordered semantic patch operations. Select blocks by block_id when possible; index is supported. See the tool description and schema resource for operation fields.')
+ ->items($schema->object([
+ 'op' => $schema->string()
+ ->enum(['set_form_values', 'add_block', 'update_block', 'remove_block', 'move_block'])
+ ->required(),
+ 'values' => $schema->object(),
+ 'block' => $schema->object(),
+ 'patch' => $schema->object(),
+ 'block_id' => $schema->string(),
+ 'index' => $schema->integer()->min(0),
+ 'to_index' => $schema->integer()->min(0),
+ ]))
+ ->min(1)
+ ->max(100)
+ ->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/PreviewFormDraftTool.php b/api/app/Mcp/Tools/PreviewFormDraftTool.php
new file mode 100644
index 000000000..f06ff8e90
--- /dev/null
+++ b/api/app/Mcp/Tools/PreviewFormDraftTool.php
@@ -0,0 +1,48 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Mcp\Apps\FormDraftPreviewApp;
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Attributes\RendersApp;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('preview_form_draft')]
+#[Description('Render the current guest draft, return a browser preview valid for one hour, and create a reusable editor link that remains valid for the seven-day guest draft lifetime. Call this tool again whenever a fresh preview link is needed.')]
+#[RendersApp(resource: FormDraftPreviewApp::class)]
+#[IsOpenWorld]
+class PreviewFormDraftTool extends GuestDraftMcpTool
+{
+ public function handle(Request $request, AgentFormDraftService $drafts): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'draft_token' => ['required', 'string', 'size:43'],
+ ]);
+ $draft = $drafts->get($validated['draft_token']);
+ $handoff = $drafts->issueEditorHandoff($validated['draft_token']);
+
+ return Response::structured([
+ 'draft' => $drafts->serialize($draft),
+ 'preview_url' => $drafts->previewUrl($draft),
+ 'editor_url' => $handoff['editor_url'],
+ 'editor_link_expires_at' => $handoff['expires_at'],
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'draft_token' => $schema->string()
+ ->description('Private capability token returned by create_form_draft.')
+ ->min(43)
+ ->max(43)
+ ->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/PublishFormTool.php b/api/app/Mcp/Tools/PublishFormTool.php
new file mode 100644
index 000000000..0e79907b3
--- /dev/null
+++ b/api/app/Mcp/Tools/PublishFormTool.php
@@ -0,0 +1,43 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('publish_form')]
+#[Description('Publish an accessible writable form at its current revision. Call only after showing the result or preview and receiving explicit confirmation from the user.')]
+#[IsOpenWorld]
+class PublishFormTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'expected_revision' => ['required', 'string', 'size:64'],
+ 'confirm_publish' => ['required', 'boolean'],
+ ]);
+
+ return Response::structured($forms->publish(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['expected_revision'],
+ $validated['confirm_publish'],
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'expected_revision' => $schema->string()->description('Exact 64-character revision returned by get_form.')->min(64)->max(64)->required(),
+ 'confirm_publish' => $schema->boolean()->description('True only after the user explicitly confirms publication.')->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/TrashFormTool.php b/api/app/Mcp/Tools/TrashFormTool.php
new file mode 100644
index 000000000..2e1af6aca
--- /dev/null
+++ b/api/app/Mcp/Tools/TrashFormTool.php
@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('trash_form')]
+#[Description('Move an accessible writable form at its current revision to soft-delete trash. Call only after explicit user confirmation. Restore and permanent deletion are intentionally not exposed.')]
+#[IsDestructive]
+#[IsOpenWorld(false)]
+class TrashFormTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'expected_revision' => ['required', 'string', 'size:64'],
+ 'confirm_trash' => ['required', 'boolean'],
+ ]);
+
+ return Response::structured($forms->trash(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['expected_revision'],
+ $validated['confirm_trash'],
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'expected_revision' => $schema->string()->description('Exact 64-character revision returned by get_form.')->min(64)->max(64)->required(),
+ 'confirm_trash' => $schema->boolean()->description('True only after the user explicitly confirms moving the form to trash.')->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/UpdateFormTool.php b/api/app/Mcp/Tools/UpdateFormTool.php
new file mode 100644
index 000000000..c24cbc607
--- /dev/null
+++ b/api/app/Mcp/Tools/UpdateFormTool.php
@@ -0,0 +1,43 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\McpFormManagementService;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+
+#[Name('update_form')]
+#[Description('Replace the editable definition of an accessible form. Requires the revision value returned by get_form to prevent silent concurrent overwrites. This tool cannot publish or trash a form.')]
+#[IsOpenWorld(false)]
+class UpdateFormTool extends AuthenticatedMcpTool
+{
+ public function handle(Request $request, McpFormManagementService $forms): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'form_id' => ['required', 'integer', 'min:1'],
+ 'expected_revision' => ['required', 'string', 'size:64'],
+ 'definition' => ['required', 'array'],
+ ]);
+
+ return Response::structured($forms->update(
+ $this->user($request),
+ $validated['form_id'],
+ $validated['expected_revision'],
+ $validated['definition'],
+ ));
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'form_id' => $schema->integer()->min(1)->required(),
+ 'expected_revision' => $schema->string()->description('Exact 64-character revision returned by get_form.')->min(64)->max(64)->required(),
+ 'definition' => $schema->object()->description('Complete canonical OpnForm agent form definition v1.')->required(),
+ ];
+ }
+}
diff --git a/api/app/Mcp/Tools/ValidateFormDefinitionTool.php b/api/app/Mcp/Tools/ValidateFormDefinitionTool.php
new file mode 100644
index 000000000..75bd0eb72
--- /dev/null
+++ b/api/app/Mcp/Tools/ValidateFormDefinitionTool.php
@@ -0,0 +1,55 @@
+<?php
+
+namespace App\Mcp\Tools;
+
+use App\Service\Forms\AgentFormDefinition;
+use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Laravel\Mcp\Request;
+use Laravel\Mcp\Response;
+use Laravel\Mcp\ResponseFactory;
+use Laravel\Mcp\Server\Attributes\Description;
+use Laravel\Mcp\Server\Attributes\Name;
+use Laravel\Mcp\Server\Tools\Annotations\IsIdempotent;
+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;
+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
+
+#[Name('validate_form_definition')]
+#[Description('Normalize and validate an OpnForm agent form definition without storing it. Returns the canonical definition with defaults, stable block IDs, sanitized content, and normalized aliases.')]
+#[IsReadOnly]
+#[IsIdempotent]
+#[IsOpenWorld(false)]
+class ValidateFormDefinitionTool extends GuestMcpTool
+{
+ public function handle(Request $request, AgentFormDefinition $formDefinition): ResponseFactory
+ {
+ $validated = $request->validate([
+ 'definition' => ['required', 'array'],
+ ]);
+
+ $definition = $formDefinition->normalizeAndValidate($validated['definition']);
+
+ return Response::structured([
+ 'valid' => true,
+ 'schema_version' => AgentFormDefinition::SCHEMA_VERSION,
+ 'definition' => $definition,
+ ]);
+ }
+
+ public function schema(JsonSchema $schema): array
+ {
+ return [
+ 'definition' => $schema->object()
+ ->description('Form definition following opnform://schemas/agent-form-definition/v1. IDs and optional defaults may be omitted.')
+ ->required(),
+ ];
+ }
+
+ public function outputSchema(JsonSchema $schema): array
+ {
+ return [
+ 'valid' => $schema->boolean()->required(),
+ 'schema_version' => $schema->integer()->required(),
+ 'definition' => $schema->object()->required(),
+ ];
+ }
+}
diff --git a/api/app/Models/Forms/AgentFormDraft.php b/api/app/Models/Forms/AgentFormDraft.php
new file mode 100644
index 000000000..86b00d355
--- /dev/null
+++ b/api/app/Models/Forms/AgentFormDraft.php
@@ -0,0 +1,64 @@
+<?php
+
+namespace App\Models\Forms;
+
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+
+class AgentFormDraft extends Model
+{
+ public const STATUS_ACTIVE = 'active';
+
+ public const STATUS_CLAIMED = 'claimed';
+
+ protected $fillable = [
+ 'token_hash',
+ 'definition',
+ 'schema_version',
+ 'version',
+ 'status',
+ 'claimed_form_id',
+ 'claim_receipt_hash',
+ 'claimed_at',
+ 'editor_session_hash',
+ 'editor_session_expires_at',
+ 'expires_at',
+ ];
+
+ protected $hidden = [
+ 'token_hash',
+ 'claim_receipt_hash',
+ 'editor_session_hash',
+ ];
+
+ protected function casts(): array
+ {
+ return [
+ 'definition' => 'array',
+ 'schema_version' => 'integer',
+ 'version' => 'integer',
+ 'claimed_form_id' => 'integer',
+ 'claimed_at' => 'datetime',
+ 'editor_session_expires_at' => 'datetime',
+ 'expires_at' => 'datetime',
+ ];
+ }
+
+ public function scopeActive(Builder $query): Builder
+ {
+ return $query
+ ->where('status', self::STATUS_ACTIVE)
+ ->where('expires_at', '>', now());
+ }
+
+ public function isAvailable(): bool
+ {
+ return $this->status === self::STATUS_ACTIVE && $this->expires_at->isFuture();
+ }
+
+ public function editorHandoffs(): HasMany
+ {
+ return $this->hasMany(AgentFormDraftHandoff::class);
+ }
+}
diff --git a/api/app/Models/Forms/AgentFormDraftHandoff.php b/api/app/Models/Forms/AgentFormDraftHandoff.php
new file mode 100644
index 000000000..c628ff3ad
--- /dev/null
+++ b/api/app/Models/Forms/AgentFormDraftHandoff.php
@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Models\Forms;
+
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+
+class AgentFormDraftHandoff extends Model
+{
+ protected $fillable = [
+ 'agent_form_draft_id',
+ 'token_hash',
+ 'last_used_at',
+ 'expires_at',
+ ];
+
+ protected $hidden = [
+ 'token_hash',
+ ];
+
+ protected function casts(): array
+ {
+ return [
+ 'last_used_at' => 'datetime',
+ 'expires_at' => 'datetime',
+ ];
+ }
+
+ public function draft(): BelongsTo
+ {
+ return $this->belongsTo(AgentFormDraft::class, 'agent_form_draft_id');
+ }
+}
diff --git a/api/app/Providers/AppServiceProvider.php b/api/app/Providers/AppServiceProvider.php
index 3b2c4a4ed..4d37a0137 100644
--- a/api/app/Providers/AppServiceProvider.php
+++ b/api/app/Providers/AppServiceProvider.php
@@ -129,4 +129,5 @@ class AppServiceProvider extends ServiceProvider
throw new RuntimeException('Unsafe testing sqlite configuration detected.');
}
+
}
diff --git a/api/app/Providers/AuthServiceProvider.php b/api/app/Providers/AuthServiceProvider.php
index 04c2c89c1..5ca7824c0 100644
--- a/api/app/Providers/AuthServiceProvider.php
+++ b/api/app/Providers/AuthServiceProvider.php
@@ -16,6 +16,7 @@ use App\Policies\PersonalAccessTokenPolicy;
use App\Policies\TemplatePolicy;
use App\Policies\WorkspacePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
+use Illuminate\Support\Facades\Gate;
use Laravel\Sanctum\PersonalAccessToken;
class AuthServiceProvider extends ServiceProvider
@@ -43,8 +44,13 @@ class AuthServiceProvider extends ServiceProvider
*/
public function boot()
{
- \Illuminate\Support\Facades\Gate::define('viewMailcoach', function ($user = null) {
+ Gate::define('viewMailcoach', function ($user = null) {
return optional($user)->admin;
});
+
+ Gate::define('manage-instance-settings', function ($user = null) {
+ return config('app.self_hosted')
+ && $user?->workspaces()->wherePivot('role', \App\Models\User::ROLE_ADMIN)->exists();
+ });
}
}
diff --git a/api/app/Providers/OAuthServiceProvider.php b/api/app/Providers/OAuthServiceProvider.php
new file mode 100644
index 000000000..9534cb8e5
--- /dev/null
+++ b/api/app/Providers/OAuthServiceProvider.php
@@ -0,0 +1,43 @@
+<?php
+
+namespace App\Providers;
+
+use App\Service\OAuth\McpPassportClientRepository;
+use Illuminate\Support\Facades\Route;
+use Illuminate\Support\ServiceProvider;
+use Laravel\Passport\ClientRepository;
+use Laravel\Passport\Passport;
+
+final class OAuthServiceProvider extends ServiceProvider
+{
+ public function register(): void
+ {
+ Passport::ignoreRoutes();
+
+ // Laravel MCP currently resolves Passport's concrete repository from
+ // the container. This adapter keeps dynamic PKCE registration working
+ // with Passport 12 until the project can upgrade to Passport 13.
+ $this->app->singleton(ClientRepository::class, function () {
+ $personalAccessClient = config('passport.personal_access_client', []);
+
+ return new McpPassportClientRepository(
+ $personalAccessClient['id'] ?? null,
+ $personalAccessClient['secret'] ?? null
+ );
+ });
+ }
+
+ public function boot(): void
+ {
+ if (! config('oauth.enabled', false)) {
+ return;
+ }
+
+ Passport::authorizationView('oauth.authorize');
+ Passport::tokensCan(config('oauth.scopes', []));
+ Passport::tokensExpireIn(now()->addMinutes(max(1, (int) config('oauth.access_token_ttl', 10080))));
+ Passport::refreshTokensExpireIn(now()->addDays(max(1, (int) config('oauth.refresh_token_ttl_days', 30))));
+
+ Route::middleware('mcp.enabled')->group(base_path('routes/oauth.php'));
+ }
+}
diff --git a/api/app/Providers/RouteServiceProvider.php b/api/app/Providers/RouteServiceProvider.php
index 26952e914..401f9e10e 100644
--- a/api/app/Providers/RouteServiceProvider.php
+++ b/api/app/Providers/RouteServiceProvider.php
@@ -69,11 +69,6 @@ class RouteServiceProvider extends ServiceProvider
});
});
- // Rate limit for summary endpoints: 30 requests per minute per user
- RateLimiter::for('summary', function (Request $request) {
- return Limit::perMinute(30)->by($request->user()?->id ?: $request->ip());
- });
-
// Export endpoints use dedicated buckets so long-running CSV exports
// are not blocked by the general API rate limit.
RateLimiter::for('export', function (Request $request) {
@@ -109,6 +104,23 @@ class RouteServiceProvider extends ServiceProvider
->by('public-uploads:hour:' . $key),
];
});
+
+ RateLimiter::for('mcp', function (Request $request) {
+ $identifier = $request->user()
+ ? 'user:'.$request->user()->getAuthIdentifier()
+ : 'ip:'.$request->ip();
+
+ return [
+ Limit::perMinute(max(1, config('opnform.mcp.rate_limit.per_minute', 120)))
+ ->by('mcp:minute:'.$identifier),
+ Limit::perHour(max(1, config('opnform.mcp.rate_limit.per_hour', 3000)))
+ ->by('mcp:hour:'.$identifier),
+ ];
+ });
+
+ RateLimiter::for('mcp-oauth-registration', function (Request $request) {
+ return Limit::perHour(20)->by('mcp-oauth-registration:'.$request->ip());
+ });
}
protected function registerGlobalRouteParamConstraints()
diff --git a/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
index e5d581e36..efe378f42 100644
--- a/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
+++ b/api/app/Rules/PropertyValidators/PaymentPropertyValidator.php
@@ -87,6 +87,13 @@ class PaymentPropertyValidator implements PropertyValidatorInterface
return $errors;
}
+ // Guest form definitions have no workspace security boundary yet. Defer
+ // provider lookup until the draft is claimed so validation cannot be
+ // used to enumerate OAuth provider IDs from other accounts.
+ if ($this->workspace === null) {
+ return $errors;
+ }
+
try {
$provider = OAuthProvider::find($property['stripe_account_id']);
if ($provider === null) {
@@ -94,8 +101,7 @@ class PaymentPropertyValidator implements PropertyValidatorInterface
return $errors;
}
- // Check if the provider is associated with the workspace (if workspace is provided)
- if ($this->workspace && !$this->workspace->hasProvider($provider->id)) {
+ if (!$this->workspace->hasProvider($provider->id)) {
Log::error('Attempted to use Stripe account not associated with the workspace', [
'stripe_account_id' => $property['stripe_account_id'],
'provider_id' => $provider->id,
diff --git a/api/app/Rules/PublicMediaUrlRule.php b/api/app/Rules/PublicMediaUrlRule.php
new file mode 100644
index 000000000..9f83b0ff2
--- /dev/null
+++ b/api/app/Rules/PublicMediaUrlRule.php
@@ -0,0 +1,109 @@
+<?php
+
+namespace App\Rules;
+
+use Closure;
+use Illuminate\Contracts\Validation\ValidationRule;
+
+class PublicMediaUrlRule implements ValidationRule
+{
+ private const PRIVATE_HOST_SUFFIXES = [
+ 'home',
+ 'internal',
+ 'lan',
+ 'local',
+ 'localhost',
+ 'test',
+ ];
+
+ private const TEMPORARY_HOST_SUFFIXES = [
+ 'loca.lt',
+ 'localtunnel.me',
+ 'ngrok-free.app',
+ 'ngrok.io',
+ 'trycloudflare.com',
+ ];
+
+ private const TEMPORARY_QUERY_PARAMETERS = [
+ 'expires',
+ 'signature',
+ 'x-amz-expires',
+ 'x-amz-signature',
+ 'x-goog-expires',
+ 'x-goog-signature',
+ ];
+
+ public function validate(string $attribute, mixed $value, Closure $fail): void
+ {
+ if (! is_string($value) || filter_var($value, FILTER_VALIDATE_URL) === false) {
+ $fail('The :attribute must be a valid public HTTPS URL.');
+
+ return;
+ }
+
+ if (strtolower((string) parse_url($value, PHP_URL_SCHEME)) !== 'https') {
+ $fail('The :attribute must use HTTPS.');
+
+ return;
+ }
+
+ if (parse_url($value, PHP_URL_USER) !== null || parse_url($value, PHP_URL_PASS) !== null) {
+ $fail('The :attribute cannot contain embedded credentials.');
+
+ return;
+ }
+
+ $host = strtolower(rtrim(trim((string) parse_url($value, PHP_URL_HOST), '[]'), '.'));
+ if ($host === '' || $this->isPrivateHost($host)) {
+ $fail('The :attribute must use a public host.');
+
+ return;
+ }
+
+ if ($this->hasSuffix($host, self::TEMPORARY_HOST_SUFFIXES)) {
+ $fail('The :attribute cannot use a temporary tunnel host.');
+
+ return;
+ }
+
+ parse_str((string) parse_url($value, PHP_URL_QUERY), $query);
+ $queryKeys = array_map(
+ fn (string|int $key): string => strtolower((string) $key),
+ array_keys($query),
+ );
+ if (array_intersect($queryKeys, self::TEMPORARY_QUERY_PARAMETERS) !== []) {
+ $fail('The :attribute cannot use an expiring or signed URL.');
+ }
+ }
+
+ private function isPrivateHost(string $host): bool
+ {
+ if ($host === 'localhost' || $this->hasSuffix($host, self::PRIVATE_HOST_SUFFIXES)) {
+ return true;
+ }
+
+ if (! filter_var($host, FILTER_VALIDATE_IP)) {
+ return false;
+ }
+
+ return filter_var(
+ $host,
+ FILTER_VALIDATE_IP,
+ FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE,
+ ) === false;
+ }
+
+ /**
+ * @param array<int, string> $suffixes
+ */
+ private function hasSuffix(string $host, array $suffixes): bool
+ {
+ foreach ($suffixes as $suffix) {
+ if ($host === $suffix || str_ends_with($host, '.'.$suffix)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/api/app/Service/Forms/AgentFormDefinition.php b/api/app/Service/Forms/AgentFormDefinition.php
new file mode 100644
index 000000000..51f1aadd0
--- /dev/null
+++ b/api/app/Service/Forms/AgentFormDefinition.php
@@ -0,0 +1,412 @@
+<?php
+
+namespace App\Service\Forms;
+
+use App\Models\Forms\Form;
+use App\Models\Workspace;
+use App\Rules\ComputedVariablesRule;
+use App\Rules\CssOnlyRule;
+use App\Rules\FormPropertiesRule;
+use App\Rules\PublicMediaUrlRule;
+use App\Service\Forms\AgentFormFieldCatalog as FieldCatalog;
+use Illuminate\Support\Arr;
+use Illuminate\Support\Facades\Validator;
+use Illuminate\Validation\Rule;
+use Illuminate\Validation\ValidationException;
+use JsonException;
+use Stevebauman\Purify\Facades\Purify;
+
+class AgentFormDefinition
+{
+ public const SCHEMA_VERSION = 1;
+
+ public const MAX_DEFINITION_BYTES = 1_000_000;
+
+ private const ALLOWED_TOP_LEVEL_KEYS = [
+ 'schema_version',
+ 'title',
+ 'visibility',
+ 'properties',
+ 'computed_variables',
+ 'language',
+ 'font_family',
+ 'theme',
+ 'presentation_style',
+ 'width',
+ 'size',
+ 'layout_rtl',
+ 'border_radius',
+ 'dark_mode',
+ 'color',
+ 'uppercase_labels',
+ 'no_branding',
+ 'transparent_background',
+ 'translations',
+ 'cover_picture',
+ 'cover_settings',
+ 'logo_picture',
+ 'custom_code',
+ 'custom_css',
+ 'submit_button_text',
+ 're_fillable',
+ 're_fill_button_text',
+ 'submitted_text',
+ 'redirect_url',
+ 'max_submissions_count',
+ 'max_submissions_reached_text',
+ 'editable_submissions',
+ 'editable_submissions_button_text',
+ 'confetti_on_submission',
+ 'show_progress_bar',
+ 'auto_save',
+ 'auto_focus',
+ 'enable_partial_submissions',
+ 'enable_ip_tracking',
+ 'can_be_indexed',
+ 'use_captcha',
+ 'captcha_provider',
+ 'seo_meta',
+ 'settings',
+ 'analytics',
+ ];
+
+ public function __construct(private readonly FormDataNormalizer $normalizer)
+ {
+ }
+
+ public function normalizeAndValidate(array $definition, ?Workspace $workspace = null): array
+ {
+ $definition = $this->migrate($definition);
+ $definition = array_replace($this->defaults(), $definition);
+ $definition = $this->normalizeAliases($definition);
+ $definition = $this->normalizer->normalize($definition, backfillPropertyIds: true);
+ $definition['properties'] = collect($definition['properties'])->map(function ($property) {
+ if (! is_array($property)) {
+ return $property;
+ }
+
+ $property = array_replace([
+ 'help' => null,
+ 'hidden' => false,
+ 'required' => false,
+ 'placeholder' => null,
+ 'width' => 'full',
+ ], $property);
+
+ if (($property['type'] ?? null) === 'nf-text' && isset($property['content'])) {
+ $property['content'] = Purify::clean((string) $property['content']);
+ }
+
+ return $property;
+ })->values()->all();
+
+ $this->validate($definition, $workspace);
+
+ return Arr::only($definition, self::ALLOWED_TOP_LEVEL_KEYS);
+ }
+
+ public function validate(array $definition, ?Workspace $workspace = null): void
+ {
+ $unknownKeys = array_values(array_diff(array_keys($definition), self::ALLOWED_TOP_LEVEL_KEYS));
+
+ if ($unknownKeys !== []) {
+ throw ValidationException::withMessages([
+ 'definition' => ['Unknown top-level keys: '.implode(', ', $unknownKeys).'.'],
+ ]);
+ }
+
+ try {
+ $encodedDefinition = json_encode($definition, JSON_THROW_ON_ERROR);
+ } catch (JsonException) {
+ throw ValidationException::withMessages([
+ 'definition' => ['The form definition must contain valid JSON values.'],
+ ]);
+ }
+
+ if (strlen($encodedDefinition) > self::MAX_DEFINITION_BYTES) {
+ throw ValidationException::withMessages([
+ 'definition' => ['The form definition must not exceed 1 MB.'],
+ ]);
+ }
+
+ $propertyIds = collect($definition['properties'] ?? [])
+ ->pluck('id')
+ ->filter(fn ($id) => is_string($id) && $id !== '');
+
+ if ($propertyIds->duplicates()->isNotEmpty()) {
+ throw ValidationException::withMessages([
+ 'properties' => ['Every form block must have a unique id.'],
+ ]);
+ }
+
+ Validator::make($definition, [
+ 'schema_version' => ['required', 'integer', Rule::in([self::SCHEMA_VERSION])],
+ 'title' => ['required', 'string', 'max:255'],
+ 'visibility' => ['required', Rule::in(Form::VISIBILITY)],
+ 'properties' => ['required', 'array', 'min:1', 'max:500', new FormPropertiesRule($workspace)],
+ 'properties.*.id' => ['required', 'string', 'max:255'],
+ 'properties.*.name' => ['required', 'string', 'max:500'],
+ 'properties.*.type' => ['required', Rule::in(FieldCatalog::types())],
+ 'properties.*.help' => ['nullable', 'string'],
+ 'properties.*.image.url' => ['nullable', new PublicMediaUrlRule()],
+ 'computed_variables' => ['nullable', 'array', new ComputedVariablesRule()],
+ 'language' => ['required', Rule::in(Form::LANGUAGES)],
+ 'font_family' => ['nullable', 'string'],
+ 'theme' => ['required', Rule::in(Form::THEMES)],
+ 'presentation_style' => ['required', Rule::in(Form::PRESENTATION_STYLES)],
+ 'width' => ['required', Rule::in(Form::WIDTHS)],
+ 'size' => ['required', Rule::in(Form::SIZES)],
+ 'layout_rtl' => ['required', 'boolean'],
+ 'border_radius' => ['required', Rule::in(Form::BORDER_RADIUS)],
+ 'dark_mode' => ['required', Rule::in(Form::DARK_MODE_VALUES)],
+ 'color' => ['required', 'string'],
+ 'uppercase_labels' => ['required', 'boolean'],
+ 'no_branding' => ['required', 'boolean'],
+ 'transparent_background' => ['required', 'boolean'],
+ 'translations' => ['nullable', 'array'],
+ 'cover_picture' => ['nullable', new PublicMediaUrlRule()],
+ 'cover_settings' => ['nullable', 'array'],
+ 'cover_settings.focal_point' => ['sometimes', 'nullable', 'array'],
+ 'cover_settings.focal_point.x' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:100'],
+ 'cover_settings.focal_point.y' => ['sometimes', 'nullable', 'numeric', 'min:0', 'max:100'],
+ 'cover_settings.brightness' => ['sometimes', 'nullable', 'integer', 'min:-100', 'max:100'],
+ 'logo_picture' => ['nullable', new PublicMediaUrlRule()],
+ 'custom_code' => ['nullable', 'string'],
+ 'custom_css' => ['nullable', 'string', new CssOnlyRule()],
+ 'submit_button_text' => ['nullable', 'string', 'max:50'],
+ 're_fillable' => ['required', 'boolean'],
+ 're_fill_button_text' => ['nullable', 'string', 'max:50'],
+ 'submitted_text' => ['required', 'string', 'max:10000'],
+ 'redirect_url' => ['nullable', 'string'],
+ 'max_submissions_count' => ['nullable', 'integer', 'min:1'],
+ 'max_submissions_reached_text' => ['nullable', 'string'],
+ 'editable_submissions' => ['required', 'boolean'],
+ 'editable_submissions_button_text' => ['required', 'string', 'min:1', 'max:50'],
+ 'confetti_on_submission' => ['required', 'boolean'],
+ 'show_progress_bar' => ['required', 'boolean'],
+ 'auto_save' => ['required', 'boolean'],
+ 'auto_focus' => ['required', 'boolean'],
+ 'enable_partial_submissions' => ['required', 'boolean'],
+ 'enable_ip_tracking' => ['required', 'boolean'],
+ 'can_be_indexed' => ['required', 'boolean'],
+ 'use_captcha' => ['required', 'boolean'],
+ 'captcha_provider' => ['required', Rule::in(['recaptcha', 'hcaptcha'])],
+ 'seo_meta' => ['nullable', 'array'],
+ 'settings' => ['present', 'array'],
+ 'settings.navigation_arrows' => ['sometimes', 'boolean'],
+ 'settings.auto_next' => ['sometimes', 'boolean'],
+ 'analytics' => ['nullable', 'array'],
+ 'analytics.provider' => ['nullable', Rule::in(['meta_pixel', 'google_analytics', 'gtm'])],
+ 'analytics.tracking_id' => [
+ 'nullable',
+ 'string',
+ 'max:50',
+ 'regex:/^[A-Za-z0-9\-_\.]+$/',
+ 'required_if:analytics.provider,meta_pixel,google_analytics,gtm',
+ ],
+ ])->validate();
+ }
+
+ public function defaults(): array
+ {
+ return [
+ 'schema_version' => self::SCHEMA_VERSION,
+ 'title' => 'Untitled Form',
+ 'visibility' => 'draft',
+ 'properties' => [],
+ 'computed_variables' => [],
+ 'language' => 'en',
+ 'font_family' => null,
+ 'theme' => 'default',
+ 'presentation_style' => 'classic',
+ 'width' => 'centered',
+ 'size' => 'md',
+ 'layout_rtl' => false,
+ 'border_radius' => 'small',
+ 'dark_mode' => 'auto',
+ 'color' => '#3B82F6',
+ 'uppercase_labels' => false,
+ 'no_branding' => false,
+ 'transparent_background' => false,
+ 'translations' => [],
+ 'cover_picture' => null,
+ 'cover_settings' => [],
+ 'logo_picture' => null,
+ 'custom_code' => null,
+ 'custom_css' => null,
+ 'submit_button_text' => null,
+ 're_fillable' => false,
+ 're_fill_button_text' => null,
+ 'submitted_text' => 'Amazing, we saved your answers. Thank you for your time and have a great day!',
+ 'redirect_url' => null,
+ 'max_submissions_count' => null,
+ 'max_submissions_reached_text' => 'This form has now reached the maximum number of allowed submissions and is now closed.',
+ 'editable_submissions' => false,
+ 'editable_submissions_button_text' => 'Edit submission',
+ 'confetti_on_submission' => false,
+ 'show_progress_bar' => false,
+ 'auto_save' => true,
+ 'auto_focus' => true,
+ 'enable_partial_submissions' => false,
+ 'enable_ip_tracking' => false,
+ 'can_be_indexed' => true,
+ 'use_captcha' => false,
+ 'captcha_provider' => 'recaptcha',
+ 'seo_meta' => [],
+ 'settings' => [],
+ 'analytics' => [],
+ ];
+ }
+
+ /**
+ * Return the canonical agent-editable portion of an existing form.
+ */
+ public function fromForm(Form $form): array
+ {
+ $definition = ['schema_version' => self::SCHEMA_VERSION];
+
+ foreach (self::ALLOWED_TOP_LEVEL_KEYS as $key) {
+ if ($key === 'schema_version') {
+ continue;
+ }
+
+ if (array_key_exists($key, $form->getAttributes())) {
+ $definition[$key] = $form->getAttribute($key);
+ }
+ }
+
+ return $definition;
+ }
+
+ public function jsonSchema(): array
+ {
+ return [
+ '$schema' => 'https://json-schema.org/draft/2020-12/schema',
+ '$id' => 'https://opnform.com/schemas/agent-form-definition/v1.json',
+ 'title' => 'OpnForm Agent Form Definition v1',
+ 'type' => 'object',
+ 'additionalProperties' => false,
+ 'required' => ['schema_version', 'title', 'properties'],
+ 'properties' => [
+ 'schema_version' => ['const' => self::SCHEMA_VERSION],
+ 'title' => ['type' => 'string', 'minLength' => 1, 'maxLength' => 255],
+ 'visibility' => ['type' => 'string', 'enum' => Form::VISIBILITY, 'default' => 'draft'],
+ 'properties' => [
+ 'type' => 'array',
+ 'minItems' => 1,
+ 'maxItems' => 500,
+ 'items' => ['$ref' => '#/$defs/block'],
+ ],
+ 'computed_variables' => ['type' => 'array', 'default' => []],
+ 'language' => ['type' => 'string', 'enum' => Form::LANGUAGES, 'default' => 'en'],
+ 'font_family' => ['type' => ['string', 'null']],
+ 'theme' => ['type' => 'string', 'enum' => Form::THEMES, 'default' => 'default'],
+ 'presentation_style' => ['type' => 'string', 'enum' => Form::PRESENTATION_STYLES, 'default' => 'classic'],
+ 'width' => ['type' => 'string', 'enum' => Form::WIDTHS, 'default' => 'centered'],
+ 'size' => ['type' => 'string', 'enum' => Form::SIZES, 'default' => 'md'],
+ 'layout_rtl' => ['type' => 'boolean', 'default' => false],
+ 'border_radius' => ['type' => 'string', 'enum' => Form::BORDER_RADIUS, 'default' => 'small'],
+ 'dark_mode' => ['type' => 'string', 'enum' => Form::DARK_MODE_VALUES, 'default' => 'auto'],
+ 'color' => ['type' => 'string', 'default' => '#3B82F6'],
+ 'uppercase_labels' => ['type' => 'boolean', 'default' => false],
+ 'no_branding' => ['type' => 'boolean', 'default' => false],
+ 'transparent_background' => ['type' => 'boolean', 'default' => false],
+ 'translations' => ['type' => ['object', 'array'], 'default' => (object) []],
+ 'cover_picture' => ['type' => ['string', 'null'], 'format' => 'uri', 'pattern' => '^https://'],
+ 'cover_settings' => ['type' => ['object', 'array'], 'default' => (object) []],
+ 'logo_picture' => ['type' => ['string', 'null'], 'format' => 'uri', 'pattern' => '^https://'],
+ 'custom_code' => ['type' => ['string', 'null']],
+ 'custom_css' => ['type' => ['string', 'null']],
+ 'submit_button_text' => ['type' => ['string', 'null'], 'maxLength' => 50],
+ 're_fillable' => ['type' => 'boolean', 'default' => false],
+ 're_fill_button_text' => ['type' => ['string', 'null'], 'maxLength' => 50],
+ 'submitted_text' => ['type' => 'string', 'maxLength' => 10000],
+ 'redirect_url' => ['type' => ['string', 'null']],
+ 'max_submissions_count' => ['type' => ['integer', 'null'], 'minimum' => 1],
+ 'max_submissions_reached_text' => ['type' => ['string', 'null']],
+ 'editable_submissions' => ['type' => 'boolean', 'default' => false],
+ 'editable_submissions_button_text' => ['type' => 'string', 'minLength' => 1, 'maxLength' => 50],
+ 'confetti_on_submission' => ['type' => 'boolean', 'default' => false],
+ 'show_progress_bar' => ['type' => 'boolean', 'default' => false],
+ 'auto_save' => ['type' => 'boolean', 'default' => true],
+ 'auto_focus' => ['type' => 'boolean', 'default' => true],
+ 'enable_partial_submissions' => ['type' => 'boolean', 'default' => false],
+ 'enable_ip_tracking' => ['type' => 'boolean', 'default' => false],
+ 'can_be_indexed' => ['type' => 'boolean', 'default' => true],
+ 'use_captcha' => ['type' => 'boolean', 'default' => false],
+ 'captcha_provider' => ['type' => 'string', 'enum' => ['recaptcha', 'hcaptcha'], 'default' => 'recaptcha'],
+ 'seo_meta' => ['type' => ['object', 'array'], 'default' => (object) []],
+ 'settings' => ['type' => ['object', 'array'], 'default' => (object) []],
+ 'analytics' => ['type' => ['object', 'array'], 'default' => (object) []],
+ ],
+ '$defs' => [
+ 'block' => [
+ 'type' => 'object',
+ 'required' => ['name', 'type'],
+ 'additionalProperties' => true,
+ 'properties' => [
+ 'id' => ['type' => 'string'],
+ 'name' => ['type' => 'string', 'minLength' => 1],
+ 'type' => ['type' => 'string', 'enum' => FieldCatalog::types()],
+ 'help' => ['type' => ['string', 'null']],
+ 'hidden' => ['type' => 'boolean', 'default' => false],
+ 'required' => ['type' => 'boolean', 'default' => false],
+ 'placeholder' => ['type' => ['string', 'null']],
+ 'width' => ['type' => 'string', 'enum' => ['full', '1/2', '1/3', '2/3', '1/4', '3/4'], 'default' => 'full'],
+ 'image' => ['$ref' => '#/$defs/blockImage'],
+ ],
+ ],
+ 'blockImage' => [
+ 'type' => 'object',
+ 'additionalProperties' => true,
+ 'properties' => [
+ 'url' => ['type' => ['string', 'null'], 'format' => 'uri', 'pattern' => '^https://'],
+ 'alt' => ['type' => ['string', 'null'], 'maxLength' => 125],
+ 'layout' => [
+ 'type' => ['string', 'null'],
+ 'enum' => ['between', 'left-small', 'right-small', 'left-split', 'right-split', 'background', null],
+ ],
+ 'focal_point' => [
+ 'type' => ['object', 'null'],
+ 'properties' => [
+ 'x' => ['type' => 'number', 'minimum' => 0, 'maximum' => 100],
+ 'y' => ['type' => 'number', 'minimum' => 0, 'maximum' => 100],
+ ],
+ ],
+ 'brightness' => ['type' => 'integer', 'minimum' => -100, 'maximum' => 100],
+ 'fade' => ['type' => 'boolean'],
+ ],
+ ],
+ ],
+ 'x-opnform-max-bytes' => self::MAX_DEFINITION_BYTES,
+ ];
+ }
+
+ private function migrate(array $definition): array
+ {
+ $version = $definition['schema_version'] ?? self::SCHEMA_VERSION;
+
+ if ($version !== self::SCHEMA_VERSION) {
+ throw ValidationException::withMessages([
+ 'schema_version' => ["Unsupported schema version [{$version}]. Current version is ".self::SCHEMA_VERSION.'.'],
+ ]);
+ }
+
+ $definition['schema_version'] = self::SCHEMA_VERSION;
+
+ return $definition;
+ }
+
+ private function normalizeAliases(array $definition): array
+ {
+ $definition['properties'] = collect($definition['properties'] ?? [])->map(function ($property) {
+ if (! is_array($property) || ! isset(FieldCatalog::ALIASES[$property['type'] ?? ''])) {
+ return $property;
+ }
+
+ return array_replace($property, FieldCatalog::ALIASES[$property['type']]);
+ })->values()->all();
+
+ return $definition;
+ }
+}
diff --git a/api/app/Service/Forms/AgentFormDraftPatcher.php b/api/app/Service/Forms/AgentFormDraftPatcher.php
new file mode 100644
index 000000000..8e032fd90
--- /dev/null
+++ b/api/app/Service/Forms/AgentFormDraftPatcher.php
@@ -0,0 +1,168 @@
+<?php
+
+namespace App\Service\Forms;
+
+use Illuminate\Validation\ValidationException;
+
+class AgentFormDraftPatcher
+{
+ private const OPERATIONS = [
+ 'set_form_values',
+ 'add_block',
+ 'update_block',
+ 'remove_block',
+ 'move_block',
+ ];
+
+ public function apply(array $definition, array $operations): array
+ {
+ if ($operations === []) {
+ throw ValidationException::withMessages([
+ 'operations' => ['At least one draft operation is required.'],
+ ]);
+ }
+
+ foreach ($operations as $index => $operation) {
+ if (! is_array($operation)) {
+ throw $this->operationError($index, 'Each operation must be an object.');
+ }
+
+ $name = $operation['op'] ?? null;
+
+ if (! is_string($name) || ! in_array($name, self::OPERATIONS, true)) {
+ throw $this->operationError($index, 'Unsupported operation.');
+ }
+
+ $definition = match ($name) {
+ 'set_form_values' => $this->setFormValues($definition, $operation, $index),
+ 'add_block' => $this->addBlock($definition, $operation, $index),
+ 'update_block' => $this->updateBlock($definition, $operation, $index),
+ 'remove_block' => $this->removeBlock($definition, $operation, $index),
+ 'move_block' => $this->moveBlock($definition, $operation, $index),
+ };
+ }
+
+ return $definition;
+ }
+
+ private function setFormValues(array $definition, array $operation, int $operationIndex): array
+ {
+ $values = $operation['values'] ?? null;
+
+ if (! is_array($values) || $values === []) {
+ throw $this->operationError($operationIndex, 'set_form_values.values must be a non-empty object.');
+ }
+
+ $protectedKeys = array_intersect(array_keys($values), ['schema_version', 'properties']);
+
+ if ($protectedKeys !== []) {
+ throw $this->operationError($operationIndex, 'Use block operations to change properties; schema_version cannot be changed.');
+ }
+
+ return array_replace($definition, $values);
+ }
+
+ private function addBlock(array $definition, array $operation, int $operationIndex): array
+ {
+ $block = $operation['block'] ?? null;
+
+ if (! is_array($block) || $block === []) {
+ throw $this->operationError($operationIndex, 'add_block.block must be an object.');
+ }
+
+ $properties = $this->properties($definition);
+ $position = $operation['index'] ?? count($properties);
+
+ if (! is_int($position) || $position < 0 || $position > count($properties)) {
+ throw $this->operationError($operationIndex, 'add_block.index is out of range.');
+ }
+
+ array_splice($properties, $position, 0, [$block]);
+ $definition['properties'] = array_values($properties);
+
+ return $definition;
+ }
+
+ private function updateBlock(array $definition, array $operation, int $operationIndex): array
+ {
+ $patch = $operation['patch'] ?? null;
+
+ if (! is_array($patch) || $patch === []) {
+ throw $this->operationError($operationIndex, 'update_block.patch must be a non-empty object.');
+ }
+
+ if (array_key_exists('id', $patch)) {
+ throw $this->operationError($operationIndex, 'Block IDs are stable and cannot be changed.');
+ }
+
+ $properties = $this->properties($definition);
+ $blockIndex = $this->resolveBlockIndex($properties, $operation, $operationIndex);
+ $properties[$blockIndex] = array_replace($properties[$blockIndex], $patch);
+ $definition['properties'] = $properties;
+
+ return $definition;
+ }
+
+ private function removeBlock(array $definition, array $operation, int $operationIndex): array
+ {
+ $properties = $this->properties($definition);
+ $blockIndex = $this->resolveBlockIndex($properties, $operation, $operationIndex);
+ array_splice($properties, $blockIndex, 1);
+ $definition['properties'] = array_values($properties);
+
+ return $definition;
+ }
+
+ private function moveBlock(array $definition, array $operation, int $operationIndex): array
+ {
+ $properties = $this->properties($definition);
+ $blockIndex = $this->resolveBlockIndex($properties, $operation, $operationIndex);
+ $toIndex = $operation['to_index'] ?? null;
+
+ if (! is_int($toIndex) || $toIndex < 0 || $toIndex >= count($properties)) {
+ throw $this->operationError($operationIndex, 'move_block.to_index is out of range.');
+ }
+
+ $block = $properties[$blockIndex];
+ array_splice($properties, $blockIndex, 1);
+ array_splice($properties, $toIndex, 0, [$block]);
+ $definition['properties'] = array_values($properties);
+
+ return $definition;
+ }
+
+ private function resolveBlockIndex(array $properties, array $operation, int $operationIndex): int
+ {
+ $blockId = $operation['block_id'] ?? null;
+
+ if (is_string($blockId) && $blockId !== '') {
+ foreach ($properties as $index => $property) {
+ if (($property['id'] ?? null) === $blockId) {
+ return $index;
+ }
+ }
+
+ throw $this->operationError($operationIndex, "Block [{$blockId}] was not found.");
+ }
+
+ $index = $operation['index'] ?? null;
+
+ if (! is_int($index) || ! array_key_exists($index, $properties)) {
+ throw $this->operationError($operationIndex, 'A valid block_id or index is required.');
+ }
+
+ return $index;
+ }
+
+ private function properties(array $definition): array
+ {
+ return array_values($definition['properties'] ?? []);
+ }
+
+ private function operationError(int $index, string $message): ValidationException
+ {
+ return ValidationException::withMessages([
+ "operations.{$index}" => [$message],
+ ]);
+ }
+}
diff --git a/api/app/Service/Forms/AgentFormDraftRateLimiter.php b/api/app/Service/Forms/AgentFormDraftRateLimiter.php
new file mode 100644
index 000000000..52cc265d6
--- /dev/null
+++ b/api/app/Service/Forms/AgentFormDraftRateLimiter.php
@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Service\Forms;
+
+use Illuminate\Support\Facades\RateLimiter;
+use Illuminate\Validation\ValidationException;
+
+class AgentFormDraftRateLimiter
+{
+ public function hit(string $identifier): void
+ {
+ $hash = hash('sha256', $identifier);
+ $minuteKey = "mcp:draft-create:minute:{$hash}";
+ $hourKey = "mcp:draft-create:hour:{$hash}";
+ $minuteLimit = max(1, config('opnform.mcp.rate_limit.draft_creates_per_minute', 20));
+ $hourLimit = max(1, config('opnform.mcp.rate_limit.draft_creates_per_hour', 200));
+
+ if (RateLimiter::tooManyAttempts($minuteKey, $minuteLimit)
+ || RateLimiter::tooManyAttempts($hourKey, $hourLimit)) {
+ throw ValidationException::withMessages([
+ 'definition' => ['Too many drafts were created. Reuse or update an existing draft before trying again.'],
+ ]);
+ }
+
+ RateLimiter::hit($minuteKey, 60);
+ RateLimiter::hit($hourKey, 3600);
+ }
+}
diff --git a/api/app/Service/Forms/AgentFormDraftService.php b/api/app/Service/Forms/AgentFormDraftService.php
new file mode 100644
index 000000000..296e4b2a0
--- /dev/null
+++ b/api/app/Service/Forms/AgentFormDraftService.php
@@ -0,0 +1,323 @@
+<?php
+
+namespace App\Service\Forms;
+
+use App\Models\Forms\AgentFormDraft;
+use App\Models\Forms\AgentFormDraftHandoff;
+use App\Models\Forms\Form;
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Support\Facades\URL;
+use Illuminate\Validation\ValidationException;
+
+class AgentFormDraftService
+{
+ public const EXPIRY_DAYS = 7;
+
+ public const PREVIEW_URL_TTL_MINUTES = 60;
+
+ public function __construct(
+ private readonly AgentFormDefinition $formDefinition,
+ private readonly AgentFormDraftPatcher $patcher,
+ private readonly FormCreationService $formCreation,
+ ) {
+ }
+
+ /**
+ * @return array{draft: AgentFormDraft, token: string}
+ */
+ public function create(array $definition): array
+ {
+ $definition['visibility'] = 'draft';
+ $definition = $this->formDefinition->normalizeAndValidate($definition);
+ $token = $this->generateToken();
+
+ $draft = AgentFormDraft::query()->create([
+ 'token_hash' => $this->hashToken($token),
+ 'definition' => $definition,
+ 'schema_version' => AgentFormDefinition::SCHEMA_VERSION,
+ 'version' => 1,
+ 'status' => AgentFormDraft::STATUS_ACTIVE,
+ 'expires_at' => now()->addDays(self::EXPIRY_DAYS),
+ ]);
+
+ return ['draft' => $draft, 'token' => $token];
+ }
+
+ public function get(string $token): AgentFormDraft
+ {
+ return $this->resolveActive($token);
+ }
+
+ public function patch(string $token, int $expectedVersion, array $operations): AgentFormDraft
+ {
+ return DB::transaction(function () use ($token, $expectedVersion, $operations) {
+ $draft = $this->resolveActive($token, lock: true);
+
+ if ($draft->version !== $expectedVersion) {
+ throw ValidationException::withMessages([
+ 'expected_version' => ["Draft version conflict. Current version is {$draft->version}. Fetch the draft and retry."],
+ ]);
+ }
+
+ $definition = $this->patcher->apply($draft->definition, $operations);
+ $definition['visibility'] = 'draft';
+ $definition = $this->formDefinition->normalizeAndValidate($definition);
+
+ $draft->forceFill([
+ 'definition' => $definition,
+ 'schema_version' => AgentFormDefinition::SCHEMA_VERSION,
+ 'version' => $draft->version + 1,
+ ])->save();
+
+ return $draft->refresh();
+ });
+ }
+
+ public function serialize(AgentFormDraft $draft): array
+ {
+ return [
+ 'version' => $draft->version,
+ 'schema_version' => $draft->schema_version,
+ 'status' => $draft->status,
+ 'expires_at' => $draft->expires_at->toIso8601String(),
+ 'definition' => $draft->definition,
+ ];
+ }
+
+ /**
+ * @return array{handoff_token: string, editor_url: string, expires_at: string}
+ */
+ public function issueEditorHandoff(string $draftToken): array
+ {
+ return DB::transaction(function () use ($draftToken) {
+ $draft = $this->resolveActive($draftToken, lock: true);
+ $handoffToken = $this->generateToken();
+ $expiresAt = $draft->expires_at->copy();
+
+ $draft->editorHandoffs()->create([
+ 'token_hash' => $this->hashToken($handoffToken),
+ 'expires_at' => $expiresAt,
+ ]);
+
+ return [
+ 'handoff_token' => $handoffToken,
+ 'editor_url' => front_url('/agent-drafts/edit#handoff='.$handoffToken),
+ 'expires_at' => $expiresAt->toIso8601String(),
+ ];
+ });
+ }
+
+ /**
+ * @return array{draft: AgentFormDraft, editor_session: string}
+ */
+ public function consumeEditorHandoff(string $handoffToken): array
+ {
+ return DB::transaction(function () use ($handoffToken) {
+ $this->assertTokenShape($handoffToken, 'handoff_token');
+
+ $handoff = AgentFormDraftHandoff::query()
+ ->where('token_hash', $this->hashToken($handoffToken))
+ ->where('expires_at', '>', now())
+ ->lockForUpdate()
+ ->first();
+
+ if (! $handoff) {
+ throw ValidationException::withMessages([
+ 'handoff_token' => ['This editor link is invalid or expired.'],
+ ]);
+ }
+
+ $draft = AgentFormDraft::query()
+ ->whereKey($handoff->agent_form_draft_id)
+ ->active()
+ ->lockForUpdate()
+ ->first();
+
+ if (! $draft) {
+ throw ValidationException::withMessages([
+ 'handoff_token' => ['This editor link is invalid or expired.'],
+ ]);
+ }
+
+ $editorSession = $this->editorSessionToken($draft);
+ $handoff->forceFill(['last_used_at' => now()])->save();
+ $draft->forceFill([
+ 'editor_session_hash' => $this->hashToken($editorSession),
+ 'editor_session_expires_at' => $draft->expires_at,
+ ])->save();
+
+ return ['draft' => $draft->refresh(), 'editor_session' => $editorSession];
+ });
+ }
+
+ public function getForEditor(string $editorSession): AgentFormDraft
+ {
+ return $this->resolveEditorSession($editorSession);
+ }
+
+ public function replaceFromEditor(string $editorSession, int $expectedVersion, array $definition): AgentFormDraft
+ {
+ return DB::transaction(function () use ($editorSession, $expectedVersion, $definition) {
+ $draft = $this->resolveEditorSession($editorSession, lock: true);
+ $this->assertActiveVersion($draft, $expectedVersion);
+
+ $definition['visibility'] = 'draft';
+ $definition = $this->formDefinition->normalizeAndValidate($definition);
+ $draft->forceFill([
+ 'definition' => $definition,
+ 'schema_version' => AgentFormDefinition::SCHEMA_VERSION,
+ 'version' => $draft->version + 1,
+ ])->save();
+
+ return $draft->refresh();
+ });
+ }
+
+ /**
+ * @return array{form: Form, cleanings: array, already_claimed: bool}
+ */
+ public function claim(string $editorSession, int $expectedVersion, Workspace $workspace, User $user): array
+ {
+ return DB::transaction(function () use ($editorSession, $expectedVersion, $workspace, $user) {
+ $draft = $this->resolveEditorSession($editorSession, lock: true, activeOnly: false);
+
+ if ($draft->status === AgentFormDraft::STATUS_CLAIMED && $draft->claimed_form_id) {
+ $form = Form::query()->findOrFail($draft->claimed_form_id);
+ Gate::forUser($user)->authorize('view', $form);
+
+ return ['form' => $form, 'cleanings' => [], 'already_claimed' => true];
+ }
+
+ $this->assertActiveVersion($draft, $expectedVersion);
+ Gate::forUser($user)->authorize('ownsWorkspace', $workspace);
+ Gate::forUser($user)->authorize('create', [Form::class, $workspace]);
+
+ $definition = $draft->definition;
+ $definition['visibility'] = 'draft';
+ $definition = $this->formDefinition->normalizeAndValidate($definition, $workspace);
+ $created = $this->formCreation->create($definition, $user, $workspace);
+
+ $draft->forceFill([
+ 'status' => AgentFormDraft::STATUS_CLAIMED,
+ 'claimed_form_id' => $created['form']->id,
+ 'claimed_at' => now(),
+ ])->save();
+
+ return [
+ 'form' => $created['form'],
+ 'cleanings' => $created['cleanings'],
+ 'already_claimed' => false,
+ ];
+ });
+ }
+
+ public function previewUrl(AgentFormDraft $draft): string
+ {
+ $sourceUrl = URL::temporarySignedRoute(
+ 'agent-drafts.preview',
+ now()->addMinutes(self::PREVIEW_URL_TTL_MINUTES),
+ ['draft' => $draft->id],
+ );
+
+ return front_url('/agent-drafts/preview?source='.rawurlencode($sourceUrl));
+ }
+
+ private function resolveActive(string $token, bool $lock = false): AgentFormDraft
+ {
+ $this->assertTokenShape($token, 'draft_token');
+
+ $query = AgentFormDraft::query()
+ ->where('token_hash', $this->hashToken($token))
+ ->active();
+
+ if ($lock) {
+ $query->lockForUpdate();
+ }
+
+ $draft = $query->first();
+
+ if (! $draft) {
+ throw $this->unavailable();
+ }
+
+ return $draft;
+ }
+
+ private function resolveEditorSession(string $token, bool $lock = false, bool $activeOnly = true): AgentFormDraft
+ {
+ $this->assertTokenShape($token, 'editor_session');
+ $query = AgentFormDraft::query()
+ ->where('editor_session_hash', $this->hashToken($token))
+ ->where('editor_session_expires_at', '>', now())
+ ->where('expires_at', '>', now());
+
+ if ($activeOnly) {
+ $query->where('status', AgentFormDraft::STATUS_ACTIVE);
+ }
+ if ($lock) {
+ $query->lockForUpdate();
+ }
+
+ $draft = $query->first();
+ if (! $draft) {
+ throw ValidationException::withMessages([
+ 'editor_session' => ['Editor session not found or expired.'],
+ ]);
+ }
+
+ return $draft;
+ }
+
+ private function assertActiveVersion(AgentFormDraft $draft, int $expectedVersion): void
+ {
+ if (! $draft->isAvailable()) {
+ throw $this->unavailable();
+ }
+ if ($draft->version !== $expectedVersion) {
+ throw ValidationException::withMessages([
+ 'expected_version' => ["Draft version conflict. Current version is {$draft->version}. Fetch the draft and retry."],
+ ]);
+ }
+ }
+
+ private function assertTokenShape(string $token, string $field): void
+ {
+ if (! preg_match('/^[A-Za-z0-9_-]{43}$/', $token)) {
+ throw ValidationException::withMessages([
+ $field => ['Invalid or unavailable capability token.'],
+ ]);
+ }
+ }
+
+ private function generateToken(): string
+ {
+ return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
+ }
+
+ private function editorSessionToken(AgentFormDraft $draft): string
+ {
+ $token = hash_hmac(
+ 'sha256',
+ 'agent-form-draft-editor:'.$draft->getKey(),
+ (string) config('app.key'),
+ true,
+ );
+
+ return rtrim(strtr(base64_encode($token), '+/', '-_'), '=');
+ }
+
+ private function hashToken(string $token): string
+ {
+ return hash('sha256', $token);
+ }
+
+ private function unavailable(): ValidationException
+ {
+ return ValidationException::withMessages([
+ 'draft_token' => ['Draft not found, expired, or already claimed.'],
+ ]);
+ }
+}
diff --git a/api/app/Service/Forms/AgentFormFieldCatalog.php b/api/app/Service/Forms/AgentFormFieldCatalog.php
new file mode 100644
index 000000000..c9ecb5ef3
--- /dev/null
+++ b/api/app/Service/Forms/AgentFormFieldCatalog.php
@@ -0,0 +1,125 @@
+<?php
+
+namespace App\Service\Forms;
+
+class AgentFormFieldCatalog
+{
+ public const INPUT_TYPES = [
+ 'text',
+ 'rich_text',
+ 'date',
+ 'url',
+ 'phone_number',
+ 'email',
+ 'checkbox',
+ 'select',
+ 'multi_select',
+ 'matrix',
+ 'number',
+ 'rating',
+ 'scale',
+ 'slider',
+ 'files',
+ 'signature',
+ 'barcode',
+ 'payment',
+ ];
+
+ public const LAYOUT_TYPES = [
+ 'nf-text',
+ 'nf-page-break',
+ 'nf-divider',
+ 'nf-image',
+ 'nf-video',
+ 'nf-audio',
+ 'nf-code',
+ ];
+
+ public const ALIASES = [
+ 'radio' => ['type' => 'select', 'without_dropdown' => true],
+ 'qrcode' => ['type' => 'barcode', 'decoders' => ['qr_reader']],
+ 'password' => ['type' => 'text', 'secret_input' => true, 'multi_lines' => false],
+ 'toggle_switch' => ['type' => 'checkbox', 'use_toggle_switch' => true],
+ ];
+
+ public static function types(): array
+ {
+ return [...self::INPUT_TYPES, ...self::LAYOUT_TYPES];
+ }
+
+ public static function reference(): array
+ {
+ return [
+ 'input_types' => self::INPUT_TYPES,
+ 'layout_types' => self::LAYOUT_TYPES,
+ 'aliases' => self::ALIASES,
+ 'common_properties' => [
+ 'id' => 'Stable UUID. It is generated when omitted.',
+ 'name' => 'Required user-facing block label.',
+ 'type' => 'One canonical type or alias from this catalog.',
+ 'help' => 'Optional sanitized HTML help text.',
+ 'hidden' => 'Boolean, defaults to false.',
+ 'required' => 'Boolean, defaults to false.',
+ 'placeholder' => 'Optional placeholder.',
+ 'width' => 'One of full, 1/2, 1/3, 2/3, 1/4, 3/4. Defaults to full.',
+ ],
+ 'type_properties' => [
+ 'text' => ['multi_lines', 'max_char_limit', 'show_char_limit', 'secret_input', 'input_mask'],
+ 'date' => ['with_time', 'date_range', 'prefill_today', 'disable_past_dates', 'disable_future_dates'],
+ 'select' => ['select.options[{name,id,image?}]', 'without_dropdown', 'allow_creation'],
+ 'multi_select' => ['multi_select.options[{name,id,image?}]', 'without_dropdown', 'min_selection', 'max_selection'],
+ 'checkbox' => ['use_toggle_switch'],
+ 'rating' => ['rating_max_value'],
+ 'scale' => ['scale_min_value', 'scale_max_value', 'scale_step_value'],
+ 'slider' => ['slider_min_value', 'slider_max_value', 'slider_step_value'],
+ 'files' => ['max_file_size', 'allowed_file_types'],
+ 'barcode' => ['decoders'],
+ 'matrix' => ['rows', 'columns'],
+ 'payment' => ['amount', 'currency', 'stripe_account_id'],
+ 'nf-text' => ['content'],
+ 'nf-page-break' => ['next_btn_text', 'previous_btn_text'],
+ 'nf-image' => ['image_block'],
+ 'nf-video' => ['video_block'],
+ 'nf-audio' => ['audio_block'],
+ 'nf-code' => ['content'],
+ ],
+ 'presentation_modes' => [
+ 'classic' => [
+ 'behavior' => 'Renders fields in a continuous form. Add nf-page-break blocks only when explicit pagination is wanted.',
+ 'widths' => 'Responsive widths such as 1/2 and 1/3 may be used.',
+ 'standalone_layout_blocks' => 'Layout blocks such as nf-image, nf-divider, and nf-code are supported.',
+ ],
+ 'focused' => [
+ 'behavior' => 'Typeform-like flow. Every visible block is already one sequential step; do not add nf-page-break blocks.',
+ 'blocks' => 'Use input blocks and concise nf-text intro or explanation steps. Do not use standalone nf-image, nf-divider, nf-code, nf-video, or nf-audio blocks.',
+ 'widths' => 'Use width full because each step renders one block.',
+ 'media' => 'To illustrate a step, attach an image object directly to that input or nf-text block.',
+ 'settings' => [
+ 'auto_next' => 'Boolean. When true, compatible selection controls advance after input.',
+ 'navigation_arrows' => 'Boolean. Shows previous and next arrow controls.',
+ ],
+ 'translations' => [
+ 'focused_next_button_text' => 'Localized label for the next-step button.',
+ ],
+ ],
+ ],
+ 'block_media' => [
+ 'property' => 'image',
+ 'attach_to' => 'Any input block or nf-text block, especially for focused steps. This differs from the classic-only nf-image standalone block and its image_block property.',
+ 'image' => [
+ 'url' => 'Absolute public HTTPS image URL. Required for the media to render.',
+ 'alt' => 'Descriptive alternative text, at most 125 characters.',
+ 'layout' => 'One of between, left-small, right-small, left-split, right-split, background.',
+ 'focal_point' => ['x' => 'Number from 0 to 100.', 'y' => 'Number from 0 to 100.'],
+ 'brightness' => 'Integer from -100 to 100.',
+ 'fade' => 'Optional boolean overlay fade.',
+ ],
+ 'asset_policy' => 'Use user-provided or durable public HTTPS URLs. Never persist localhost, private addresses, expiring signed URLs, temporary tunnel domains such as trycloudflare.com, or paths discovered in the OpnForm source tree.',
+ ],
+ 'availability' => [
+ 'preview' => 'All field types may be rendered in a draft preview.',
+ 'save' => 'Workspace plan and hosting rules are applied when a draft is claimed or a form is saved; disabled features are returned as warnings.',
+ ],
+ ];
+ }
+}
diff --git a/api/app/Service/Forms/FormCleaner.php b/api/app/Service/Forms/FormCleaner.php
index 14c4d3207..71e0aa7d1 100644
--- a/api/app/Service/Forms/FormCleaner.php
+++ b/api/app/Service/Forms/FormCleaner.php
@@ -105,6 +105,19 @@ class FormCleaner
return $this;
}
+ /**
+ * Ingest raw form data from non-HTTP clients such as MCP tools.
+ */
+ public function processData(array $data, ?Form $form = null): FormCleaner
+ {
+ $customDomain = $data['custom_domain'] ?? $form?->custom_domain ?? null;
+ $allowOnSelfHosted = config('app.self_hosted', true) && (bool) config('opnform.custom_code.enable_self_hosted', false);
+ $this->allowCustomCode = ! empty($customDomain) || $allowOnSelfHosted;
+ $this->data = $this->commonCleaning($data);
+
+ return $this;
+ }
+
/**
* Create form cleaner instance from existing form
*/
diff --git a/api/app/Service/Forms/FormCreationService.php b/api/app/Service/Forms/FormCreationService.php
new file mode 100644
index 000000000..42930aa93
--- /dev/null
+++ b/api/app/Service/Forms/FormCreationService.php
@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Service\Forms;
+
+use App\Models\Forms\Form;
+use App\Models\User;
+use App\Models\Workspace;
+
+class FormCreationService
+{
+ /**
+ * @return array{form: Form, cleanings: array, has_cleaned: bool}
+ */
+ public function create(array $data, User $creator, Workspace $workspace): array
+ {
+ $cleaner = new FormCleaner();
+ $formData = $cleaner
+ ->processData($data)
+ ->simulateCleaning($workspace)
+ ->getData();
+
+ unset($formData['schema_version']);
+ $formData['workspace_id'] = $workspace->id;
+
+ $form = Form::create(array_merge($formData, [
+ 'creator_id' => $creator->id,
+ ]));
+
+ if (config('app.self_hosted') && ! empty($formData['slug'])) {
+ $form->slug = $formData['slug'];
+ $form->save();
+ }
+
+ return [
+ 'form' => $form,
+ 'cleanings' => $cleaner->getPerformedCleanings(),
+ 'has_cleaned' => $cleaner->hasCleaned(),
+ ];
+ }
+}
diff --git a/api/app/Service/Forms/FormDataNormalizer.php b/api/app/Service/Forms/FormDataNormalizer.php
new file mode 100644
index 000000000..0119dd85d
--- /dev/null
+++ b/api/app/Service/Forms/FormDataNormalizer.php
@@ -0,0 +1,79 @@
+<?php
+
+namespace App\Service\Forms;
+
+use Illuminate\Support\Str;
+use Stevebauman\Purify\Facades\Purify;
+
+class FormDataNormalizer
+{
+ /**
+ * Normalize data shared by HTTP requests, MCP tools, and draft claims.
+ */
+ public function normalize(array $data, bool $backfillPropertyIds = false): array
+ {
+ if (isset($data['title']) && is_string($data['title'])) {
+ $data['title'] = Str::substr(trim($data['title']), 0, 255);
+ }
+
+ if (isset($data['properties']) && is_array($data['properties'])) {
+ $data['properties'] = $this->normalizeProperties($data['properties'], $backfillPropertyIds);
+ }
+
+ return $data;
+ }
+
+ public function normalizeProperties(array $properties, bool $backfillIds = false): array
+ {
+ return collect($properties)->map(function ($property) use ($backfillIds) {
+ if (! is_array($property)) {
+ return $property;
+ }
+
+ if ($backfillIds && empty($property['id'])) {
+ $property['id'] = Str::uuid()->toString();
+ }
+
+ if (isset($property['name']) && is_string($property['name'])) {
+ $property['name'] = trim(strip_tags($property['name']));
+ }
+
+ if (isset($property['help']) && is_string($property['help'])) {
+ $property['help'] = Purify::clean($property['help']);
+
+ if (strip_tags($property['help']) === '') {
+ $property['help'] = null;
+ }
+ }
+
+ return $this->normalizeSelectOptionIds($property);
+ })->values()->all();
+ }
+
+ private function normalizeSelectOptionIds(array $property): array
+ {
+ $type = $property['type'] ?? null;
+
+ if (! in_array($type, ['select', 'multi_select'], true)) {
+ return $property;
+ }
+
+ if (! isset($property[$type]['options']) || ! is_array($property[$type]['options'])) {
+ return $property;
+ }
+
+ $property[$type]['options'] = array_map(function ($option) {
+ if (! is_array($option) || ! empty($option['id'] ?? null)) {
+ return $option;
+ }
+
+ if (! empty($option['name'] ?? null) && is_string($option['name'])) {
+ $option['id'] = $option['name'];
+ }
+
+ return $option;
+ }, $property[$type]['options']);
+
+ return $property;
+ }
+}
diff --git a/api/app/Service/Forms/FormSummaryRateLimiter.php b/api/app/Service/Forms/FormSummaryRateLimiter.php
new file mode 100644
index 000000000..c8e67e3cc
--- /dev/null
+++ b/api/app/Service/Forms/FormSummaryRateLimiter.php
@@ -0,0 +1,40 @@
+<?php
+
+namespace App\Service\Forms;
+
+use Illuminate\Support\Facades\RateLimiter;
+
+class FormSummaryRateLimiter
+{
+ public function attempt(int $userId): bool
+ {
+ $key = $this->key($userId);
+ if (RateLimiter::tooManyAttempts($key, $this->limit())) {
+ return false;
+ }
+
+ RateLimiter::hit($key, 60);
+
+ return true;
+ }
+
+ public function availableIn(int $userId): int
+ {
+ return RateLimiter::availableIn($this->key($userId));
+ }
+
+ public function remaining(int $userId): int
+ {
+ return RateLimiter::remaining($this->key($userId), $this->limit());
+ }
+
+ public function limit(): int
+ {
+ return max(1, config('opnform.form_summary_rate_limit_per_minute', 30));
+ }
+
+ private function key(int $userId): string
+ {
+ return 'form-summary:user:'.hash('sha256', (string) $userId);
+ }
+}
diff --git a/api/app/Service/Forms/FormUpdateService.php b/api/app/Service/Forms/FormUpdateService.php
new file mode 100644
index 000000000..57052880d
--- /dev/null
+++ b/api/app/Service/Forms/FormUpdateService.php
@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Service\Forms;
+
+use App\Models\Forms\Form;
+use Illuminate\Support\Str;
+
+final class FormUpdateService
+{
+ /**
+ * @return array{form: Form, cleanings: array, cleaning_keys: array, has_cleaned: bool}
+ */
+ public function update(Form $form, array $data): array
+ {
+ $cleaner = (new FormCleaner())
+ ->processData($data, $form)
+ ->simulateCleaning($form->workspace);
+ $formData = $cleaner->getData();
+ unset($formData['schema_version']);
+
+ $newPropertyIds = collect($formData['properties'])->pluck('id')->flip()->all();
+ $formData['removed_properties'] = array_merge(
+ $form->removed_properties ?? [],
+ collect($form->properties)
+ ->filter(fn (array $field): bool => ! Str::of($field['type'])->startsWith('nf-') && ! isset($newPropertyIds[$field['id']]))
+ ->all(),
+ );
+
+ $form->slug = config('app.self_hosted') && ! empty($formData['slug'])
+ ? $formData['slug']
+ : $form->slug;
+ $form->update($formData);
+
+ return [
+ 'form' => $form,
+ 'cleanings' => $cleaner->getPerformedCleanings(),
+ 'cleaning_keys' => $cleaner->getCleaningKeys(),
+ 'has_cleaned' => $cleaner->hasCleaned(),
+ ];
+ }
+}
diff --git a/api/app/Service/Forms/McpFormManagementService.php b/api/app/Service/Forms/McpFormManagementService.php
new file mode 100644
index 000000000..dd0096bb5
--- /dev/null
+++ b/api/app/Service/Forms/McpFormManagementService.php
@@ -0,0 +1,276 @@
+<?php
+
+namespace App\Service\Forms;
+
+use App\Models\Forms\Form;
+use App\Models\Forms\FormSubmission;
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+use Illuminate\Validation\ValidationException;
+
+class McpFormManagementService
+{
+ public function __construct(
+ private readonly AgentFormDefinition $definitions,
+ private readonly FormCreationService $formCreation,
+ private readonly FormUpdateService $formUpdate,
+ ) {
+ }
+
+ public function workspace(User $user, int $workspaceId): Workspace
+ {
+ $workspace = $user->workspaces()
+ ->withPivot('role')
+ ->where('workspaces.id', $workspaceId)
+ ->first();
+
+ if (! $workspace) {
+ throw ValidationException::withMessages([
+ 'workspace_id' => ['Workspace not found or not accessible.'],
+ ]);
+ }
+
+ return $workspace;
+ }
+
+ /** @return array<int, array<string, mixed>> */
+ public function listWorkspaces(User $user): array
+ {
+ return $user->workspaces()
+ ->withPivot('role')
+ ->orderBy('workspaces.name')
+ ->get()
+ ->map(fn (Workspace $workspace) => $this->serializeWorkspace($workspace))
+ ->all();
+ }
+
+ /** @return array<string, mixed> */
+ public function serializeWorkspace(Workspace $workspace): array
+ {
+ $role = $workspace->pivot?->role;
+
+ return [
+ 'id' => $workspace->id,
+ 'name' => $workspace->name,
+ 'icon' => $workspace->icon,
+ 'role' => $role,
+ 'can_write_forms' => $role !== User::ROLE_READONLY,
+ 'plan_tier' => $workspace->plan_tier,
+ ];
+ }
+
+ /** @return array{forms: array<int, array<string, mixed>>, pagination: array<string, int>} */
+ public function listForms(
+ User $user,
+ ?int $workspaceId,
+ ?string $search,
+ ?string $visibility,
+ int $page,
+ int $perPage,
+ ): array {
+ $workspaceIds = $user->workspaces()->pluck('workspaces.id');
+
+ if ($workspaceId !== null && ! $workspaceIds->contains($workspaceId)) {
+ throw ValidationException::withMessages([
+ 'workspace_id' => ['Workspace not found or not accessible.'],
+ ]);
+ }
+
+ $query = Form::query()
+ ->whereIn('workspace_id', $workspaceIds)
+ ->with('workspace')
+ ->withCount(['submissions as submissions_count' => fn (Builder $query) => $query->where('status', FormSubmission::STATUS_COMPLETED)])
+ ->withTotalViews()
+ ->when($workspaceId !== null, fn (Builder $query) => $query->where('workspace_id', $workspaceId))
+ ->when($search, fn (Builder $query) => $query->whereRaw('LOWER(title) LIKE ?', ['%'.Str::lower($search).'%']))
+ ->when($visibility, fn (Builder $query) => $query->where('visibility', $visibility))
+ ->orderByDesc('updated_at');
+
+ $forms = $query->paginate($perPage, ['*'], 'page', $page);
+
+ return [
+ 'forms' => collect($forms->items())->map(fn (Form $form) => $this->serializeFormSummary($form))->all(),
+ 'pagination' => [
+ 'page' => $forms->currentPage(),
+ 'per_page' => $forms->perPage(),
+ 'total' => $forms->total(),
+ 'last_page' => $forms->lastPage(),
+ ],
+ ];
+ }
+
+ public function form(User $user, int $formId, bool $lockForUpdate = false): Form
+ {
+ $form = Form::query()
+ ->with('workspace')
+ ->when($lockForUpdate, fn (Builder $query) => $query->lockForUpdate())
+ ->find($formId);
+
+ if (! $form || ! $user->ownsForm($form)) {
+ throw ValidationException::withMessages([
+ 'form_id' => ['Form not found or not accessible.'],
+ ]);
+ }
+
+ return $form;
+ }
+
+ /** @return array<string, mixed> */
+ public function create(User $user, ?int $workspaceId, array $definition): array
+ {
+ $workspace = $this->resolveCreationWorkspace($user, $workspaceId);
+ $this->assertWritable($workspace, $user);
+
+ $definition = $this->definitions->normalizeAndValidate($definition, $workspace);
+ $definition['visibility'] = 'draft';
+ $created = $this->formCreation->create($definition, $user, $workspace);
+
+ return [
+ 'message' => 'Form created as an unpublished draft.',
+ 'form' => $this->serializeForm($created['form']->load('workspace')),
+ 'disabled_features' => $created['cleanings'],
+ 'next_step' => 'Open edit_url to review or refine the unpublished form. Ask the user before calling publish_form.',
+ ];
+ }
+
+ /** @return array<string, mixed> */
+ public function update(User $user, int $formId, string $expectedRevision, array $definition): array
+ {
+ return DB::transaction(function () use ($user, $formId, $expectedRevision, $definition) {
+ $form = $this->form($user, $formId, lockForUpdate: true);
+ $this->assertWritable($form->workspace, $user);
+ $this->assertFresh($form, $expectedRevision);
+
+ $definition = $this->definitions->normalizeAndValidate($definition, $form->workspace);
+ $definition['visibility'] = $form->visibility;
+
+ $updated = $this->formUpdate->update($form, $definition);
+
+ return [
+ 'message' => 'Form updated.',
+ 'form' => $this->serializeForm($updated['form']->refresh()->load('workspace')),
+ 'disabled_features' => $updated['cleanings'],
+ ];
+ });
+ }
+
+ /** @return array<string, mixed> */
+ public function publish(User $user, int $formId, string $expectedRevision, bool $confirmed): array
+ {
+ if (! $confirmed) {
+ throw ValidationException::withMessages([
+ 'confirm_publish' => ['Ask the user for explicit confirmation before publishing.'],
+ ]);
+ }
+
+ return DB::transaction(function () use ($user, $formId, $expectedRevision) {
+ $form = $this->form($user, $formId, lockForUpdate: true);
+ $this->assertWritable($form->workspace, $user);
+ $this->assertFresh($form, $expectedRevision);
+ $form->update(['visibility' => 'public']);
+
+ return [
+ 'message' => 'Form published.',
+ 'form' => $this->serializeForm($form->refresh()->load('workspace')),
+ ];
+ });
+ }
+
+ /** @return array<string, mixed> */
+ public function trash(User $user, int $formId, string $expectedRevision, bool $confirmed): array
+ {
+ if (! $confirmed) {
+ throw ValidationException::withMessages([
+ 'confirm_trash' => ['Ask the user for explicit confirmation before moving the form to trash.'],
+ ]);
+ }
+
+ return DB::transaction(function () use ($user, $formId, $expectedRevision) {
+ $form = $this->form($user, $formId, lockForUpdate: true);
+ $this->assertWritable($form->workspace, $user);
+ $this->assertFresh($form, $expectedRevision);
+ $summary = $this->serializeFormSummary($form);
+ $form->delete();
+
+ return [
+ 'message' => 'Form moved to trash. This MCP integration does not expose restore or permanent deletion.',
+ 'form' => $summary,
+ ];
+ });
+ }
+
+ /** @return array<string, mixed> */
+ public function serializeForm(Form $form): array
+ {
+ return array_merge($this->serializeFormSummary($form), [
+ 'definition' => $this->definitions->fromForm($form),
+ 'revision' => $this->revision($form),
+ 'edit_url' => $form->edit_url,
+ ]);
+ }
+
+ /** @return array<string, mixed> */
+ private function serializeFormSummary(Form $form): array
+ {
+ return [
+ 'id' => $form->id,
+ 'workspace_id' => $form->workspace_id,
+ 'title' => $form->title,
+ 'visibility' => $form->visibility,
+ 'share_url' => $form->share_url,
+ 'submissions_count' => $form->submissions_count,
+ 'views_count' => $form->views_count,
+ 'created_at' => $form->created_at?->toISOString(),
+ 'updated_at' => $form->updated_at?->toISOString(),
+ ];
+ }
+
+ private function resolveCreationWorkspace(User $user, ?int $workspaceId): Workspace
+ {
+ if ($workspaceId !== null) {
+ return $this->workspace($user, $workspaceId);
+ }
+
+ $workspaces = $user->workspaces()->withPivot('role')->limit(2)->get();
+
+ if ($workspaces->count() === 1) {
+ return $workspaces->first();
+ }
+
+ throw ValidationException::withMessages([
+ 'workspace_id' => [$workspaces->isEmpty()
+ ? 'No workspace is available for this account.'
+ : 'This account has multiple workspaces. Call list_workspaces and provide workspace_id.'],
+ ]);
+ }
+
+ private function assertWritable(Workspace $workspace, User $user): void
+ {
+ if ($workspace->isReadonlyUser($user)) {
+ throw ValidationException::withMessages([
+ 'workspace_id' => ['This workspace membership is read-only.'],
+ ]);
+ }
+ }
+
+ private function assertFresh(Form $form, string $expectedRevision): void
+ {
+ if (! hash_equals($this->revision($form), $expectedRevision)) {
+ throw ValidationException::withMessages([
+ 'expected_revision' => ['The form changed since it was fetched. Call get_form and retry with its revision value.'],
+ ]);
+ }
+ }
+
+ private function revision(Form $form): string
+ {
+ return hash('sha256', json_encode([
+ 'id' => $form->id,
+ 'updated_at' => $form->updated_at?->toISOString(),
+ 'definition' => $this->definitions->fromForm($form),
+ ], JSON_THROW_ON_ERROR));
+ }
+}
diff --git a/api/app/Service/Forms/McpSubmissionExportRateLimiter.php b/api/app/Service/Forms/McpSubmissionExportRateLimiter.php
new file mode 100644
index 000000000..b8317c1cd
--- /dev/null
+++ b/api/app/Service/Forms/McpSubmissionExportRateLimiter.php
@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Service\Forms;
+
+use Illuminate\Support\Facades\RateLimiter;
+use Illuminate\Validation\ValidationException;
+
+class McpSubmissionExportRateLimiter
+{
+ public function hit(int $userId, int $formId): void
+ {
+ $identifier = hash('sha256', $userId.':'.$formId);
+ $minuteKey = "mcp:submission-export:minute:{$identifier}";
+ $hourKey = "mcp:submission-export:hour:{$identifier}";
+ $minuteLimit = max(1, config('opnform.mcp.rate_limit.submission_exports_per_minute', 5));
+ $hourLimit = max(1, config('opnform.mcp.rate_limit.submission_exports_per_hour', 30));
+
+ if (RateLimiter::tooManyAttempts($minuteKey, $minuteLimit)
+ || RateLimiter::tooManyAttempts($hourKey, $hourLimit)) {
+ throw ValidationException::withMessages([
+ 'form_id' => ['Too many submission exports were queued. Reuse the current export or try again later.'],
+ ]);
+ }
+
+ RateLimiter::hit($minuteKey, 60);
+ RateLimiter::hit($hourKey, 3600);
+ }
+}
diff --git a/api/app/Service/Forms/McpSubmissionService.php b/api/app/Service/Forms/McpSubmissionService.php
new file mode 100644
index 000000000..05dadfc3d
--- /dev/null
+++ b/api/app/Service/Forms/McpSubmissionService.php
@@ -0,0 +1,235 @@
+<?php
+
+namespace App\Service\Forms;
+
+use App\Jobs\Form\ExportFormSubmissionsJob;
+use App\Models\Forms\Form;
+use App\Models\Forms\FormSubmission;
+use App\Models\User;
+use App\Service\Billing\Feature;
+use App\Service\Billing\PlanAccessService;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Validation\ValidationException;
+
+class McpSubmissionService
+{
+ public function __construct(
+ private readonly McpFormManagementService $forms,
+ private readonly FormSummaryService $summaries,
+ private readonly FormExportService $exports,
+ private readonly McpSubmissionExportRateLimiter $exportRateLimiter,
+ private readonly FormSummaryRateLimiter $summaryRateLimiter,
+ private readonly PlanAccessService $planAccess,
+ ) {
+ }
+
+ /** @return array{submissions: array<int, array<string, mixed>>, pagination: array<string, int>} */
+ public function list(
+ User $user,
+ int $formId,
+ ?string $search,
+ string $status,
+ ?string $dateFrom,
+ ?string $dateTo,
+ int $page,
+ int $perPage,
+ ): array {
+ $form = $this->forms->form($user, $formId);
+ $query = $this->submissionQuery($form, $status, $dateFrom, $dateTo);
+
+ if ($search) {
+ $driver = DB::connection()->getDriverName();
+
+ if ($driver === 'mysql') {
+ $query->whereRaw("JSON_SEARCH(data, 'one', ?) IS NOT NULL", ['%'.$search.'%']);
+ } elseif ($driver === 'sqlite') {
+ $query->whereRaw("EXISTS (
+ SELECT 1 FROM json_each(data)
+ WHERE CAST(json_each.value AS TEXT) LIKE ?
+ )", ['%'.$search.'%']);
+ } else {
+ $query->whereRaw("EXISTS (
+ SELECT 1 FROM jsonb_each_text(data) AS kv(key, value)
+ WHERE kv.value ILIKE ?
+ )", ['%'.$search.'%']);
+ }
+ }
+
+ $submissions = $query->orderByDesc('created_at')->paginate($perPage, ['*'], 'page', $page);
+
+ return [
+ 'submissions' => collect($submissions->items())
+ ->map(fn (FormSubmission $submission) => $this->serialize($form, $submission))
+ ->all(),
+ 'pagination' => [
+ 'page' => $submissions->currentPage(),
+ 'per_page' => $submissions->perPage(),
+ 'total' => $submissions->total(),
+ 'last_page' => $submissions->lastPage(),
+ ],
+ ];
+ }
+
+ /** @return array<string, mixed> */
+ public function get(User $user, int $formId, int $submissionId): array
+ {
+ $form = $this->forms->form($user, $formId);
+ $submission = $form->submissions()->find($submissionId);
+
+ if (! $submission) {
+ throw ValidationException::withMessages([
+ 'submission_id' => ['Submission not found or not accessible.'],
+ ]);
+ }
+
+ return $this->serialize($form, $submission);
+ }
+
+ /** @return array<string, mixed> */
+ public function stats(
+ User $user,
+ int $formId,
+ string $status,
+ ?string $dateFrom,
+ ?string $dateTo,
+ ): array {
+ $form = $this->forms->form($user, $formId);
+ $this->planAccess->requireFeature($form->workspace, Feature::FORM_ANALYTICS);
+ $this->planAccess->requireFeature($form->workspace, Feature::FORM_SUMMARY);
+ if (! $this->summaryRateLimiter->attempt($user->id)) {
+ throw ValidationException::withMessages([
+ 'form_id' => ['Too many submission statistics requests. Try again later.'],
+ ]);
+ }
+ $filtered = $this->submissionQuery($form, $status, $dateFrom, $dateTo);
+ $filteredCount = (clone $filtered)->count();
+ $averageDuration = (clone $filtered)->whereNotNull('completion_time')->avg('completion_time');
+ $views = $form->views_count;
+ $completed = $form->submissions()->where('status', FormSubmission::STATUS_COMPLETED)->count();
+ $partial = $form->submissions()->where('status', FormSubmission::STATUS_PARTIAL)->count();
+
+ return [
+ 'form_id' => $form->id,
+ 'filters' => [
+ 'status' => $status,
+ 'date_from' => $dateFrom,
+ 'date_to' => $dateTo,
+ ],
+ 'overview' => [
+ 'views' => $views,
+ 'completed_submissions' => $completed,
+ 'partial_submissions' => $partial,
+ 'completion_rate' => $views > 0 ? round(($completed / $views) * 100, 2) : 0,
+ ],
+ 'filtered_submissions' => $filteredCount,
+ 'average_completion_seconds' => $averageDuration !== null ? round((float) $averageDuration, 2) : null,
+ 'field_summary' => $this->summaries->generateSummary($form, $dateFrom, $dateTo, $status),
+ ];
+ }
+
+ /** @return array<string, mixed> */
+ public function startExport(User $user, int $formId, array $submissionIds): array
+ {
+ $form = $this->forms->form($user, $formId);
+
+ if ($submissionIds !== []) {
+ $matched = $form->submissions()->whereIn('id', $submissionIds)->count();
+
+ if ($matched !== count(array_unique($submissionIds))) {
+ throw ValidationException::withMessages([
+ 'submission_ids' => ['One or more submissions were not found in this form.'],
+ ]);
+ }
+ } elseif (! $form->submissions()->exists()) {
+ throw ValidationException::withMessages([
+ 'form_id' => ['This form has no submissions to export.'],
+ ]);
+ }
+
+ $this->exportRateLimiter->hit($user->id, $form->id);
+
+ $columns = collect($form->properties)
+ ->filter(fn (array $property) => isset($property['id']) && ! str_starts_with((string) ($property['type'] ?? ''), 'nf-'))
+ ->mapWithKeys(fn (array $property) => [$property['id'] => true])
+ ->put('created_at', true)
+ ->all();
+ $jobId = $this->exports->initializeAsyncExport($form, $user->id);
+
+ ExportFormSubmissionsJob::dispatch($form, $columns, $submissionIds, $jobId, $user->id);
+
+ return [
+ 'job_id' => $jobId,
+ 'status' => 'queued',
+ 'message' => 'Submission export queued. Poll get_submission_export until it is completed or failed.',
+ ];
+ }
+
+ /** @return array<string, mixed> */
+ public function exportStatus(User $user, int $formId, string $jobId): array
+ {
+ $form = $this->forms->form($user, $formId);
+ $job = Cache::get($this->exports->getCacheKey($jobId));
+
+ if (! is_array($job)
+ || (int) ($job['user_id'] ?? 0) !== $user->id
+ || (int) ($job['form_id'] ?? 0) !== $form->id) {
+ throw ValidationException::withMessages([
+ 'job_id' => ['Export not found, expired, or not accessible.'],
+ ]);
+ }
+
+ return [
+ 'job_id' => $jobId,
+ 'status' => $job['status'],
+ 'progress' => $job['progress'],
+ 'processed_submissions' => $job['processed_submissions'] ?? null,
+ 'total_submissions' => $job['total_submissions'] ?? null,
+ 'file_url' => $job['file_url'] ?? null,
+ 'expires_at' => $job['expires_at'] ?? null,
+ 'error_message' => $job['error_message'] ?? null,
+ ];
+ }
+
+ /** @return array<string, mixed> */
+ private function serialize(Form $form, FormSubmission $submission): array
+ {
+ $responses = (new FormSubmissionFormatter($form, $submission->data ?? []))
+ ->showHiddenFields()
+ ->showRemovedFields()
+ ->useSignedUrlForFiles()
+ ->getCleanKeyValue();
+
+ $result = [
+ 'id' => $submission->id,
+ 'form_id' => $form->id,
+ 'status' => $submission->status,
+ 'created_at' => $submission->created_at?->toISOString(),
+ 'updated_at' => $submission->updated_at?->toISOString(),
+ 'completion_time_seconds' => $submission->completion_time,
+ 'responses' => $responses,
+ ];
+
+ if ($form->enable_ip_tracking
+ && $form->workspace->hasFeature('enable_ip_tracking')
+ && ! empty($submission->meta['ip_address'] ?? null)) {
+ $result['ip_address'] = $submission->meta['ip_address'];
+ }
+
+ return $result;
+ }
+
+ private function submissionQuery(
+ Form $form,
+ string $status,
+ ?string $dateFrom,
+ ?string $dateTo,
+ ): Builder {
+ return $form->submissions()->getQuery()
+ ->when($status === 'completed', fn (Builder $query) => $query->where('status', FormSubmission::STATUS_COMPLETED))
+ ->when($status === 'partial', fn (Builder $query) => $query->where('status', FormSubmission::STATUS_PARTIAL))
+ ->when($dateFrom, fn (Builder $query) => $query->whereDate('created_at', '>=', $dateFrom))
+ ->when($dateTo, fn (Builder $query) => $query->whereDate('created_at', '<=', $dateTo));
+ }
+}
diff --git a/api/app/Service/OAuth/McpOAuthSessionService.php b/api/app/Service/OAuth/McpOAuthSessionService.php
new file mode 100644
index 000000000..ef02a5ffc
--- /dev/null
+++ b/api/app/Service/OAuth/McpOAuthSessionService.php
@@ -0,0 +1,131 @@
+<?php
+
+namespace App\Service\OAuth;
+
+use App\Models\User;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Str;
+use RuntimeException;
+use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
+use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
+
+class McpOAuthSessionService
+{
+ private const AUTHORIZATION_REQUEST_PREFIX = 'mcp:oauth:authorization-request:';
+
+ private const LOGIN_TICKET_PREFIX = 'mcp:oauth:login-ticket:';
+
+ public function beginAuthorization(Request $request): string
+ {
+ $frontUrl = rtrim((string) config('app.front_url'), '/');
+ if (! filter_var($frontUrl, FILTER_VALIDATE_URL)) {
+ throw new RuntimeException('FRONT_URL must be configured to use MCP OAuth.');
+ }
+
+ $token = Str::random(64);
+
+ Cache::put(
+ self::AUTHORIZATION_REQUEST_PREFIX.hash('sha256', $token),
+ $request->getRequestUri(),
+ now()->addMinutes(10)
+ );
+
+ return $frontUrl.'/mcp/authorize?request='.rawurlencode($token);
+ }
+
+ public function issueLoginTicket(string $authorizationRequestToken, User $user): string
+ {
+ $requestUri = $this->pullOnce(
+ self::AUTHORIZATION_REQUEST_PREFIX.hash('sha256', $authorizationRequestToken)
+ );
+
+ if (! is_string($requestUri) || ! $this->isAuthorizationRequestUri($requestUri)) {
+ throw new BadRequestHttpException('This OAuth authorization request is invalid or has expired.');
+ }
+
+ $ticket = Str::random(64);
+
+ Cache::put(
+ self::LOGIN_TICKET_PREFIX.hash('sha256', $ticket),
+ [
+ 'user_id' => $user->getAuthIdentifier(),
+ 'request_uri' => $this->removeQueryParameter($requestUri, 'mcp_login_ticket'),
+ ],
+ now()->addMinutes(5)
+ );
+
+ return url($this->appendQueryParameter($requestUri, 'mcp_login_ticket', $ticket));
+ }
+
+ public function consumeLoginTicket(string $ticket, Request $request): void
+ {
+ $ticketData = $this->pullOnce(self::LOGIN_TICKET_PREFIX.hash('sha256', $ticket));
+ $expectedRequestUri = is_array($ticketData) ? ($ticketData['request_uri'] ?? null) : null;
+ $userId = is_array($ticketData) ? ($ticketData['user_id'] ?? null) : null;
+
+ if ((! is_int($userId) && ! is_string($userId))
+ || ! is_string($expectedRequestUri)
+ || ! hash_equals(
+ $expectedRequestUri,
+ $this->removeQueryParameter($request->getRequestUri(), 'mcp_login_ticket')
+ )) {
+ throw new AccessDeniedHttpException('This MCP login ticket is invalid or has expired.');
+ }
+
+ Auth::guard('web')->loginUsingId($userId);
+ $request->session()->regenerate();
+ }
+
+ public function withoutLoginTicket(Request $request): string
+ {
+ $query = $request->query();
+ unset($query['mcp_login_ticket']);
+
+ return $request->url().($query === [] ? '' : '?'.http_build_query($query));
+ }
+
+ private function isAuthorizationRequestUri(string $uri): bool
+ {
+ $parts = parse_url($uri);
+ $expectedPath = '/'.trim((string) config('passport.path', 'oauth'), '/').'/authorize';
+
+ return is_array($parts)
+ && ($parts['path'] ?? null) === $expectedPath
+ && isset($parts['query']);
+ }
+
+ private function appendQueryParameter(string $uri, string $name, string $value): string
+ {
+ $separator = str_contains($uri, '?') ? '&' : '?';
+
+ return $uri.$separator.rawurlencode($name).'='.rawurlencode($value);
+ }
+
+ private function removeQueryParameter(string $uri, string $name): string
+ {
+ $parts = parse_url($uri);
+ parse_str((string) ($parts['query'] ?? ''), $query);
+ unset($query[$name]);
+
+ $path = (string) ($parts['path'] ?? '');
+
+ return $path.($query === [] ? '' : '?'.http_build_query($query));
+ }
+
+ private function pullOnce(string $key): mixed
+ {
+ $lock = Cache::lock('mcp:oauth:consume:'.hash('sha256', $key), 5);
+
+ if (! $lock->get()) {
+ return null;
+ }
+
+ try {
+ return Cache::pull($key);
+ } finally {
+ $lock->release();
+ }
+ }
+}
diff --git a/api/app/Service/OAuth/McpPassportClientRepository.php b/api/app/Service/OAuth/McpPassportClientRepository.php
new file mode 100644
index 000000000..2649a4b50
--- /dev/null
+++ b/api/app/Service/OAuth/McpPassportClientRepository.php
@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Service\OAuth;
+
+use Laravel\Passport\Client;
+use Laravel\Passport\ClientRepository;
+
+class McpPassportClientRepository extends ClientRepository
+{
+ /**
+ * Compatibility bridge for Laravel MCP dynamic registration on Passport 12.
+ *
+ * Passport 13 cannot coexist with OpnForm's current JWT dependency because
+ * they require incompatible major versions of lcobucci/jwt.
+ *
+ * @param array<int, string> $redirectUris
+ */
+ public function createAuthorizationCodeGrantClient(
+ string $name,
+ array $redirectUris,
+ bool $confidential,
+ bool $enableDeviceFlow
+ ): Client {
+ $client = $this->create(
+ null,
+ $name,
+ implode(',', $redirectUris),
+ null,
+ false,
+ false,
+ $confidential
+ );
+
+ // Laravel MCP uses Passport 13's response attributes. Keep them
+ // in-memory while Passport 12 persists its equivalent redirect field.
+ $client->setAttribute('redirect_uris', $redirectUris);
+ $client->setAttribute('grant_types', ['authorization_code', 'refresh_token']);
+
+ return $client;
+ }
+}
diff --git a/api/app/Service/Telemetry/TelemetryEvent.php b/api/app/Service/Telemetry/TelemetryEvent.php
index 14238ef78..5d2a4aa89 100644
--- a/api/app/Service/Telemetry/TelemetryEvent.php
+++ b/api/app/Service/Telemetry/TelemetryEvent.php
@@ -10,6 +10,7 @@ enum TelemetryEvent: string
case FORM_CREATED = 'form.created';
case WORKSPACE_CREATED = 'workspace.created';
case FORM_SUBMISSION = 'form.submission';
+ case MCP_REQUEST = 'mcp.request';
case TWO_FACTOR_ENABLED = 'two_factor.enabled';
case SSO_CREATED = 'sso.created';
diff --git a/api/app/Support/Mcp/McpAvailability.php b/api/app/Support/Mcp/McpAvailability.php
new file mode 100644
index 000000000..f09152b99
--- /dev/null
+++ b/api/app/Support/Mcp/McpAvailability.php
@@ -0,0 +1,79 @@
+<?php
+
+namespace App\Support\Mcp;
+
+use App\Enums\SettingsKey;
+use App\Models\Setting;
+
+final class McpAvailability
+{
+ public function __construct(private readonly McpOAuthReadiness $readiness)
+ {
+ }
+
+ public function enabled(): bool
+ {
+ if (! config('app.self_hosted')) {
+ return true;
+ }
+
+ return $this->resolveEnabled($this->configuredValue());
+ }
+
+ public function configuredValue(): ?bool
+ {
+ $stored = Setting::get(SettingsKey::MCP_ENABLED);
+
+ return is_bool($stored) ? $stored : null;
+ }
+
+ public function available(): bool
+ {
+ if (! config('app.self_hosted')) {
+ return true;
+ }
+
+ return $this->enabled() && $this->readiness->inspect()['ready'];
+ }
+
+ /**
+ * Return a consistent settings-page snapshot without repeating database and
+ * OAuth readiness checks during the same request.
+ *
+ * @param array{ready: bool, blockers: array<int, array{code: string, message: string}>}|null $readiness
+ * @return array{enabled: bool, available: bool, configured_value: ?bool, ready: bool, blockers: array<int, array{code: string, message: string}>}
+ */
+ public function status(?array $readiness = null): array
+ {
+ if (! config('app.self_hosted')) {
+ return [
+ 'enabled' => true,
+ 'available' => true,
+ 'configured_value' => null,
+ 'ready' => true,
+ 'blockers' => [],
+ ];
+ }
+
+ $configuredValue = $this->configuredValue();
+ $enabled = $this->resolveEnabled($configuredValue);
+ $readiness ??= $this->readiness->inspect();
+
+ return [
+ 'enabled' => $enabled,
+ 'available' => $enabled && $readiness['ready'],
+ 'configured_value' => $configuredValue,
+ ...$readiness,
+ ];
+ }
+
+ public function guestDraftsEnabled(): bool
+ {
+ return ! config('app.self_hosted') && $this->enabled();
+ }
+
+ private function resolveEnabled(?bool $configuredValue): bool
+ {
+ return $configuredValue ?? (bool) config('opnform.mcp.enabled', false);
+ }
+}
diff --git a/api/app/Support/Mcp/McpConnectionConfiguration.php b/api/app/Support/Mcp/McpConnectionConfiguration.php
new file mode 100644
index 000000000..ce3b4b6fd
--- /dev/null
+++ b/api/app/Support/Mcp/McpConnectionConfiguration.php
@@ -0,0 +1,63 @@
+<?php
+
+namespace App\Support\Mcp;
+
+final class McpConnectionConfiguration
+{
+ /**
+ * @return array{
+ * server_url: string,
+ * settings_url: string,
+ * snippets: array{cursor: string, claude_code: string, chatgpt: string, codex: string, other: string, portable: string},
+ * install_urls: array{cursor: string}
+ * }
+ */
+ public function forSelfHostedInstance(): array
+ {
+ $appUrl = rtrim((string) config('app.url'), '/');
+ $serverUrl = $appUrl.'/mcp';
+
+ return [
+ 'server_url' => $serverUrl,
+ 'settings_url' => front_url('/?user-settings=mcp'),
+ 'snippets' => [
+ 'cursor' => $this->json([
+ 'mcpServers' => [
+ 'opnform' => [
+ 'url' => $serverUrl,
+ ],
+ ],
+ ]),
+ 'claude_code' => 'claude mcp add --transport http opnform '.escapeshellarg($serverUrl),
+ 'chatgpt' => "Server URL: {$serverUrl}\nAuthentication: OAuth",
+ 'codex' => 'codex mcp add opnform --url '.escapeshellarg($serverUrl),
+ 'other' => $this->json([
+ 'mcpServers' => [
+ 'opnform' => [
+ 'type' => 'http',
+ 'url' => $serverUrl,
+ ],
+ ],
+ ]),
+ 'portable' => $this->json([
+ '$schema' => 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json',
+ 'mcpServers' => [
+ 'opnform' => [
+ 'type' => 'streamable-http',
+ 'url' => $serverUrl,
+ ],
+ ],
+ ]),
+ ],
+ 'install_urls' => [
+ 'cursor' => 'cursor://anysphere.cursor-deeplink/mcp/install?name=opnform&config='.
+ rawurlencode(base64_encode($this->json(['url' => $serverUrl]))),
+ ],
+ ];
+ }
+
+ private function json(array $value): string
+ {
+ return json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
+ }
+}
diff --git a/api/app/Support/Mcp/McpOAuthKeyValidator.php b/api/app/Support/Mcp/McpOAuthKeyValidator.php
new file mode 100644
index 000000000..dd6ba179c
--- /dev/null
+++ b/api/app/Support/Mcp/McpOAuthKeyValidator.php
@@ -0,0 +1,70 @@
+<?php
+
+namespace App\Support\Mcp;
+
+use Laravel\Passport\Passport;
+
+final class McpOAuthKeyValidator
+{
+ /**
+ * @return array<int, array{code: string, message: string}>
+ */
+ public function blockers(bool $environmentOnly = false): array
+ {
+ $privateKey = $this->configuredKey('private');
+ $publicKey = $this->configuredKey('public');
+
+ if ($privateKey === null && $publicKey === null && ! $environmentOnly) {
+ $privateKey = $this->storedKey('private');
+ $publicKey = $this->storedKey('public');
+ }
+
+ if ($privateKey === null || $publicKey === null) {
+ return [[
+ 'code' => 'passport_keys_missing',
+ 'message' => $environmentOnly
+ ? 'MCP OAuth requires both PASSPORT_PRIVATE_KEY and PASSPORT_PUBLIC_KEY.'
+ : 'MCP OAuth requires both PASSPORT_PRIVATE_KEY and PASSPORT_PUBLIC_KEY, or a complete Passport key pair in storage.',
+ ]];
+ }
+
+ $private = openssl_pkey_get_private($privateKey);
+ $public = openssl_pkey_get_public($publicKey);
+ if ($private === false || $public === false) {
+ return [[
+ 'code' => 'passport_keys_invalid',
+ 'message' => 'The configured Passport key pair is not valid PEM.',
+ ]];
+ }
+
+ $privateDetails = openssl_pkey_get_details($private);
+ $publicDetails = openssl_pkey_get_details($public);
+ if (! is_array($privateDetails)
+ || ! is_array($publicDetails)
+ || ! hash_equals($privateDetails['key'], $publicDetails['key'])) {
+ return [[
+ 'code' => 'passport_keys_mismatched',
+ 'message' => 'The configured Passport private and public keys do not belong to the same pair.',
+ ]];
+ }
+
+ return [];
+ }
+
+ private function configuredKey(string $type): ?string
+ {
+ $configured = config("passport.{$type}_key");
+ if (is_string($configured) && trim($configured) !== '') {
+ return str_replace('\\n', "\n", $configured);
+ }
+
+ return null;
+ }
+
+ private function storedKey(string $type): ?string
+ {
+ $path = Passport::keyPath("oauth-{$type}.key");
+
+ return is_file($path) ? file_get_contents($path) ?: null : null;
+ }
+}
diff --git a/api/app/Support/Mcp/McpOAuthReadiness.php b/api/app/Support/Mcp/McpOAuthReadiness.php
new file mode 100644
index 000000000..7ce952303
--- /dev/null
+++ b/api/app/Support/Mcp/McpOAuthReadiness.php
@@ -0,0 +1,70 @@
+<?php
+
+namespace App\Support\Mcp;
+
+final class McpOAuthReadiness
+{
+ public function __construct(private readonly McpOAuthKeyValidator $keys)
+ {
+ }
+
+ /**
+ * @return array{ready: bool, blockers: array<int, array{code: string, message: string}>}
+ */
+ public function inspect(): array
+ {
+ $blockers = [];
+
+ if (! config('oauth.enabled', false)) {
+ $blockers[] = [
+ 'code' => 'oauth_disabled',
+ 'message' => 'Delegated OAuth is disabled by OAUTH_ENABLED.',
+ ];
+ }
+
+ foreach ([
+ 'APP_URL' => config('app.url'),
+ 'FRONT_URL' => config('app.front_url'),
+ ] as $name => $url) {
+ if (! $this->isSupportedPublicUrl($url)) {
+ $blockers[] = [
+ 'code' => strtolower($name).'_invalid',
+ 'message' => "{$name} must be an HTTPS base URL without credentials, query parameters, or fragments, or an HTTP loopback URL for local development.",
+ ];
+ }
+ }
+
+ $blockers = array_merge($blockers, $this->keys->blockers());
+
+ return [
+ 'ready' => $blockers === [],
+ 'blockers' => $blockers,
+ ];
+ }
+
+ private function isSupportedPublicUrl(mixed $value): bool
+ {
+ if (! is_string($value) || filter_var($value, FILTER_VALIDATE_URL) === false) {
+ return false;
+ }
+
+ $parts = parse_url($value);
+ if (! is_array($parts)
+ || isset($parts['user'])
+ || isset($parts['pass'])
+ || isset($parts['query'])
+ || isset($parts['fragment'])
+ ) {
+ return false;
+ }
+
+ $scheme = strtolower((string) ($parts['scheme'] ?? ''));
+ if ($scheme === 'https') {
+ return true;
+ }
+
+ $host = strtolower(trim((string) ($parts['host'] ?? ''), '[]'));
+
+ return $scheme === 'http' && in_array($host, ['localhost', '127.0.0.1', '::1'], true);
+ }
+}
diff --git a/api/composer.json b/api/composer.json
index 28bf40b8a..7c13884aa 100644
--- a/api/composer.json
+++ b/api/composer.json
@@ -26,6 +26,8 @@
"laravel/cashier": "*",
"laravel/framework": "^11.9",
"laravel/horizon": "*",
+ "laravel/mcp": "^0.8.2",
+ "laravel/passport": "^12.4",
"laravel/sanctum": "^4.0",
"laravel/socialite": "*",
"laravel/tinker": "^2.9",
diff --git a/api/composer.lock b/api/composer.lock
index 62e4d3735..3ec2e2f8a 100644
--- a/api/composer.lock
+++ b/api/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": "961af48ddfce7334fd40697a96d42b50",
+ "content-hash": "bc379d303aea32fd8c42afd5db155ba1",
"packages": [
{
"name": "aws/aws-crt-php",
@@ -613,6 +613,73 @@
},
"time": "2025-09-16T12:23:56+00:00"
},
+ {
+ "name": "defuse/php-encryption",
+ "version": "v2.4.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/defuse/php-encryption.git",
+ "reference": "f53396c2d34225064647a05ca76c1da9d99e5828"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/defuse/php-encryption/zipball/f53396c2d34225064647a05ca76c1da9d99e5828",
+ "reference": "f53396c2d34225064647a05ca76c1da9d99e5828",
+ "shasum": ""
+ },
+ "require": {
+ "ext-openssl": "*",
+ "paragonie/random_compat": ">= 2",
+ "php": ">=5.6.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^5|^6|^7|^8|^9|^10",
+ "yoast/phpunit-polyfills": "^2.0.0"
+ },
+ "bin": [
+ "bin/generate-defuse-key"
+ ],
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "Defuse\\Crypto\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Taylor Hornby",
+ "email": "[email protected]",
+ "homepage": "https://defuse.ca/"
+ },
+ {
+ "name": "Scott Arciszewski",
+ "email": "[email protected]",
+ "homepage": "https://paragonie.com"
+ }
+ ],
+ "description": "Secure PHP Encryption Library",
+ "keywords": [
+ "aes",
+ "authenticated encryption",
+ "cipher",
+ "crypto",
+ "cryptography",
+ "encrypt",
+ "encryption",
+ "openssl",
+ "security",
+ "symmetric key cryptography"
+ ],
+ "support": {
+ "issues": "https://github.com/defuse/php-encryption/issues",
+ "source": "https://github.com/defuse/php-encryption/tree/v2.4.0"
+ },
+ "time": "2023-06-19T06:10:36+00:00"
+ },
{
"name": "dflydev/dot-access-data",
"version": "v3.0.3",
@@ -2412,6 +2479,53 @@
},
"time": "2021-12-07T10:10:20+00:00"
},
+ {
+ "name": "illuminate/json-schema",
+ "version": "v12.66.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/illuminate/json-schema.git",
+ "reference": "543aab5a872b6b08f3b8c907064b009b84a56e07"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/illuminate/json-schema/zipball/543aab5a872b6b08f3b8c907064b009b84a56e07",
+ "reference": "543aab5a872b6b08f3b8c907064b009b84a56e07",
+ "shasum": ""
+ },
+ "require": {
+ "illuminate/contracts": "^10.50.0|^11.47.0|^12.40.2",
+ "php": "^8.1"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "12.x-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Illuminate\\JsonSchema\\": ""
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Taylor Otwell",
+ "email": "[email protected]"
+ }
+ ],
+ "description": "The Illuminate Json Schema package.",
+ "homepage": "https://laravel.com",
+ "support": {
+ "issues": "https://github.com/laravel/framework/issues",
+ "source": "https://github.com/laravel/framework"
+ },
+ "time": "2026-06-16T14:57:46+00:00"
+ },
{
"name": "jane-php/json-schema-runtime",
"version": "v7.10.4",
@@ -3257,6 +3371,156 @@
},
"time": "2026-02-10T18:18:08+00:00"
},
+ {
+ "name": "laravel/mcp",
+ "version": "v0.8.2",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/laravel/mcp.git",
+ "reference": "0c32bf369c6432cab21458f9f4479da33a49ba37"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/laravel/mcp/zipball/0c32bf369c6432cab21458f9f4479da33a49ba37",
+ "reference": "0c32bf369c6432cab21458f9f4479da33a49ba37",
+ "shasum": ""
+ },
+ "require": {
+ "ext-json": "*",
+ "ext-mbstring": "*",
+ "illuminate/console": "^11.45.3|^12.41.1|^13.0",
+ "illuminate/container": "^11.45.3|^12.41.1|^13.0",
+ "illuminate/contracts": "^11.45.3|^12.41.1|^13.0",
+ "illuminate/http": "^11.45.3|^12.41.1|^13.0",
+ "illuminate/json-schema": "^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",
+ "illuminate/validation": "^11.45.3|^12.41.1|^13.0",
+ "php": "^8.2",
+ "symfony/process": "^7.4.5|^8.0.5"
+ },
+ "require-dev": {
+ "laravel/pint": "^1.20",
+ "orchestra/testbench": "^9.15|^10.8|^11.0",
+ "pestphp/pest": "^3.8.5|^4.3.2",
+ "phpstan/phpstan": "^2.1.27",
+ "rector/rector": "^2.2.4"
+ },
+ "type": "library",
+ "extra": {
+ "laravel": {
+ "aliases": {
+ "Mcp": "Laravel\\Mcp\\Facades\\Mcp"
+ },
+ "providers": [
+ "Laravel\\Mcp\\Server\\McpServiceProvider"
+ ]
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Laravel\\Mcp\\": "src/",
+ "Laravel\\Mcp\\Server\\": "src/Server/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Taylor Otwell",
+ "email": "[email protected]"
+ }
+ ],
+ "description": "Rapidly build MCP servers for your Laravel applications.",
+ "homepage": "https://github.com/laravel/mcp",
+ "keywords": [
+ "laravel",
+ "mcp"
+ ],
+ "support": {
+ "issues": "https://github.com/laravel/mcp/issues",
+ "source": "https://github.com/laravel/mcp"
+ },
+ "time": "2026-06-25T14:00:45+00:00"
+ },
+ {
+ "name": "laravel/passport",
+ "version": "v12.4.3",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/laravel/passport.git",
+ "reference": "1d2e0170a52f150d5c35c9a6fc1f7ccebcde7626"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/laravel/passport/zipball/1d2e0170a52f150d5c35c9a6fc1f7ccebcde7626",
+ "reference": "1d2e0170a52f150d5c35c9a6fc1f7ccebcde7626",
+ "shasum": ""
+ },
+ "require": {
+ "ext-json": "*",
+ "firebase/php-jwt": "^6.4|^7.0",
+ "illuminate/auth": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/console": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/container": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/contracts": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/cookie": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/database": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/encryption": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/http": "^9.21|^10.0|^11.0|^12.0",
+ "illuminate/support": "^9.21|^10.0|^11.0|^12.0",
+ "lcobucci/jwt": "^4.3|^5.0",
+ "league/oauth2-server": "^8.5.3",
+ "nyholm/psr7": "^1.5",
+ "php": "^8.0",
+ "phpseclib/phpseclib": "^2.0|^3.0",
+ "symfony/console": "^6.0|^7.0",
+ "symfony/psr-http-message-bridge": "^2.1|^6.0|^7.0"
+ },
+ "require-dev": {
+ "mockery/mockery": "^1.0",
+ "orchestra/testbench": "^7.35|^8.14|^9.0|^10.0",
+ "phpstan/phpstan": "^1.10",
+ "phpunit/phpunit": "^9.3|^10.5|^11.5"
+ },
+ "type": "library",
+ "extra": {
+ "laravel": {
+ "providers": [
+ "Laravel\\Passport\\PassportServiceProvider"
+ ]
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "Laravel\\Passport\\": "src/",
+ "Laravel\\Passport\\Database\\Factories\\": "database/factories/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Taylor Otwell",
+ "email": "[email protected]"
+ }
+ ],
+ "description": "Laravel Passport provides OAuth2 server support to Laravel.",
+ "keywords": [
+ "laravel",
+ "oauth",
+ "passport"
+ ],
+ "support": {
+ "issues": "https://github.com/laravel/passport/issues",
+ "source": "https://github.com/laravel/passport"
+ },
+ "time": "2026-02-19T14:14:05+00:00"
+ },
{
"name": "laravel/prompts",
"version": "v0.3.13",
@@ -4117,6 +4381,60 @@
],
"time": "2022-12-11T20:36:23+00:00"
},
+ {
+ "name": "league/event",
+ "version": "2.3.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/thephpleague/event.git",
+ "reference": "062ebb450efbe9a09bc2478e89b7c933875b0935"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/thephpleague/event/zipball/062ebb450efbe9a09bc2478e89b7c933875b0935",
+ "reference": "062ebb450efbe9a09bc2478e89b7c933875b0935",
+ "shasum": ""
+ },
+ "require": {
+ "php": ">=7.1.0"
+ },
+ "require-dev": {
+ "henrikbjorn/phpspec-code-coverage": "~1.0.1",
+ "phpspec/phpspec": "^2.2"
+ },
+ "type": "library",
+ "extra": {
+ "branch-alias": {
+ "dev-master": "2.2-dev"
+ }
+ },
+ "autoload": {
+ "psr-4": {
+ "League\\Event\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Frank de Jonge",
+ "email": "[email protected]"
+ }
+ ],
+ "description": "Event package",
+ "keywords": [
+ "emitter",
+ "event",
+ "listener"
+ ],
+ "support": {
+ "issues": "https://github.com/thephpleague/event/issues",
+ "source": "https://github.com/thephpleague/event/tree/2.3.0"
+ },
+ "time": "2025-03-14T19:51:10+00:00"
+ },
{
"name": "league/flysystem",
"version": "3.31.0",
@@ -4436,6 +4754,94 @@
},
"time": "2024-12-10T19:59:05+00:00"
},
+ {
+ "name": "league/oauth2-server",
+ "version": "8.5.5",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/thephpleague/oauth2-server.git",
+ "reference": "cc8778350f905667e796b3c2364a9d3bd7a73518"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/thephpleague/oauth2-server/zipball/cc8778350f905667e796b3c2364a9d3bd7a73518",
+ "reference": "cc8778350f905667e796b3c2364a9d3bd7a73518",
+ "shasum": ""
+ },
+ "require": {
+ "defuse/php-encryption": "^2.3",
+ "ext-openssl": "*",
+ "lcobucci/clock": "^2.2 || ^3.0",
+ "lcobucci/jwt": "^4.3 || ^5.0",
+ "league/event": "^2.2",
+ "league/uri": "^6.7 || ^7.0",
+ "php": "^8.0",
+ "psr/http-message": "^1.0.1 || ^2.0"
+ },
+ "replace": {
+ "league/oauth2server": "*",
+ "lncd/oauth2": "*"
+ },
+ "require-dev": {
+ "laminas/laminas-diactoros": "^3.0.0",
+ "phpstan/phpstan": "^0.12.57",
+ "phpstan/phpstan-phpunit": "^0.12.16",
+ "phpunit/phpunit": "^9.6.6",
+ "roave/security-advisories": "dev-master"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "League\\OAuth2\\Server\\": "src/"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "authors": [
+ {
+ "name": "Alex Bilbie",
+ "email": "[email protected]",
+ "homepage": "http://www.alexbilbie.com",
+ "role": "Developer"
+ },
+ {
+ "name": "Andy Millington",
+ "email": "[email protected]",
+ "homepage": "https://www.noexceptions.io",
+ "role": "Developer"
+ }
+ ],
+ "description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.",
+ "homepage": "https://oauth2.thephpleague.com/",
+ "keywords": [
+ "Authentication",
+ "api",
+ "auth",
+ "authorisation",
+ "authorization",
+ "oauth",
+ "oauth 2",
+ "oauth 2.0",
+ "oauth2",
+ "protect",
+ "resource",
+ "secure",
+ "server"
+ ],
+ "support": {
+ "issues": "https://github.com/thephpleague/oauth2-server/issues",
+ "source": "https://github.com/thephpleague/oauth2-server/tree/8.5.5"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/sephster",
+ "type": "github"
+ }
+ ],
+ "time": "2024-12-20T23:06:10+00:00"
+ },
{
"name": "league/uri",
"version": "7.8.0",
@@ -16862,5 +17268,5 @@
"ext-pcntl": "8.0",
"ext-posix": "8.0"
},
- "plugin-api-version": "2.9.0"
+ "plugin-api-version": "2.6.0"
}
diff --git a/api/config/app.php b/api/config/app.php
index af6a062d2..78aa9ddc9 100644
--- a/api/config/app.php
+++ b/api/config/app.php
@@ -238,6 +238,7 @@ return [
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
+ App\Providers\OAuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\HorizonServiceProvider::class,
diff --git a/api/config/auth.php b/api/config/auth.php
index 78085d4bd..1e1337728 100644
--- a/api/config/auth.php
+++ b/api/config/auth.php
@@ -46,6 +46,11 @@ return [
'provider' => 'users',
'hash' => false,
],
+
+ 'oauth' => [
+ 'driver' => 'passport',
+ 'provider' => 'users',
+ ],
],
/*
diff --git a/api/config/mcp.php b/api/config/mcp.php
new file mode 100644
index 000000000..7530f250e
--- /dev/null
+++ b/api/config/mcp.php
@@ -0,0 +1,24 @@
+<?php
+
+$redirectDomains = array_values(array_filter(array_map(
+ 'trim',
+ explode(',', env('MCP_OAUTH_REDIRECT_DOMAINS', implode(',', [
+ 'https://chatgpt.com',
+ 'https://chat.openai.com',
+ 'https://claude.ai',
+ 'http://localhost',
+ 'http://127.0.0.1',
+ 'http://[::1]',
+ ])))
+)));
+
+$customSchemes = array_values(array_filter(array_map(
+ 'trim',
+ explode(',', env('MCP_OAUTH_CUSTOM_SCHEMES', 'chatgpt,claude,cursor,vscode'))
+)));
+
+return [
+ 'redirect_domains' => $redirectDomains,
+ 'custom_schemes' => $customSchemes,
+ 'authorization_server' => env('MCP_AUTHORIZATION_SERVER') ?: null,
+];
diff --git a/api/config/oauth.php b/api/config/oauth.php
new file mode 100644
index 000000000..2dc082443
--- /dev/null
+++ b/api/config/oauth.php
@@ -0,0 +1,25 @@
+<?php
+
+return [
+ /*
+ |--------------------------------------------------------------------------
+ | Delegated OAuth 2.1
+ |--------------------------------------------------------------------------
+ |
+ | Passport is reserved for third-party clients that need delegated access.
+ | It remains separate from the JWT used by the first-party frontend and
+ | from Sanctum personal access tokens.
+ |
+ */
+ // This controls whether the OAuth infrastructure is available. Runtime
+ // MCP access is gated separately by McpAvailability so self-hosted admins
+ // can toggle it without rebuilding Laravel's route cache.
+ 'enabled' => env('OAUTH_ENABLED', true),
+
+ 'access_token_ttl' => (int) env('OAUTH_ACCESS_TOKEN_TTL', 60 * 24 * 7),
+ 'refresh_token_ttl_days' => (int) env('OAUTH_REFRESH_TOKEN_TTL_DAYS', 30),
+
+ 'scopes' => [
+ 'mcp:use' => 'Use OpnForm MCP features to access the forms and submissions you explicitly ask the assistant to manage.',
+ ],
+];
diff --git a/api/config/opnform.php b/api/config/opnform.php
index fd2a61b6c..bd9fe6ae4 100644
--- a/api/config/opnform.php
+++ b/api/config/opnform.php
@@ -16,6 +16,20 @@ return [
'per_hour' => (int) env('PUBLIC_UPLOADS_RATE_LIMIT_PER_HOUR', 300),
],
],
+ 'mcp' => [
+ // Cloud instances expose MCP by default. Self-hosted instances must opt in.
+ 'enabled' => env('MCP_ENABLED', false),
+ 'observability_enabled' => env('MCP_OBSERVABILITY_ENABLED', true),
+ 'rate_limit' => [
+ 'per_minute' => (int) env('MCP_RATE_LIMIT_PER_MINUTE', 120),
+ 'per_hour' => (int) env('MCP_RATE_LIMIT_PER_HOUR', 3000),
+ 'draft_creates_per_minute' => (int) env('MCP_DRAFT_CREATES_PER_MINUTE', 20),
+ 'draft_creates_per_hour' => (int) env('MCP_DRAFT_CREATES_PER_HOUR', 200),
+ 'submission_exports_per_minute' => (int) env('MCP_SUBMISSION_EXPORTS_PER_MINUTE', 5),
+ 'submission_exports_per_hour' => (int) env('MCP_SUBMISSION_EXPORTS_PER_HOUR', 30),
+ ],
+ ],
+ 'form_summary_rate_limit_per_minute' => (int) env('FORM_SUMMARY_RATE_LIMIT_PER_MINUTE', 30),
'webhooks' => [
'allow_private_urls' => env('WEBHOOKS_ALLOW_PRIVATE_URLS', false),
],
diff --git a/api/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php b/api/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php
new file mode 100644
index 000000000..74bc85018
--- /dev/null
+++ b/api/database/migrations/2016_06_01_000001_create_oauth_auth_codes_table.php
@@ -0,0 +1,30 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::create('oauth_auth_codes', function (Blueprint $table) {
+ $table->string('id', 100)->primary();
+ $table->unsignedBigInteger('user_id')->index();
+ $table->unsignedBigInteger('client_id');
+ $table->text('scopes')->nullable();
+ $table->boolean('revoked');
+ $table->dateTime('expires_at')->nullable();
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('oauth_auth_codes');
+ }
+};
diff --git a/api/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php b/api/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php
new file mode 100644
index 000000000..659e37992
--- /dev/null
+++ b/api/database/migrations/2016_06_01_000002_create_oauth_access_tokens_table.php
@@ -0,0 +1,32 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::create('oauth_access_tokens', function (Blueprint $table) {
+ $table->string('id', 100)->primary();
+ $table->unsignedBigInteger('user_id')->nullable()->index();
+ $table->unsignedBigInteger('client_id');
+ $table->string('name')->nullable();
+ $table->text('scopes')->nullable();
+ $table->boolean('revoked');
+ $table->timestamps();
+ $table->dateTime('expires_at')->nullable();
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('oauth_access_tokens');
+ }
+};
diff --git a/api/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php b/api/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php
new file mode 100644
index 000000000..42769bc56
--- /dev/null
+++ b/api/database/migrations/2016_06_01_000003_create_oauth_refresh_tokens_table.php
@@ -0,0 +1,28 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::create('oauth_refresh_tokens', function (Blueprint $table) {
+ $table->string('id', 100)->primary();
+ $table->string('access_token_id', 100)->index();
+ $table->boolean('revoked');
+ $table->dateTime('expires_at')->nullable();
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('oauth_refresh_tokens');
+ }
+};
diff --git a/api/database/migrations/2016_06_01_000004_create_oauth_clients_table.php b/api/database/migrations/2016_06_01_000004_create_oauth_clients_table.php
new file mode 100644
index 000000000..dc66199ba
--- /dev/null
+++ b/api/database/migrations/2016_06_01_000004_create_oauth_clients_table.php
@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::create('oauth_clients', function (Blueprint $table) {
+ $table->bigIncrements('id');
+ $table->unsignedBigInteger('user_id')->nullable()->index();
+ $table->string('name');
+ $table->string('secret', 100)->nullable();
+ $table->string('provider')->nullable();
+ $table->text('redirect');
+ $table->boolean('personal_access_client');
+ $table->boolean('password_client');
+ $table->boolean('revoked');
+ $table->timestamps();
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('oauth_clients');
+ }
+};
diff --git a/api/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php b/api/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php
new file mode 100644
index 000000000..8c5b0166a
--- /dev/null
+++ b/api/database/migrations/2016_06_01_000005_create_oauth_personal_access_clients_table.php
@@ -0,0 +1,27 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::create('oauth_personal_access_clients', function (Blueprint $table) {
+ $table->bigIncrements('id');
+ $table->unsignedBigInteger('client_id');
+ $table->timestamps();
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::dropIfExists('oauth_personal_access_clients');
+ }
+};
diff --git a/api/database/migrations/2026_08_14_000000_create_agent_form_drafts_table.php b/api/database/migrations/2026_08_14_000000_create_agent_form_drafts_table.php
new file mode 100644
index 000000000..6206a1977
--- /dev/null
+++ b/api/database/migrations/2026_08_14_000000_create_agent_form_drafts_table.php
@@ -0,0 +1,29 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ public function up(): void
+ {
+ Schema::create('agent_form_drafts', function (Blueprint $table) {
+ $table->id();
+ $table->char('token_hash', 64)->unique();
+ $table->json('definition');
+ $table->unsignedSmallInteger('schema_version');
+ $table->unsignedInteger('version')->default(1);
+ $table->string('status', 20)->default('active')->index();
+ $table->foreignId('claimed_form_id')->nullable()->constrained('forms')->nullOnDelete();
+ $table->char('claim_receipt_hash', 64)->nullable()->unique();
+ $table->timestamp('claimed_at')->nullable();
+ $table->timestamp('expires_at')->index();
+ $table->timestamps();
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::dropIfExists('agent_form_drafts');
+ }
+};
diff --git a/api/database/migrations/2026_08_14_010000_add_editor_handoff_to_agent_form_drafts_table.php b/api/database/migrations/2026_08_14_010000_add_editor_handoff_to_agent_form_drafts_table.php
new file mode 100644
index 000000000..82c67f3e9
--- /dev/null
+++ b/api/database/migrations/2026_08_14_010000_add_editor_handoff_to_agent_form_drafts_table.php
@@ -0,0 +1,31 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ public function up(): void
+ {
+ Schema::table('agent_form_drafts', function (Blueprint $table) {
+ $table->char('handoff_token_hash', 64)->nullable()->unique();
+ $table->timestamp('handoff_expires_at')->nullable()->index();
+ $table->timestamp('handoff_consumed_at')->nullable();
+ $table->char('editor_session_hash', 64)->nullable()->unique();
+ $table->timestamp('editor_session_expires_at')->nullable()->index();
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::table('agent_form_drafts', function (Blueprint $table) {
+ $table->dropColumn([
+ 'handoff_token_hash',
+ 'handoff_expires_at',
+ 'handoff_consumed_at',
+ 'editor_session_hash',
+ 'editor_session_expires_at',
+ ]);
+ });
+ }
+};
diff --git a/api/database/migrations/2026_08_14_020000_make_agent_form_draft_handoffs_reusable.php b/api/database/migrations/2026_08_14_020000_make_agent_form_draft_handoffs_reusable.php
new file mode 100644
index 000000000..68ca39865
--- /dev/null
+++ b/api/database/migrations/2026_08_14_020000_make_agent_form_draft_handoffs_reusable.php
@@ -0,0 +1,40 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class () extends Migration {
+ public function up(): void
+ {
+ Schema::create('agent_form_draft_handoffs', function (Blueprint $table) {
+ $table->id();
+ $table->foreignId('agent_form_draft_id')->constrained()->cascadeOnDelete();
+ $table->char('token_hash', 64)->unique();
+ $table->timestamp('last_used_at')->nullable();
+ $table->timestamp('expires_at')->index();
+ $table->timestamps();
+ });
+
+ Schema::table('agent_form_drafts', function (Blueprint $table) {
+ $table->dropUnique(['handoff_token_hash']);
+ $table->dropIndex(['handoff_expires_at']);
+ $table->dropColumn([
+ 'handoff_token_hash',
+ 'handoff_expires_at',
+ 'handoff_consumed_at',
+ ]);
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::table('agent_form_drafts', function (Blueprint $table) {
+ $table->char('handoff_token_hash', 64)->nullable()->unique();
+ $table->timestamp('handoff_expires_at')->nullable()->index();
+ $table->timestamp('handoff_consumed_at')->nullable();
+ });
+
+ Schema::dropIfExists('agent_form_draft_handoffs');
+ }
+};
diff --git a/api/phpunit.xml b/api/phpunit.xml
index 0681a776c..7b874984f 100644
--- a/api/phpunit.xml
+++ b/api/phpunit.xml
@@ -12,6 +12,7 @@
<server name="APP_DEBUG" value="true"/>
<server name="APP_KEY" value="AckfSECXIvnK5r28GVIWUAxmbBSjTsmF"/>
<server name="APP_NAME" value="NotionForms TESTING"/>
+ <server name="APP_URL" value="http://localhost"/>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
diff --git a/api/resources/views/mcp/form-draft-preview-app.blade.php b/api/resources/views/mcp/form-draft-preview-app.blade.php
new file mode 100644
index 000000000..eacfe330c
--- /dev/null
+++ b/api/resources/views/mcp/form-draft-preview-app.blade.php
@@ -0,0 +1,204 @@
+<x-mcp::app title="OpnForm draft preview">
+ <x-slot:head>
+ <style>
+ :root { color-scheme: light dark; }
+ body { margin: 0; font-family: ui-sans-serif, system-ui, sans-serif; color: var(--color-text-primary, #111827); }
+ main { padding: 0; }
+ .preview-surface { border-radius: 14px; padding: 18px; background: var(--color-background-secondary, #f5f5f5); }
+ .header { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }
+ .heading { min-width: 0; }
+ .header-actions { display: flex; align-items: center; gap: 8px; }
+ .eyebrow { display: flex; align-items: center; gap: 8px; margin: 0 0 10px; color: var(--color-text-secondary, #4b5563); font-size: 13px; font-weight: 650; }
+ .eyebrow::before { width: 8px; height: 8px; border-radius: 999px; background: #3b82f6; content: ''; }
+ h1 { margin: 0 0 8px; font-size: 20px; }
+ .meta { margin: 0; color: var(--color-text-secondary, #6b7280); font-size: 13px; }
+ .zoom-controls { display: flex; align-items: center; overflow: hidden; border: 1px solid var(--color-border-primary, #d1d5db); border-radius: 8px; background: var(--color-background-primary, #fff); }
+ .zoom-button { display: grid; width: 32px; height: 32px; place-items: center; border: 0; border-radius: 0; padding: 0; background: transparent; color: var(--color-text-primary, #111827); font-size: 17px; font-weight: 500; cursor: pointer; }
+ .zoom-button:hover:not(:disabled), .zoom-value:hover { background: var(--color-background-secondary, #f3f4f6); }
+ .zoom-button:disabled { cursor: default; opacity: .35; }
+ .zoom-value { min-width: 46px; height: 32px; border: 0; border-right: 1px solid var(--color-border-primary, #d1d5db); border-left: 1px solid var(--color-border-primary, #d1d5db); border-radius: 0; padding: 0 6px; background: transparent; color: var(--color-text-secondary, #4b5563); font-size: 11px; font-variant-numeric: tabular-nums; cursor: pointer; }
+ .preview-viewport { width: 100%; margin-top: 18px; overflow: hidden; }
+ .preview-canvas { position: relative; margin: 0 auto; }
+ iframe { display: block; width: 1280px; height: 480px; border: 0; background: transparent; transform-origin: top left; }
+ ol { padding-left: 22px; margin: 18px 0; }
+ li { margin: 10px 0; }
+ .open-button { display: inline-flex; flex: none; height: 32px; align-items: center; border: 0; border-radius: 8px; padding: 0 10px; background: #2563eb; color: white; font-size: 12px; font-weight: 650; cursor: pointer; }
+ .open-button:disabled { cursor: wait; opacity: .6; }
+ .empty { color: var(--color-text-secondary, #6b7280); font-style: italic; }
+ @media (max-width: 520px) {
+ .preview-surface { padding: 14px; }
+ .header { align-items: stretch; flex-direction: column; }
+ .header-actions { justify-content: space-between; }
+ .eyebrow { margin-bottom: 8px; }
+ h1 { font-size: 17px; }
+ .open-button { padding: 6px 8px; }
+ }
+ </style>
+ <script type="module">
+ createMcpApp(async (app) => {
+ const title = document.getElementById('title');
+ const meta = document.getElementById('meta');
+ const fields = document.getElementById('fields');
+ const preview = document.getElementById('preview');
+ const previewViewport = document.getElementById('preview-viewport');
+ const previewCanvas = document.getElementById('preview-canvas');
+ const openButton = document.getElementById('open-editor');
+ const zoomOutButton = document.getElementById('zoom-out');
+ const zoomResetButton = document.getElementById('zoom-reset');
+ const zoomInButton = document.getElementById('zoom-in');
+ const canvasWidth = 1280;
+ const focusedHeight = 720;
+ const defaultZoom = 0.8;
+ const minimumZoom = 0.5;
+ const zoomStep = 0.1;
+ let requestedZoom = defaultZoom;
+ let naturalHeight = 480;
+ let presentationStyle = 'classic';
+ let resizeScriptPromise;
+
+ const applyPreviewLayout = () => {
+ const availableWidth = previewViewport.clientWidth;
+ const fitZoom = availableWidth > 0 ? Math.min(1, availableWidth / canvasWidth) : 1;
+ const effectiveMinimumZoom = Math.min(minimumZoom, fitZoom);
+ const zoom = Math.max(effectiveMinimumZoom, Math.min(requestedZoom, fitZoom));
+ const height = presentationStyle === 'focused' ? focusedHeight : naturalHeight;
+ preview.style.width = `${canvasWidth}px`;
+ preview.style.height = `${height}px`;
+ preview.style.transform = `scale(${zoom})`;
+ previewCanvas.style.width = `${canvasWidth * zoom}px`;
+ previewCanvas.style.height = `${height * zoom}px`;
+ zoomResetButton.textContent = `${Math.round(zoom * 100)}%`;
+ zoomOutButton.disabled = zoom <= effectiveMinimumZoom;
+ zoomInButton.disabled = zoom >= fitZoom;
+ };
+
+ zoomOutButton.onclick = () => {
+ const currentZoom = Number.parseInt(zoomResetButton.textContent, 10) / 100;
+ requestedZoom = Math.max(0.1, currentZoom - zoomStep);
+ applyPreviewLayout();
+ };
+ zoomResetButton.onclick = () => {
+ requestedZoom = defaultZoom;
+ applyPreviewLayout();
+ };
+ zoomInButton.onclick = () => {
+ const currentZoom = Number.parseInt(zoomResetButton.textContent, 10) / 100;
+ requestedZoom = Math.min(1, currentZoom + zoomStep);
+ applyPreviewLayout();
+ };
+
+ new ResizeObserver(applyPreviewLayout).observe(previewViewport);
+
+ const loadIframeResizer = (origin) => {
+ if (window.iFrameResize) {
+ return Promise.resolve();
+ }
+
+ if (!resizeScriptPromise) {
+ resizeScriptPromise = new Promise((resolve, reject) => {
+ const script = document.createElement('script');
+ script.src = `${origin}/widgets/iframeResize.min.js`;
+ script.onload = resolve;
+ script.onerror = reject;
+ document.head.appendChild(script);
+ });
+ }
+
+ return resizeScriptPromise;
+ };
+
+ app.onToolResult((result) => {
+ const payload = result?.structuredContent ?? result?.structured_content ?? {};
+ const draft = payload.draft ?? {};
+ const definition = draft.definition ?? {};
+ presentationStyle = definition.presentation_style ?? 'classic';
+ title.textContent = definition.title ?? 'Untitled form';
+ meta.textContent = `Draft v${draft.version ?? '?'} · ${presentationStyle} layout`;
+ applyPreviewLayout();
+ if (payload.preview_url) {
+ const previewUrl = new URL(payload.preview_url);
+ previewUrl.searchParams.set('embedded', '1');
+ preview.src = previewUrl.toString();
+ preview.hidden = false;
+ previewViewport.hidden = false;
+ applyPreviewLayout();
+ fields.hidden = true;
+ loadIframeResizer(previewUrl.origin).then(() => {
+ if (!preview.iFrameResizer) {
+ window.iFrameResize({
+ checkOrigin: [previewUrl.origin],
+ log: false,
+ scrolling: false,
+ sizeHeight: presentationStyle !== 'focused',
+ onResized: ({ height }) => {
+ if (presentationStyle === 'classic') {
+ naturalHeight = height;
+ applyPreviewLayout();
+ }
+ },
+ }, preview);
+ }
+ }).catch(() => {
+ preview.style.overflow = 'auto';
+ });
+ }
+ fields.replaceChildren();
+
+ const visibleFields = (definition.properties ?? []).filter((field) => !field.hidden);
+ if (visibleFields.length === 0) {
+ fields.innerHTML = '<li class="empty">No visible blocks yet.</li>';
+ } else {
+ for (const field of visibleFields) {
+ const item = document.createElement('li');
+ item.textContent = field.name ?? field.type ?? 'Untitled block';
+ fields.appendChild(item);
+ }
+ }
+
+ openButton.disabled = !payload.editor_url;
+ openButton.onclick = () => {
+ if (window.openai?.openExternal) {
+ return window.openai.openExternal({ href: payload.editor_url, redirectUrl: false });
+ }
+
+ return app.openLink({ url: payload.editor_url });
+ };
+ });
+
+ app.autoResize();
+ });
+ </script>
+ </x-slot:head>
+
+ <main>
+ <section class="preview-surface">
+ <header class="header">
+ <div class="heading">
+ <p class="eyebrow">Private preview</p>
+ <h1 id="title">Loading preview…</h1>
+ <p id="meta" class="meta"></p>
+ </div>
+ <div class="header-actions">
+ <div class="zoom-controls" role="group" aria-label="Preview zoom">
+ <button id="zoom-out" class="zoom-button" type="button" title="Zoom out" aria-label="Zoom out">−</button>
+ <button id="zoom-reset" class="zoom-value" type="button" title="Reset zoom">80%</button>
+ <button id="zoom-in" class="zoom-button" type="button" title="Zoom in" aria-label="Zoom in">+</button>
+ </div>
+ <button id="open-editor" class="open-button" type="button" disabled>Open in OpnForm</button>
+ </div>
+ </header>
+ <div id="preview-viewport" class="preview-viewport" hidden>
+ <div id="preview-canvas" class="preview-canvas">
+ <iframe
+ id="preview"
+ title="OpnForm draft preview"
+ sandbox="allow-forms allow-modals allow-popups allow-scripts allow-same-origin"
+ referrerpolicy="no-referrer"
+ hidden
+ ></iframe>
+ </div>
+ </div>
+ <ol id="fields"></ol>
+ </section>
+ </main>
+</x-mcp::app>
diff --git a/api/resources/views/oauth/authorize.blade.php b/api/resources/views/oauth/authorize.blade.php
new file mode 100644
index 000000000..748cf850d
--- /dev/null
+++ b/api/resources/views/oauth/authorize.blade.php
@@ -0,0 +1,82 @@
+<!DOCTYPE html>
+<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="robots" content="noindex, nofollow">
+ <title>Authorize {{ $client->name }} - OpnForm</title>
+ <style>
+ * { box-sizing: border-box; }
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: #f8fafc; color: #0f172a; font-family: Inter, ui-sans-serif, system-ui, sans-serif; }
+ .card { width: 100%; max-width: 440px; padding: 32px; border: 1px solid #e2e8f0; border-radius: 20px; background: white; box-shadow: 0 20px 50px rgba(15, 23, 42, .08); }
+ .brand { display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 20px; }
+ .brand-logo { display: block; width: 42px; height: 42px; }
+ .brand-name { font-size: 18px; font-weight: 700; letter-spacing: -.02em; }
+ h1 { margin: 0 0 8px; text-align: center; font-size: 24px; line-height: 1.2; }
+ .intro { margin: 0; text-align: center; color: #64748b; line-height: 1.5; }
+ .account, .destination, .permission { margin-top: 24px; padding: 16px; border-radius: 12px; background: #f8fafc; }
+ .label { margin: 0 0 6px; color: #64748b; font-size: 13px; }
+ .value { margin: 0; font-weight: 600; overflow-wrap: anywhere; }
+ .permission { display: flex; gap: 10px; align-items: flex-start; margin-top: 12px; }
+ .permission span { color: #2563eb; }
+ .permission p { margin: 0; color: #334155; font-size: 14px; line-height: 1.45; }
+ .actions { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 28px; }
+ form { margin: 0; }
+ button { width: 100%; min-height: 44px; border-radius: 10px; border: 1px solid #cbd5e1; background: white; color: #0f172a; font: inherit; font-weight: 600; cursor: pointer; }
+ button.primary { border-color: #2563eb; background: #2563eb; color: white; }
+ button:hover { filter: brightness(.97); }
+ </style>
+</head>
+<body>
+<main class="card">
+ <div class="brand" aria-label="OpnForm">
+ <svg class="brand-logo" aria-hidden="true" fill="none" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
+ <linearGradient id="opnform-gradient" gradientUnits="userSpaceOnUse" x1="60" x2="60" y1="2" y2="118.352">
+ <stop offset="0" stop-color="#2563eb"/>
+ <stop offset="1" stop-color="#60a5fa"/>
+ </linearGradient>
+ <path clip-rule="evenodd" d="m80.6502 118.352c22.9638-8.418 39.3498-30.4712 39.3498-56.352 0-33.1371-26.8629-60-60-60s-60 26.8629-60 60c0 25.8808 16.3862 47.934 39.3498 56.352l16.631-38.9411c-7.4746-1.9924-12.9808-8.8086-12.9808-16.9109 0-9.665 7.835-17.5 17.5-17.5s17.5 7.835 17.5 17.5c0 8.4269-5.9563 15.4627-13.8885 17.1269z" fill="url(#opnform-gradient)" fill-rule="evenodd"/>
+ </svg>
+ <span class="brand-name">OpnForm</span>
+ </div>
+ <h1>Connect {{ $client->name }}</h1>
+ <p class="intro">Review the access requested for your OpnForm account.</p>
+
+ <section class="account">
+ <p class="label">Signed in as</p>
+ <p class="value">{{ $user->email }}</p>
+ </section>
+
+ <section class="destination">
+ <p class="label">Callback destination</p>
+ <p class="value">{{ $request->query('redirect_uri') }}</p>
+ </section>
+
+ @foreach ($scopes as $scope)
+ <section class="permission">
+ <span aria-hidden="true">●</span>
+ <p>{{ $scope->description }}</p>
+ </section>
+ @endforeach
+
+ <div class="actions">
+ <form method="POST" action="{{ route('passport.authorizations.deny') }}">
+ @csrf
+ @method('DELETE')
+ <input type="hidden" name="state" value="">
+ <input type="hidden" name="client_id" value="{{ $client->id }}">
+ <input type="hidden" name="auth_token" value="{{ $authToken }}">
+ <button type="submit">Cancel</button>
+ </form>
+
+ <form method="POST" action="{{ route('passport.authorizations.approve') }}">
+ @csrf
+ <input type="hidden" name="state" value="">
+ <input type="hidden" name="client_id" value="{{ $client->id }}">
+ <input type="hidden" name="auth_token" value="{{ $authToken }}">
+ <button type="submit" class="primary">Authorize</button>
+ </form>
+ </div>
+</main>
+</body>
+</html>
diff --git a/api/routes/ai.php b/api/routes/ai.php
new file mode 100644
index 000000000..f0d90140c
--- /dev/null
+++ b/api/routes/ai.php
@@ -0,0 +1,32 @@
+<?php
+
+use App\Mcp\Servers\OpnFormServer;
+use App\Http\Controllers\McpOAuthRegisterController;
+use Illuminate\Support\Facades\Route;
+use Laravel\Mcp\Facades\Mcp;
+
+if (config('oauth.enabled', false)) {
+ Route::middleware('mcp.enabled')->group(function () {
+ Route::get('/.well-known/oauth-authorization-server', static fn () => response()->json([
+ 'issuer' => config('mcp.authorization_server') ?? url('/'),
+ 'authorization_endpoint' => route('passport.authorizations.authorize'),
+ 'token_endpoint' => route('passport.token'),
+ 'registration_endpoint' => url('/oauth/register'),
+ 'response_types_supported' => ['code'],
+ 'code_challenge_methods_supported' => ['S256'],
+ 'scopes_supported' => ['mcp:use'],
+ 'grant_types_supported' => ['authorization_code', 'refresh_token'],
+ 'token_endpoint_auth_methods_supported' => ['none'],
+ ]))->name('mcp.oauth.authorization-server');
+
+ Mcp::oauthRoutes();
+ Route::post('/oauth/register', McpOAuthRegisterController::class)
+ ->middleware('throttle:mcp-oauth-registration');
+ });
+}
+
+Route::middleware('mcp.enabled')->group(function () {
+ Mcp::web('/mcp', OpnFormServer::class)
+ ->middleware(['auth.mcp.optional', 'throttle:mcp', 'observe.mcp']);
+});
+Mcp::local('opnform', OpnFormServer::class);
diff --git a/api/routes/api.php b/api/routes/api.php
index 634fd7a24..2ca891a57 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -23,6 +23,7 @@ use App\Http\Controllers\Settings\OAuthProviderController;
use App\Http\Controllers\Settings\PasswordController;
use App\Http\Controllers\Settings\ProfileController;
use App\Http\Controllers\Settings\TokenController;
+use App\Http\Controllers\Settings\McpSettingsController;
use App\Http\Controllers\SubscriptionController;
use App\Http\Controllers\Forms\TemplateController;
use App\Http\Controllers\Auth\UserInviteController;
@@ -35,6 +36,9 @@ use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HealthCheckController;
+use App\Http\Controllers\AgentFormDraftController;
+use App\Http\Controllers\McpOAuthSessionController;
+use App\Http\Controllers\RevokeMcpOAuthSessionController;
/*
|--------------------------------------------------------------------------
@@ -51,6 +55,35 @@ if (config('app.self_hosted')) {
Route::get('/healthcheck', [HealthCheckController::class, 'apiCheck']);
}
+Route::middleware('mcp.enabled')->group(function () {
+ Route::prefix('agent-drafts')->name('agent-drafts.')->middleware('mcp.guest-drafts')->group(function () {
+ Route::get('/preview/{draft}', [AgentFormDraftController::class, 'preview'])
+ ->middleware(['signed', 'throttle:60,1'])
+ ->name('preview');
+ Route::post('/handoff/consume', [AgentFormDraftController::class, 'consume'])
+ ->middleware('throttle:30,1')
+ ->name('handoff.consume');
+ Route::get('/editor/current', [AgentFormDraftController::class, 'current'])
+ ->middleware('throttle:120,1')
+ ->name('editor.current');
+ Route::put('/editor/current', [AgentFormDraftController::class, 'replace'])
+ ->middleware('throttle:120,1')
+ ->name('editor.replace');
+ Route::post('/editor/claim', [AgentFormDraftController::class, 'claim'])
+ ->middleware(['auth.multi', 'throttle:30,1'])
+ ->name('editor.claim');
+ });
+
+ if (config('oauth.enabled', false)) {
+ Route::post('/mcp-oauth/session', McpOAuthSessionController::class)
+ ->middleware(['auth.multi', 'throttle:30,1'])
+ ->name('mcp-oauth.session');
+ Route::delete('/mcp-oauth/session', RevokeMcpOAuthSessionController::class)
+ ->middleware(['auth.mcp.optional', 'throttle:30,1'])
+ ->name('mcp-oauth.session.revoke');
+ }
+});
+
Route::prefix('open')->name('open.')->group(function () {
Route::prefix('forms')->name('forms.')->group(function () {
Route::post('/import', [FormImportController::class, 'import'])
@@ -97,6 +130,11 @@ Route::group(['middleware' => 'auth.multi'], function () {
Route::post('/portal', [\App\Http\Controllers\Settings\LicenseController::class, 'portal'])->name('portal');
});
+ Route::prefix('/mcp')->name('mcp.')->middleware(['self-hosted'])->group(function () {
+ Route::get('/', [McpSettingsController::class, 'show'])->name('show');
+ Route::put('/', [McpSettingsController::class, 'update'])->name('update');
+ });
+
Route::prefix('/two-factor')->name('two-factor.')->group(function () {
Route::post('/enable', [\App\Http\Controllers\Settings\TwoFactorController::class, 'enable'])->name('enable');
Route::post('/confirm', [\App\Http\Controllers\Settings\TwoFactorController::class, 'confirm'])->name('confirm');
@@ -194,7 +232,7 @@ Route::group(['middleware' => 'auth.multi'], function () {
});
// Summary endpoints - Pro plan required, with rate limiting
- Route::middleware(['feature:form_summary', 'throttle:summary'])->group(function () {
+ Route::middleware(['feature:form_summary', 'throttle.form-summary'])->group(function () {
Route::get('form-summary/{form}', [FormSummaryController::class, 'getSummary'])->name('form.summary');
Route::get('form-summary/{form}/field/{fieldId}/values', [FormSummaryController::class, 'getFieldValues'])->name('form.summary.field-values');
});
diff --git a/api/routes/oauth.php b/api/routes/oauth.php
new file mode 100644
index 000000000..7529de6ff
--- /dev/null
+++ b/api/routes/oauth.php
@@ -0,0 +1,28 @@
+<?php
+
+use App\Http\Middleware\RequireOAuthS256;
+use App\Http\Middleware\SecureOAuthConsent;
+use Illuminate\Support\Facades\Route;
+use Laravel\Passport\Http\Controllers\AccessTokenController;
+use Laravel\Passport\Http\Controllers\ApproveAuthorizationController;
+use Laravel\Passport\Http\Controllers\AuthorizationController;
+use Laravel\Passport\Http\Controllers\DenyAuthorizationController;
+
+Route::prefix(config('passport.path', 'oauth'))
+ ->as('passport.')
+ ->group(function () {
+ Route::post('/token', [AccessTokenController::class, 'issueToken'])
+ ->middleware('throttle')
+ ->name('token');
+
+ Route::get('/authorize', [AuthorizationController::class, 'authorize'])
+ ->middleware(['web', RequireOAuthS256::class, SecureOAuthConsent::class])
+ ->name('authorizations.authorize');
+
+ Route::middleware(['web', 'auth:web', SecureOAuthConsent::class])->group(function () {
+ Route::post('/authorize', [ApproveAuthorizationController::class, 'approve'])
+ ->name('authorizations.approve');
+ Route::delete('/authorize', [DenyAuthorizationController::class, 'deny'])
+ ->name('authorizations.deny');
+ });
+ });
diff --git a/api/tests/CreatesApplication.php b/api/tests/CreatesApplication.php
index 547152f6a..c939b705a 100644
--- a/api/tests/CreatesApplication.php
+++ b/api/tests/CreatesApplication.php
@@ -3,9 +3,16 @@
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
+use Illuminate\Foundation\Application;
+use RuntimeException;
trait CreatesApplication
{
+ /**
+ * @var array{private: string, public: string}|null
+ */
+ private static ?array $passportTestKeys = null;
+
/**
* Creates the application.
*
@@ -16,7 +23,37 @@ trait CreatesApplication
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
+ $this->configurePassportTestKeys($app);
return $app;
}
+
+ private function configurePassportTestKeys(Application $app): void
+ {
+ if (self::$passportTestKeys === null) {
+ $key = openssl_pkey_new([
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,
+ ]);
+
+ if ($key === false || ! openssl_pkey_export($key, $privateKey)) {
+ throw new RuntimeException('Unable to generate the Passport test private key.');
+ }
+
+ $details = openssl_pkey_get_details($key);
+ if ($details === false || ! is_string($details['key'] ?? null)) {
+ throw new RuntimeException('Unable to generate the Passport test public key.');
+ }
+
+ self::$passportTestKeys = [
+ 'private' => $privateKey,
+ 'public' => $details['key'],
+ ];
+ }
+
+ $app->make('config')->set([
+ 'passport.private_key' => self::$passportTestKeys['private'],
+ 'passport.public_key' => self::$passportTestKeys['public'],
+ ]);
+ }
}
diff --git a/api/tests/Feature/Forms/FormUpdateServiceTest.php b/api/tests/Feature/Forms/FormUpdateServiceTest.php
new file mode 100644
index 000000000..7b871b1ba
--- /dev/null
+++ b/api/tests/Feature/Forms/FormUpdateServiceTest.php
@@ -0,0 +1,32 @@
+<?php
+
+use App\Http\Resources\FormResource;
+use App\Service\Forms\FormUpdateService;
+
+it('centralizes persistence and tracks only removed input properties', function () {
+ $user = $this->actingAsUser();
+ $workspace = $this->createUserWorkspace($user);
+ $previouslyRemoved = ['id' => 'old-email', 'name' => 'Old email', 'type' => 'email'];
+ $form = $this->createForm($user, $workspace, [
+ 'properties' => [
+ ['id' => 'kept-name', 'name' => 'Name', 'type' => 'text'],
+ ['id' => 'removed-email', 'name' => 'Email', 'type' => 'email'],
+ ['id' => 'removed-copy', 'name' => 'Introduction', 'type' => 'nf-text', 'content' => '<p>Hello</p>'],
+ ],
+ 'removed_properties' => [$previouslyRemoved],
+ ]);
+ $data = (new FormResource($form))->toArray(request());
+ $data['title'] = 'Updated through the canonical service';
+ $data['clear_empty_fields_on_update'] = false;
+ $data['properties'] = [
+ ['id' => 'kept-name', 'name' => 'Name', 'type' => 'text'],
+ ];
+
+ $updated = app(FormUpdateService::class)->update($form, $data);
+ $removedIds = collect($form->refresh()->removed_properties)->pluck('id')->all();
+
+ expect($updated)->toHaveKeys(['form', 'cleanings', 'cleaning_keys', 'has_cleaned'])
+ ->and($form->title)->toBe('Updated through the canonical service')
+ ->and($removedIds)->toContain('old-email', 'removed-email')
+ ->and($removedIds)->not->toContain('removed-copy');
+});
diff --git a/api/tests/Feature/Mcp/AgentDraftEditorTest.php b/api/tests/Feature/Mcp/AgentDraftEditorTest.php
new file mode 100644
index 000000000..eb8dccf02
--- /dev/null
+++ b/api/tests/Feature/Mcp/AgentDraftEditorTest.php
@@ -0,0 +1,326 @@
+<?php
+
+use App\Http\Controllers\AgentFormDraftController;
+use App\Mcp\Servers\OpnFormServer;
+use App\Mcp\Tools\PreviewFormDraftTool;
+use App\Models\Forms\AgentFormDraft;
+use App\Models\OAuthProvider;
+use App\Models\User;
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Support\Facades\URL;
+
+function editorDraftDefinition(array $overrides = []): array
+{
+ return array_replace([
+ 'title' => 'Agent customer intake',
+ 'properties' => [
+ ['id' => 'name-field', 'name' => 'Name', 'type' => 'text'],
+ ['id' => 'email-field', 'name' => 'Email', 'type' => 'email'],
+ ],
+ ], $overrides);
+}
+
+beforeEach(function () {
+ config()->set('app.self_hosted', false);
+ config()->set('app.front_api_secret', 'test-front-secret');
+ config()->set('app.front_url', 'https://opnform.test');
+});
+
+it('renders an MCP App preview with short-lived preview and reusable editor links', function () {
+ $created = app(AgentFormDraftService::class)->create(editorDraftDefinition());
+
+ OpnFormServer::tool(PreviewFormDraftTool::class, [
+ 'draft_token' => $created['token'],
+ ])->assertOk()
+ ->assertSee('preview_url')
+ ->assertSee('editor_url')
+ ->assertSee('Agent customer intake');
+
+ OpnFormServer::resource(\App\Mcp\Apps\FormDraftPreviewApp::class)
+ ->assertOk()
+ ->assertSee('Open in OpnForm')
+ ->assertSee('window.openai?.openExternal')
+ ->assertSee('<iframe');
+
+ $draft = $created['draft']->refresh();
+ $handoff = $draft->editorHandoffs()->sole();
+ expect($handoff->token_hash)->toMatch('/^[a-f0-9]{64}$/')
+ ->and($handoff->expires_at->isSameSecond($draft->expires_at))->toBeTrue()
+ ->and(app(AgentFormDraftService::class)->issueEditorHandoff($created['token'])['editor_url'])
+ ->toStartWith('https://opnform.test/agent-drafts/edit#handoff=')
+ ->and(app(\App\Mcp\Apps\FormDraftPreviewApp::class)->resolvedAppMeta()['csp']['frameDomains'])
+ ->toBe(['https://opnform.test']);
+});
+
+it('publishes standard and ChatGPT-compatible CSP metadata with the full frontend origin', function () {
+ config()->set('app.front_url', 'http://127.0.0.1:33676');
+ $previewApp = app(\App\Mcp\Apps\FormDraftPreviewApp::class);
+ $resource = $previewApp->handle(new \Laravel\Mcp\Request())
+ ->content()
+ ->toResource($previewApp);
+
+ expect($previewApp->uri())->toBe('ui://opnform/form-draft-preview-v3')
+ ->and($previewApp->resolvedAppMeta()['csp']['resourceDomains'])
+ ->toBe(['http://127.0.0.1:33676'])
+ ->and($previewApp->resolvedAppMeta()['csp']['frameDomains'])
+ ->toBe(['http://127.0.0.1:33676'])
+ ->and($resource['text'])->not->toContain('native-preview')
+ ->and($resource['_meta']['openai/widgetCSP'])
+ ->toBe([
+ 'connect_domains' => [],
+ 'resource_domains' => ['http://127.0.0.1:33676'],
+ 'frame_domains' => ['http://127.0.0.1:33676'],
+ 'redirect_domains' => ['http://127.0.0.1:33676'],
+ ]);
+
+ config()->set('app.front_url', 'https://opnform.test');
+ $secureApp = app(\App\Mcp\Apps\FormDraftPreviewApp::class);
+ $secureResource = $secureApp->handle(new \Laravel\Mcp\Request())
+ ->content()
+ ->toResource($secureApp);
+
+ expect($secureApp->resolvedAppMeta()['csp']['frameDomains'])
+ ->toBe(['https://opnform.test'])
+ ->and($secureApp->resolvedAppMeta()['csp']['resourceDomains'])
+ ->toBe(['https://opnform.test'])
+ ->and($secureResource['_meta']['openai/widgetCSP']['frame_domains'])
+ ->toBe(['https://opnform.test']);
+});
+
+it('serves preview data only through a valid signed URL without exposing capabilities', function () {
+ $draft = app(AgentFormDraftService::class)->create(editorDraftDefinition())['draft'];
+ $signedUrl = URL::temporarySignedRoute('agent-drafts.preview', now()->addMinute(), ['draft' => $draft->id]);
+
+ $this->getJson($signedUrl)
+ ->assertOk()
+ ->assertHeader('Cache-Control', 'max-age=0, no-store, private')
+ ->assertJsonPath('draft.definition.title', 'Agent customer intake')
+ ->assertJsonMissing(['token_hash' => $draft->token_hash]);
+
+ $this->getJson(route('agent-drafts.preview', $draft))->assertForbidden();
+});
+
+it('keeps each generated browser preview link valid for one hour', function () {
+ $this->freezeTime();
+ $draft = app(AgentFormDraftService::class)->create(editorDraftDefinition())['draft'];
+ $previewUrl = app(AgentFormDraftService::class)->previewUrl($draft);
+ parse_str((string) parse_url($previewUrl, PHP_URL_QUERY), $previewQuery);
+ parse_str((string) parse_url($previewQuery['source'], PHP_URL_QUERY), $sourceQuery);
+
+ expect((int) $sourceQuery['expires'])
+ ->toBe(now()->addMinutes(AgentFormDraftService::PREVIEW_URL_TTL_MINUTES)->timestamp);
+});
+
+it('keeps every guest editor link reusable until the draft expires', function () {
+ $this->freezeTime();
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(editorDraftDefinition());
+ $firstHandoff = $drafts->issueEditorHandoff($created['token']);
+ $draft = $created['draft']->refresh();
+ $firstCapability = $draft->editorHandoffs()->sole();
+
+ expect($firstCapability->expires_at->isSameSecond($draft->expires_at))->toBeTrue();
+
+ $response = $this->withHeader('x-api-secret', 'test-front-secret')
+ ->postJson(route('agent-drafts.handoff.consume'), [
+ 'handoff_token' => $firstHandoff['handoff_token'],
+ ])
+ ->assertOk()
+ ->assertJsonPath('draft.version', 1);
+
+ $editorSession = $response->json('editor_session');
+ $draft->refresh();
+ expect($editorSession)->toHaveLength(43)
+ ->and($draft->editor_session_hash)->toBe(hash('sha256', $editorSession))
+ ->and($firstCapability->refresh()->last_used_at)->not->toBeNull();
+
+ $this->travel(1)->day();
+ $secondHandoff = $drafts->issueEditorHandoff($created['token']);
+ $this->withHeader('x-api-secret', 'test-front-secret')
+ ->postJson(route('agent-drafts.handoff.consume'), [
+ 'handoff_token' => $secondHandoff['handoff_token'],
+ ])
+ ->assertOk()
+ ->assertJsonPath('editor_session', $editorSession);
+
+ $this->withHeader('x-api-secret', 'test-front-secret')
+ ->postJson(route('agent-drafts.handoff.consume'), [
+ 'handoff_token' => $firstHandoff['handoff_token'],
+ ])
+ ->assertOk()
+ ->assertJsonPath('editor_session', $editorSession);
+
+ $this->assertDatabaseCount('agent_form_draft_handoffs', 2);
+
+ $this->travel(5)->days();
+ $this->travel(23)->hours();
+ $this->withHeader('x-api-secret', 'test-front-secret')
+ ->postJson(route('agent-drafts.handoff.consume'), [
+ 'handoff_token' => $firstHandoff['handoff_token'],
+ ])
+ ->assertOk();
+
+ $this->travel(2)->hours();
+ $this->withHeader('x-api-secret', 'test-front-secret')
+ ->postJson(route('agent-drafts.handoff.consume'), [
+ 'handoff_token' => $firstHandoff['handoff_token'],
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('handoff_token');
+});
+
+it('requires the trusted frontend secret for editor endpoints', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(editorDraftDefinition());
+ $session = $drafts->consumeEditorHandoff(
+ $drafts->issueEditorHandoff($created['token'])['handoff_token'],
+ )['editor_session'];
+
+ $this->withHeader(AgentFormDraftController::SESSION_HEADER, $session)
+ ->getJson(route('agent-drafts.editor.current'))
+ ->assertForbidden();
+});
+
+it('syncs editor replacements through the canonical optimistic version', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(editorDraftDefinition());
+ $session = $drafts->consumeEditorHandoff(
+ $drafts->issueEditorHandoff($created['token'])['handoff_token'],
+ )['editor_session'];
+ $headers = [
+ 'x-api-secret' => 'test-front-secret',
+ AgentFormDraftController::SESSION_HEADER => $session,
+ ];
+
+ $definition = $created['draft']->definition;
+ $definition['title'] = 'Edited in browser';
+
+ $this->withHeaders($headers)
+ ->putJson(route('agent-drafts.editor.replace'), [
+ 'expected_version' => 1,
+ 'definition' => $definition,
+ ])
+ ->assertOk()
+ ->assertJsonPath('draft.version', 2)
+ ->assertJsonPath('draft.definition.title', 'Edited in browser');
+
+ $this->withHeaders($headers)
+ ->putJson(route('agent-drafts.editor.replace'), [
+ 'expected_version' => 1,
+ 'definition' => $definition,
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('expected_version');
+
+ expect($drafts->get($created['token'])->version)->toBe(2);
+});
+
+it('claims a draft explicitly into an owned workspace as an unpublished form', function () {
+ $user = User::factory()->create();
+ $workspace = createUserWorkspace($user);
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(editorDraftDefinition(['no_branding' => true]));
+ $session = $drafts->consumeEditorHandoff(
+ $drafts->issueEditorHandoff($created['token'])['handoff_token'],
+ )['editor_session'];
+ $headers = [
+ 'x-api-secret' => 'test-front-secret',
+ AgentFormDraftController::SESSION_HEADER => $session,
+ ];
+
+ $response = $this->actingAs($user, 'api')
+ ->withHeaders($headers)
+ ->postJson(route('agent-drafts.editor.claim'), [
+ 'expected_version' => 1,
+ 'workspace_id' => $workspace->id,
+ ])
+ ->assertOk()
+ ->assertJsonPath('form.visibility', 'draft')
+ ->assertJsonPath('already_claimed', false)
+ ->assertJsonStructure(['cleanings' => ['form']]);
+
+ $formId = $response->json('form.id');
+ $this->assertDatabaseHas('forms', [
+ 'id' => $formId,
+ 'workspace_id' => $workspace->id,
+ 'creator_id' => $user->id,
+ 'visibility' => 'draft',
+ ]);
+ $this->assertDatabaseHas('agent_form_drafts', [
+ 'id' => $created['draft']->id,
+ 'status' => AgentFormDraft::STATUS_CLAIMED,
+ 'claimed_form_id' => $formId,
+ ]);
+
+ $this->actingAs($user, 'api')
+ ->withHeaders($headers)
+ ->postJson(route('agent-drafts.editor.claim'), [
+ 'expected_version' => 1,
+ 'workspace_id' => $workspace->id,
+ ])
+ ->assertOk()
+ ->assertJsonPath('form.id', $formId)
+ ->assertJsonPath('already_claimed', true);
+
+ $this->assertDatabaseCount('forms', 1);
+});
+
+it('refuses claim into another users workspace', function () {
+ $user = User::factory()->create();
+ $foreignWorkspace = createUserWorkspace(User::factory()->create());
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(editorDraftDefinition());
+ $session = $drafts->consumeEditorHandoff(
+ $drafts->issueEditorHandoff($created['token'])['handoff_token'],
+ )['editor_session'];
+
+ $this->actingAs($user, 'api')
+ ->withHeaders([
+ 'x-api-secret' => 'test-front-secret',
+ AgentFormDraftController::SESSION_HEADER => $session,
+ ])
+ ->postJson(route('agent-drafts.editor.claim'), [
+ 'expected_version' => 1,
+ 'workspace_id' => $foreignWorkspace->id,
+ ])
+ ->assertForbidden();
+
+ $this->assertDatabaseCount('forms', 0);
+});
+
+it('refuses a guest payment account that does not belong to the claim workspace', function () {
+ $user = User::factory()->create();
+ $workspace = createUserWorkspace($user);
+ $foreignProvider = OAuthProvider::factory()->for(User::factory()->create())->create([
+ 'provider' => 'stripe',
+ 'provider_user_id' => 'acct_foreign',
+ ]);
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(editorDraftDefinition([
+ 'properties' => [[
+ 'id' => 'payment-field',
+ 'name' => 'Payment',
+ 'type' => 'payment',
+ 'amount' => 10,
+ 'currency' => 'USD',
+ 'stripe_account_id' => $foreignProvider->id,
+ ]],
+ ]));
+ $session = $drafts->consumeEditorHandoff(
+ $drafts->issueEditorHandoff($created['token'])['handoff_token'],
+ )['editor_session'];
+
+ $this->actingAs($user, 'api')
+ ->withHeaders([
+ 'x-api-secret' => 'test-front-secret',
+ AgentFormDraftController::SESSION_HEADER => $session,
+ ])
+ ->postJson(route('agent-drafts.editor.claim'), [
+ 'expected_version' => 1,
+ 'workspace_id' => $workspace->id,
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('properties.0.stripe_account_id');
+
+ $this->assertDatabaseCount('forms', 0);
+});
diff --git a/api/tests/Feature/Mcp/AgentFormFieldCatalogParityTest.php b/api/tests/Feature/Mcp/AgentFormFieldCatalogParityTest.php
new file mode 100644
index 000000000..3bd445499
--- /dev/null
+++ b/api/tests/Feature/Mcp/AgentFormFieldCatalogParityTest.php
@@ -0,0 +1,44 @@
+<?php
+
+use App\Service\Forms\AgentFormFieldCatalog;
+
+it('keeps the MCP field catalog aligned with the client block registry', function () {
+ $registryPath = base_path('../client/data/blocks_types.json');
+
+ expect($registryPath)->toBeFile();
+
+ $registry = json_decode(file_get_contents($registryPath), true, flags: JSON_THROW_ON_ERROR);
+
+ $clientInputTypes = collect($registry)
+ ->filter(fn (array $block): bool => (bool) ($block['is_input'] ?? false))
+ ->keys()
+ ->sort()
+ ->values()
+ ->all();
+ $mcpInputTypes = collect(AgentFormFieldCatalog::INPUT_TYPES)
+ ->merge(array_keys(AgentFormFieldCatalog::ALIASES))
+ ->sort()
+ ->values()
+ ->all();
+
+ $clientLayoutTypes = collect($registry)
+ ->reject(fn (array $block): bool => (bool) ($block['is_input'] ?? false))
+ ->keys()
+ ->sort()
+ ->values()
+ ->all();
+ $mcpLayoutTypes = collect(AgentFormFieldCatalog::LAYOUT_TYPES)
+ ->sort()
+ ->values()
+ ->all();
+
+ expect($mcpInputTypes)->toBe($clientInputTypes)
+ ->and($mcpLayoutTypes)->toBe($clientLayoutTypes)
+ ->and(AgentFormFieldCatalog::INPUT_TYPES)->toHaveCount(count(array_unique(AgentFormFieldCatalog::INPUT_TYPES)))
+ ->and(AgentFormFieldCatalog::LAYOUT_TYPES)->toHaveCount(count(array_unique(AgentFormFieldCatalog::LAYOUT_TYPES)));
+
+ foreach (AgentFormFieldCatalog::ALIASES as $alias => $definition) {
+ expect(AgentFormFieldCatalog::INPUT_TYPES)->not->toContain($alias)
+ ->and(AgentFormFieldCatalog::INPUT_TYPES)->toContain($definition['type']);
+ }
+});
diff --git a/api/tests/Feature/Mcp/AgentPluginPackageTest.php b/api/tests/Feature/Mcp/AgentPluginPackageTest.php
new file mode 100644
index 000000000..bd6dbb011
--- /dev/null
+++ b/api/tests/Feature/Mcp/AgentPluginPackageTest.php
@@ -0,0 +1,230 @@
+<?php
+
+function opnformPluginPath(string $path = ''): string
+{
+ return base_path('../plugins/opnform'.($path === '' ? '' : '/'.$path));
+}
+
+function readOpnformPluginJson(string $path): array
+{
+ return json_decode(
+ file_get_contents(opnformPluginPath($path)),
+ true,
+ flags: JSON_THROW_ON_ERROR,
+ );
+}
+
+it('ships portable manifests that conform to the Agent Plugins 1.0 schemas', function () {
+ $plugin = readOpnformPluginJson('plugin.json');
+ $mcp = readOpnformPluginJson('mcp.json');
+
+ $portablePluginFields = [
+ '$schema', 'name', 'version', 'description', 'author', 'homepage',
+ 'repository', 'license', 'keywords', 'extensions',
+ ];
+
+ expect($plugin)
+ ->toHaveKeys(['$schema', 'name'])
+ ->and($plugin['$schema'])->toBe('https://agent-plugins.org/schemas/1.0.0/plugin.schema.json')
+ ->and($plugin['name'])->toMatch('/^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/')
+ ->and(strlen($plugin['name']))->toBeLessThanOrEqual(64)
+ ->and(array_diff(array_keys($plugin), $portablePluginFields))->toBe([])
+ ->and(array_diff(array_keys($plugin['author']), ['name', 'email', 'url']))->toBe([])
+ ->and($plugin['keywords'])->each->toBeString()
+ ->and($mcp)->toHaveKeys(['$schema', 'mcpServers'])
+ ->and($mcp['$schema'])->toBe('https://agent-plugins.org/schemas/1.0.0/mcp.schema.json')
+ ->and(array_diff(array_keys($mcp), ['$schema', 'mcpServers']))->toBe([])
+ ->and($mcp['mcpServers']['opnform'])->toBe([
+ 'type' => 'streamable-http',
+ 'url' => 'https://api.opnform.com/mcp',
+ ]);
+});
+
+it('ships a valid native OpenAI plugin wrapper for the hosted MCP server', function () {
+ $portable = readOpnformPluginJson('plugin.json');
+ $portableMcp = readOpnformPluginJson('mcp.json');
+ $native = readOpnformPluginJson('.codex-plugin/plugin.json');
+ $nativeMcp = readOpnformPluginJson('.mcp.json');
+ $nativePluginFields = [
+ 'id', 'name', 'version', 'description', 'skills', 'apps', 'mcpServers',
+ 'interface', 'author', 'homepage', 'repository', 'license', 'keywords',
+ ];
+ $nativeInterfaceFields = [
+ 'displayName', 'shortDescription', 'longDescription', 'developerName',
+ 'category', 'capabilities', 'websiteURL', 'privacyPolicyURL',
+ 'termsOfServiceURL', 'brandColor', 'composerIcon', 'logo', 'logoDark',
+ 'screenshots', 'defaultPrompt', 'default_prompt',
+ ];
+
+ expect($native)
+ ->toHaveKeys([
+ 'name', 'version', 'description', 'author', 'skills', 'mcpServers', 'interface',
+ ])
+ ->and($native['name'])->toBe($portable['name'])
+ ->and($native['version'])->toBe($portable['version'])
+ ->and($native['version'])->toMatch('/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/')
+ ->and($native['author'])->toBe($portable['author'])
+ ->and($native['homepage'])->toBe($portable['homepage'])
+ ->and($native['repository'])->toBe($portable['repository'])
+ ->and(array_diff(array_keys($native), $nativePluginFields))->toBe([])
+ ->and($native['skills'])->toBe('./skills/')
+ ->and($native['mcpServers'])->toBe('./.mcp.json')
+ ->and($native)->not->toHaveKey('apps')
+ ->and($native['interface'])->toHaveKeys([
+ 'displayName', 'shortDescription', 'longDescription', 'developerName',
+ 'category', 'capabilities', 'websiteURL', 'privacyPolicyURL',
+ 'termsOfServiceURL', 'defaultPrompt', 'brandColor', 'composerIcon', 'logo',
+ ])
+ ->and(array_diff(array_keys($native['interface']), $nativeInterfaceFields))->toBe([])
+ ->and($native['interface']['websiteURL'])->toBe($portable['author']['url'])
+ ->and($native['interface']['defaultPrompt'])->toHaveCount(3)
+ ->and($nativeMcp['mcpServers']['opnform'])->toBe([
+ 'type' => 'http',
+ 'url' => $portableMcp['mcpServers']['opnform']['url'],
+ 'auth' => 'oauth',
+ ])
+ ->and(array_diff(array_keys($nativeMcp), ['mcpServers']))->toBe([])
+ ->and(opnformPluginPath('.app.json'))->not->toBeFile();
+
+ foreach ($native['interface']['defaultPrompt'] as $prompt) {
+ expect($prompt)->toBeString()
+ ->and(strlen($prompt))->toBeLessThanOrEqual(128);
+ }
+});
+
+it('keeps every native manifest path relative to and inside the plugin package', function () {
+ $native = readOpnformPluginJson('.codex-plugin/plugin.json');
+ $paths = [
+ $native['skills'],
+ $native['mcpServers'],
+ $native['interface']['composerIcon'],
+ $native['interface']['logo'],
+ ];
+ $root = realpath(opnformPluginPath());
+
+ foreach ($paths as $path) {
+ $resolved = realpath(opnformPluginPath(substr($path, 2)));
+
+ expect($path)->toStartWith('./')
+ ->and($path)->not->toContain('..')
+ ->and($resolved)->not->toBeFalse()
+ ->and($resolved === $root || str_starts_with($resolved, $root.DIRECTORY_SEPARATOR))->toBeTrue();
+ }
+});
+
+it('ships a discoverable OpnForm skill with the complete safety workflow', function () {
+ $skillPath = opnformPluginPath('skills/opnform/SKILL.md');
+ $skill = file_get_contents($skillPath);
+
+ expect($skillPath)->toBeFile()
+ ->and($skill)->toStartWith("---\n")
+ ->and($skill)->toMatch('/\A---\nname: opnform\ndescription: .+\n---\n/s')
+ ->and($skill)->toContain(
+ 'opnform://schemas/agent-form-definition/v1',
+ 'validate_form_definition',
+ 'draft_token',
+ 'preview_form_draft',
+ 'get_form_draft',
+ 'open_form_draft_in_editor',
+ 'get_account_context',
+ 'list_workspaces',
+ 'publish_form',
+ 'trash_form',
+ 'get_submission_stats',
+ 'export_submissions',
+ 'disabled_features',
+ 'expected_version',
+ 'revision',
+ )
+ ->and($skill)->toContain(
+ 'Authenticated tools remain discoverable before the account is connected',
+ 'Do not report that account tools are unavailable',
+ 'Never launch another Codex or ChatGPT agent',
+ 'run `codex exec`',
+ 'OpnForm is not attached to the current conversation',
+ 'Distinguish missing tools from missing authentication',
+ 'Enabling or selecting the plugin is not OAuth authentication',
+ 'Settings → MCP servers → OpnForm → Authenticate',
+ 'start a new conversation with OpnForm selected before the first message',
+ 'may not hot-reload OAuth credentials',
+ 'do not loop or claim the connection succeeded',
+ )
+ ->and($skill)->toContain('confirm_publish: true', 'confirm_trash: true')
+ ->and($skill)->not->toContain('`confirm: true`')
+ ->and($skill)->toContain('Submission access is read-only')
+ ->and(substr_count($skill, "\n"))->toBeLessThan(500);
+});
+
+it('declares the hosted OpnForm MCP dependency in native skill metadata', function () {
+ $metadataPath = opnformPluginPath('skills/opnform/agents/openai.yaml');
+ $metadata = file_get_contents($metadataPath);
+
+ expect($metadataPath)->toBeFile()
+ ->and($metadata)->toContain(
+ 'display_name: "OpnForm"',
+ 'default_prompt: "Use $opnform',
+ 'type: "mcp"',
+ 'value: "opnform"',
+ 'transport: "streamable_http"',
+ 'url: "https://api.opnform.com/mcp"',
+ );
+});
+
+it('contains valid JSON and no local endpoints or fabricated ChatGPT app IDs', function () {
+ $iterator = new RecursiveIteratorIterator(
+ new RecursiveDirectoryIterator(opnformPluginPath(), FilesystemIterator::SKIP_DOTS),
+ );
+
+ foreach ($iterator as $file) {
+ $contents = file_get_contents($file->getPathname());
+
+ expect($contents)
+ ->not->toMatch('~https?://(?:localhost|127(?:\.\d+){3}|\[?::1\]?)(?::\d+)?~i')
+ ->not->toContain('plugin_asdk_app');
+
+ if ($file->getExtension() === 'json') {
+ expect(fn () => json_decode($contents, true, flags: JSON_THROW_ON_ERROR))->not->toThrow(JsonException::class);
+ }
+ }
+});
+
+it('does not expose plugin package files from the monorepo root', function () {
+ expect(base_path('../plugin.json'))->not->toBeFile()
+ ->and(base_path('../mcp.json'))->not->toBeFile()
+ ->and(base_path('../skills/opnform'))->not->toBeDirectory()
+ ->and(base_path('../.agents/plugins/marketplace.json'))->not->toBeFile();
+});
+
+it('teaches agents how to change presentation and media without repository inspection', function () {
+ $skill = file_get_contents(opnformPluginPath('skills/opnform/SKILL.md'));
+
+ expect($skill)
+ ->toContain('Re-read the field reference before changing presentation style, fields, layout, or media')
+ ->toContain('every visible block becomes one step automatically')
+ ->toContain('add an `image` object to that input or `nf-text` block')
+ ->toContain('Never persist localhost, private addresses, temporary tunnel domains');
+});
+
+it('renders a flattened and hardened form preview frame', function () {
+ $view = file_get_contents(resource_path('views/mcp/form-draft-preview-app.blade.php'));
+
+ expect($view)
+ ->toContain('class="preview-surface"')
+ ->toContain('<p class="eyebrow">Private preview</p>')
+ ->toContain("previewUrl.searchParams.set('embedded', '1')")
+ ->toContain('/widgets/iframeResize.min.js')
+ ->toContain('checkOrigin: [previewUrl.origin]')
+ ->toContain('scrolling: false')
+ ->toContain('const canvasWidth = 1280')
+ ->toContain('const focusedHeight = 720')
+ ->toContain('const defaultZoom = 0.8')
+ ->toContain('availableWidth / canvasWidth')
+ ->toContain('new ResizeObserver(applyPreviewLayout).observe(previewViewport)')
+ ->toContain("sizeHeight: presentationStyle !== 'focused'")
+ ->toContain('aria-label="Preview zoom"')
+ ->toContain('sandbox="allow-forms allow-modals allow-popups allow-scripts allow-same-origin"')
+ ->toContain('referrerpolicy="no-referrer"')
+ ->not->toContain('class="card"')
+ ->not->toContain('border-radius: 10px')
+ ->not->toContain('allow-top-navigation');
+});
diff --git a/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php b/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php
new file mode 100644
index 000000000..48f41f1ab
--- /dev/null
+++ b/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php
@@ -0,0 +1,404 @@
+<?php
+
+use App\Mcp\Servers\OpnFormServer;
+use App\Mcp\Tools\CreateFormTool;
+use App\Mcp\Tools\GetAccountContextTool;
+use App\Mcp\Tools\GetFormTool;
+use App\Mcp\Tools\ListFormsTool;
+use App\Mcp\Tools\ListWorkspacesTool;
+use App\Mcp\Tools\PublishFormTool;
+use App\Mcp\Tools\TrashFormTool;
+use App\Mcp\Tools\UpdateFormTool;
+use App\Models\Forms\Form;
+use App\Enums\SettingsKey;
+use App\Models\Setting;
+use App\Models\OAuthProvider;
+use App\Models\User;
+use App\Models\Workspace;
+use App\Service\Forms\AgentFormDefinition;
+use Illuminate\Database\Events\QueryExecuted;
+use Illuminate\Support\Facades\DB;
+use Laravel\Passport\Passport;
+
+function managedFormDefinition(array $overrides = []): array
+{
+ return array_replace([
+ 'schema_version' => 1,
+ 'title' => 'Agent-managed intake',
+ 'properties' => [
+ ['id' => 'name', 'name' => 'Name', 'type' => 'text'],
+ ['id' => 'email', 'name' => 'Email', 'type' => 'email'],
+ ],
+ ], $overrides);
+}
+
+function managedWorkspace(User $user, string $role = User::ROLE_ADMIN): Workspace
+{
+ $workspace = Workspace::factory()->create();
+ $workspace->users()->attach($user, ['role' => $role]);
+
+ return $workspace;
+}
+
+function managedForm(User $user, Workspace $workspace, array $overrides = []): Form
+{
+ return Form::factory()
+ ->forWorkspace($workspace)
+ ->createdBy($user)
+ ->create(array_replace([
+ 'title' => 'Existing managed form',
+ 'visibility' => 'draft',
+ 'properties' => managedFormDefinition()['properties'],
+ 'computed_variables' => [],
+ 'settings' => [],
+ ], $overrides));
+}
+
+function managedFormRevision(User $user, Form $form): string
+{
+ $management = app(\App\Service\Forms\McpFormManagementService::class);
+
+ return $management->serializeForm($management->form($user, $form->id))['revision'];
+}
+
+function configureManagedSelfHostedMcp(): void
+{
+ $key = openssl_pkey_new([
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,
+ ]);
+ openssl_pkey_export($key, $privateKey);
+ $details = openssl_pkey_get_details($key);
+
+ config()->set('oauth.enabled', true);
+ config()->set('app.url', 'https://forms.example.com');
+ config()->set('app.front_url', 'https://forms.example.com');
+ config()->set('passport.private_key', $privateKey);
+ config()->set('passport.public_key', $details['key']);
+}
+
+it('always advertises account tools as OAuth protected', function () {
+ $tool = app(ListFormsTool::class);
+
+ expect($tool->eligibleForRegistration())->toBeTrue()
+ ->and($tool->toArray()['securitySchemes'])->toBe([
+ [
+ 'type' => 'oauth2',
+ 'scopes' => ['mcp:use'],
+ ],
+ ]);
+});
+
+it('advertises guest and account tools with explicit per-tool auth policies', function () {
+ $payload = [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/list',
+ 'params' => [],
+ ];
+ $headers = ['Accept' => 'application/json, text/event-stream'];
+
+ $response = $this->postJson('/mcp', $payload, $headers)->assertOk();
+ $tools = collect($response->json('result.tools'))->keyBy('name');
+
+ expect($tools)->toHaveKeys(['create_form_draft', 'list_forms', 'trash_form'])
+ ->and($tools['create_form_draft']['securitySchemes'])->toBe([
+ ['type' => 'noauth'],
+ ])
+ ->and($tools['list_forms']['securitySchemes'])->toBe([
+ [
+ 'type' => 'oauth2',
+ 'scopes' => ['mcp:use'],
+ ],
+ ]);
+
+ $user = User::factory()->create();
+ Passport::actingAs($user, ['mcp:use'], 'oauth');
+
+ $this->postJson('/mcp', $payload, array_merge($headers, [
+ 'Authorization' => 'Bearer scoped-account-token',
+ ]))->assertOk()
+ ->assertSee(['create_form_draft', 'list_forms', 'trash_form']);
+});
+
+it('hides guest draft capabilities but keeps validation and OAuth tools on self-hosted instances', function () {
+ config()->set('app.self_hosted', true);
+ configureManagedSelfHostedMcp();
+ Setting::set(SettingsKey::MCP_ENABLED, true);
+ $headers = ['Accept' => 'application/json, text/event-stream'];
+
+ $toolsResponse = $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/list',
+ 'params' => [],
+ ], $headers)->assertOk();
+ $toolNames = collect($toolsResponse->json('result.tools'))->pluck('name');
+
+ expect($toolNames)
+ ->toContain('validate_form_definition', 'create_form', 'list_forms', 'list_submissions')
+ ->not->toContain(
+ 'create_form_draft',
+ 'get_form_draft',
+ 'patch_form_draft',
+ 'preview_form_draft',
+ 'open_form_draft_in_editor',
+ );
+
+ $resourcesResponse = $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 2,
+ 'method' => 'resources/list',
+ 'params' => [],
+ ], $headers)->assertOk();
+ $resourceUris = collect($resourcesResponse->json('result.resources'))->pluck('uri');
+
+ expect($resourceUris)
+ ->toContain('opnform://schemas/agent-form-definition/v1', 'opnform://reference/form-fields/v1')
+ ->not->toContain('ui://opnform/form-draft-preview-v3');
+
+ $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 3,
+ 'method' => 'tools/call',
+ 'params' => [
+ 'name' => 'create_form_draft',
+ 'arguments' => ['definition' => managedFormDefinition()],
+ ],
+ ], $headers)->assertOk()
+ ->assertJsonPath('error.code', -32602)
+ ->assertJsonPath('error.message', 'Tool [create_form_draft] not found.');
+});
+
+it('lists only the connected account workspaces with form write capability', function () {
+ $user = User::factory()->create();
+ $writable = managedWorkspace($user);
+ $readonly = managedWorkspace($user, User::ROLE_READONLY);
+ Workspace::factory()->create(['name' => 'Other account workspace']);
+
+ OpnFormServer::actingAs($user, 'oauth')
+ ->tool(GetAccountContextTool::class)
+ ->assertOk()
+ ->assertSee([$user->email, $writable->name, $readonly->name])
+ ->assertDontSee('Other account workspace');
+
+ OpnFormServer::actingAs($user, 'oauth')
+ ->tool(ListWorkspacesTool::class)
+ ->assertOk()
+ ->assertSee(['can_write_forms', User::ROLE_READONLY]);
+});
+
+it('creates an unpublished form automatically when the account has one workspace', function () {
+ $user = User::factory()->create();
+ $workspace = managedWorkspace($user);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(CreateFormTool::class, [
+ 'definition' => managedFormDefinition(['visibility' => 'public']),
+ ])->assertOk()
+ ->assertSee(['unpublished draft', 'Agent-managed intake', 'publish_form']);
+
+ $form = Form::query()->sole();
+ expect($form->workspace_id)->toBe($workspace->id)
+ ->and($form->creator_id)->toBe($user->id)
+ ->and($form->visibility)->toBe('draft')
+ ->and($form->edit_url)->toBeString()->not->toBeEmpty();
+});
+
+it('requires workspace selection only when multiple workspaces are available', function () {
+ $user = User::factory()->create();
+ $selected = managedWorkspace($user);
+ managedWorkspace($user);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(CreateFormTool::class, [
+ 'definition' => managedFormDefinition(),
+ ])->assertHasErrors(['multiple workspaces']);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(CreateFormTool::class, [
+ 'workspace_id' => $selected->id,
+ 'definition' => managedFormDefinition(),
+ ])->assertOk();
+
+ expect(Form::query()->sole()->workspace_id)->toBe($selected->id);
+});
+
+it('allows readonly members to inspect forms but rejects every mutation', function () {
+ $owner = User::factory()->create();
+ $readonly = User::factory()->create();
+ $workspace = managedWorkspace($owner);
+ $workspace->users()->attach($readonly, ['role' => User::ROLE_READONLY]);
+ $form = managedForm($owner, $workspace);
+
+ OpnFormServer::actingAs($readonly, 'oauth')->tool(GetFormTool::class, [
+ 'form_id' => $form->id,
+ ])->assertOk()->assertSee('Existing managed form');
+
+ OpnFormServer::actingAs($readonly, 'oauth')->tool(CreateFormTool::class, [
+ 'workspace_id' => $workspace->id,
+ 'definition' => managedFormDefinition(),
+ ])->assertHasErrors(['read-only']);
+
+ OpnFormServer::actingAs($readonly, 'oauth')->tool(PublishFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => managedFormRevision($readonly, $form),
+ 'confirm_publish' => true,
+ ])->assertHasErrors(['read-only']);
+});
+
+it('lists and searches only accessible non-trashed forms', function () {
+ $user = User::factory()->create();
+ $workspace = managedWorkspace($user);
+ managedForm($user, $workspace, ['title' => 'Customer survey']);
+ $trashed = managedForm($user, $workspace, ['title' => 'Customer survey old']);
+ $trashed->delete();
+
+ $other = User::factory()->create();
+ managedForm($other, managedWorkspace($other), ['title' => 'Customer survey secret']);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(ListFormsTool::class, [
+ 'search' => 'customer',
+ 'visibility' => 'draft',
+ ])->assertOk()
+ ->assertSee('Customer survey')
+ ->assertDontSee(['Customer survey old', 'Customer survey secret']);
+});
+
+it('updates a canonical form without changing publication state and rejects stale writes', function () {
+ $user = User::factory()->create();
+ $workspace = managedWorkspace($user);
+ $form = managedForm($user, $workspace, ['visibility' => 'public']);
+ $management = app(\App\Service\Forms\McpFormManagementService::class);
+ $expectedRevision = $management->serializeForm($management->form($user, $form->id))['revision'];
+ $queries = [];
+ DB::listen(function (QueryExecuted $query) use (&$queries) {
+ $queries[] = $query->sql;
+ });
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(UpdateFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => $expectedRevision,
+ 'definition' => managedFormDefinition([
+ 'title' => 'Updated by agent',
+ 'visibility' => 'draft',
+ ]),
+ ])->assertOk()->assertSee('Updated by agent');
+
+ expect($form->refresh()->visibility)->toBe('public');
+
+ if (DB::connection()->getDriverName() !== 'sqlite') {
+ expect(collect($queries)->contains(fn (string $query) => str_contains(strtolower($query), 'for update')))->toBeTrue();
+ }
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(UpdateFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => $expectedRevision,
+ 'definition' => managedFormDefinition(['title' => 'Stale overwrite']),
+ ])->assertHasErrors(['changed since it was fetched']);
+
+ expect($form->refresh()->title)->toBe('Updated by agent');
+});
+
+it('rejects Stripe accounts outside the selected workspace on create and update', function () {
+ $user = User::factory()->create();
+ $workspace = managedWorkspace($user);
+ $form = managedForm($user, $workspace);
+ $foreignProvider = OAuthProvider::factory()->for(User::factory()->create())->create([
+ 'provider' => 'stripe',
+ 'provider_user_id' => 'acct_foreign',
+ ]);
+ $definition = managedFormDefinition([
+ 'properties' => [[
+ 'id' => 'payment-field',
+ 'name' => 'Payment',
+ 'type' => 'payment',
+ 'amount' => 10,
+ 'currency' => 'USD',
+ 'stripe_account_id' => $foreignProvider->id,
+ ]],
+ ]);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(CreateFormTool::class, [
+ 'workspace_id' => $workspace->id,
+ 'definition' => $definition,
+ ])->assertHasErrors(['not associated with this workspace']);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(UpdateFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => managedFormRevision($user, $form),
+ 'definition' => $definition,
+ ])->assertHasErrors(['not associated with this workspace']);
+
+ expect(Form::query()->count())->toBe(1)
+ ->and($form->refresh()->properties)->toBe(managedFormDefinition()['properties']);
+});
+
+it('publishes only with confirmation and exposes no publication through update_form', function () {
+ $user = User::factory()->create();
+ $form = managedForm($user, managedWorkspace($user));
+ $expectedRevision = managedFormRevision($user, $form);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(PublishFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => $expectedRevision,
+ 'confirm_publish' => false,
+ ])->assertHasErrors(['explicit confirmation']);
+
+ expect($form->refresh()->visibility)->toBe('draft');
+
+ $form->update(['title' => 'Changed after confirmation context']);
+ OpnFormServer::actingAs($user, 'oauth')->tool(PublishFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => $expectedRevision,
+ 'confirm_publish' => true,
+ ])->assertHasErrors(['changed since it was fetched']);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(PublishFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => managedFormRevision($user, $form),
+ 'confirm_publish' => true,
+ ])->assertOk()->assertSee('Form published');
+
+ expect($form->refresh()->visibility)->toBe('public');
+});
+
+it('moves forms to soft-delete trash only with confirmation', function () {
+ $user = User::factory()->create();
+ $form = managedForm($user, managedWorkspace($user));
+ $expectedRevision = managedFormRevision($user, $form);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(TrashFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => $expectedRevision,
+ 'confirm_trash' => false,
+ ])->assertHasErrors(['explicit confirmation']);
+
+ $this->assertNotSoftDeleted($form);
+
+ $form->update(['title' => 'Changed after confirmation context']);
+ OpnFormServer::actingAs($user, 'oauth')->tool(TrashFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => $expectedRevision,
+ 'confirm_trash' => true,
+ ])->assertHasErrors(['changed since it was fetched']);
+
+ OpnFormServer::actingAs($user, 'oauth')->tool(TrashFormTool::class, [
+ 'form_id' => $form->id,
+ 'expected_revision' => managedFormRevision($user, $form),
+ 'confirm_trash' => true,
+ ])->assertOk()->assertSee(['moved to trash', 'does not expose restore']);
+
+ $this->assertSoftDeleted($form);
+});
+
+it('returns canonical definitions for legacy forms without mutating them', function () {
+ $user = User::factory()->create();
+ $form = managedForm($user, managedWorkspace($user));
+
+ $definition = app(AgentFormDefinition::class)->fromForm($form);
+
+ expect($definition)
+ ->toHaveKey('schema_version', 1)
+ ->toHaveKey('title', 'Existing managed form')
+ ->toHaveKey('properties')
+ ->not->toHaveKey('creator_id')
+ ->not->toHaveKey('workspace_id');
+});
diff --git a/api/tests/Feature/Mcp/GuestDraftToolsTest.php b/api/tests/Feature/Mcp/GuestDraftToolsTest.php
new file mode 100644
index 000000000..5ba525b3c
--- /dev/null
+++ b/api/tests/Feature/Mcp/GuestDraftToolsTest.php
@@ -0,0 +1,234 @@
+<?php
+
+use App\Mcp\Servers\OpnFormServer;
+use App\Mcp\Tools\CreateFormDraftTool;
+use App\Mcp\Tools\GetFormDraftTool;
+use App\Mcp\Tools\PatchFormDraftTool;
+use App\Models\Forms\AgentFormDraft;
+use App\Service\Forms\AgentFormDraftRateLimiter;
+use App\Service\Forms\AgentFormDraftService;
+use Illuminate\Validation\ValidationException;
+
+function guestDraftDefinition(array $overrides = []): array
+{
+ return array_replace([
+ 'title' => 'Customer intake',
+ 'properties' => [
+ ['id' => 'name-field', 'name' => 'Name', 'type' => 'text'],
+ ['id' => 'email-field', 'name' => 'Email', 'type' => 'email'],
+ ],
+ ], $overrides);
+}
+
+beforeEach(function () {
+ config()->set('app.self_hosted', false);
+});
+
+it('creates a seven-day server-side guest draft and only stores a token hash', function () {
+ $before = now();
+
+ OpnFormServer::tool(CreateFormDraftTool::class, [
+ 'definition' => guestDraftDefinition(['visibility' => 'public']),
+ ])->assertOk()
+ ->assertSee('draft_token')
+ ->assertSee('Customer intake')
+ ->assertSee('expected_version');
+
+ $draft = AgentFormDraft::query()->sole();
+
+ expect($draft->token_hash)->toMatch('/^[a-f0-9]{64}$/')
+ ->and($draft->definition['visibility'])->toBe('draft')
+ ->and($draft->version)->toBe(1)
+ ->and($draft->schema_version)->toBe(1)
+ ->and($draft->status)->toBe(AgentFormDraft::STATUS_ACTIVE)
+ ->and($draft->expires_at->betweenIncluded($before->copy()->addDays(7)->subSecond(), now()->addDays(7)->addSecond()))->toBeTrue();
+
+ $this->assertDatabaseCount('forms', 0);
+});
+
+it('fetches a draft with its capability token without exposing stored secrets', function () {
+ $created = app(AgentFormDraftService::class)->create(guestDraftDefinition());
+
+ OpnFormServer::tool(GetFormDraftTool::class, [
+ 'draft_token' => $created['token'],
+ ])->assertOk()
+ ->assertSee('Customer intake')
+ ->assertDontSee($created['draft']->token_hash)
+ ->assertDontSee('token_hash');
+});
+
+it('patches form values and blocks with optimistic versioning', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(guestDraftDefinition());
+
+ $response = OpnFormServer::tool(PatchFormDraftTool::class, [
+ 'draft_token' => $created['token'],
+ 'expected_version' => 1,
+ 'operations' => [
+ [
+ 'op' => 'set_form_values',
+ 'values' => ['title' => 'Qualified lead', 'visibility' => 'public'],
+ ],
+ [
+ 'op' => 'update_block',
+ 'block_id' => 'name-field',
+ 'patch' => ['name' => 'Full legal name', 'required' => true],
+ ],
+ [
+ 'op' => 'add_block',
+ 'index' => 1,
+ 'block' => ['name' => 'Company', 'type' => 'text'],
+ ],
+ [
+ 'op' => 'move_block',
+ 'block_id' => 'email-field',
+ 'to_index' => 0,
+ ],
+ ],
+ ]);
+
+ $response->assertOk()
+ ->assertSee('Qualified lead')
+ ->assertSee('Full legal name')
+ ->assertSee('version');
+
+ $updated = $created['draft']->refresh();
+
+ expect($updated->version)->toBe(2)
+ ->and($updated->definition['visibility'])->toBe('draft')
+ ->and($updated->definition['properties'][0]['id'])->toBe('email-field')
+ ->and($updated->definition['properties'][1]['name'])->toBe('Full legal name')
+ ->and($updated->definition['properties'][1]['required'])->toBeTrue()
+ ->and($updated->definition['properties'][2]['name'])->toBe('Company')
+ ->and($updated->definition['properties'][2]['id'])->toBeString()->not->toBeEmpty();
+});
+
+it('rejects stale patches without changing the draft', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(guestDraftDefinition());
+
+ $drafts->patch($created['token'], 1, [[
+ 'op' => 'set_form_values',
+ 'values' => ['title' => 'First update'],
+ ]]);
+
+ OpnFormServer::tool(PatchFormDraftTool::class, [
+ 'draft_token' => $created['token'],
+ 'expected_version' => 1,
+ 'operations' => [[
+ 'op' => 'set_form_values',
+ 'values' => ['title' => 'Stale overwrite'],
+ ]],
+ ])->assertHasErrors(['Current version is 2']);
+
+ expect($created['draft']->refresh()->definition['title'])->toBe('First update')
+ ->and($created['draft']->version)->toBe(2);
+});
+
+it('rolls back invalid patch operations and preserves the previous version', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(guestDraftDefinition([
+ 'properties' => [
+ ['id' => 'only-field', 'name' => 'Name', 'type' => 'text'],
+ ],
+ ]));
+
+ OpnFormServer::tool(PatchFormDraftTool::class, [
+ 'draft_token' => $created['token'],
+ 'expected_version' => 1,
+ 'operations' => [[
+ 'op' => 'remove_block',
+ 'block_id' => 'only-field',
+ ]],
+ ])->assertHasErrors();
+
+ expect($created['draft']->refresh()->version)->toBe(1)
+ ->and($created['draft']->definition['properties'])->toHaveCount(1);
+});
+
+it('rejects malformed, expired, and claimed draft capabilities with one generic error', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $created = $drafts->create(guestDraftDefinition());
+
+ OpnFormServer::tool(GetFormDraftTool::class, [
+ 'draft_token' => str_repeat('x', 43),
+ ])->assertHasErrors(['Draft not found, expired, or already claimed']);
+
+ $created['draft']->forceFill(['expires_at' => now()->subSecond()])->save();
+
+ OpnFormServer::tool(GetFormDraftTool::class, [
+ 'draft_token' => $created['token'],
+ ])->assertHasErrors(['Draft not found, expired, or already claimed']);
+
+ $claimed = $drafts->create(guestDraftDefinition());
+ $claimed['draft']->forceFill(['status' => AgentFormDraft::STATUS_CLAIMED])->save();
+
+ OpnFormServer::tool(GetFormDraftTool::class, [
+ 'draft_token' => $claimed['token'],
+ ])->assertHasErrors(['Draft not found, expired, or already claimed']);
+});
+
+it('rejects duplicate block ids', function () {
+ OpnFormServer::tool(CreateFormDraftTool::class, [
+ 'definition' => guestDraftDefinition([
+ 'properties' => [
+ ['id' => 'duplicate', 'name' => 'One', 'type' => 'text'],
+ ['id' => 'duplicate', 'name' => 'Two', 'type' => 'email'],
+ ],
+ ]),
+ ])->assertHasErrors(['unique id']);
+});
+
+it('rejects oversized draft definitions before persistence', function () {
+ OpnFormServer::tool(CreateFormDraftTool::class, [
+ 'definition' => guestDraftDefinition([
+ 'custom_code' => str_repeat('x', 1_000_001),
+ ]),
+ ])->assertHasErrors(['must not exceed 1 MB']);
+
+ $this->assertDatabaseCount('agent_form_drafts', 0);
+});
+
+it('sanitizes rich text html before an agent draft can be rendered', function () {
+ $created = app(AgentFormDraftService::class)->create(guestDraftDefinition([
+ 'properties' => [[
+ 'id' => 'rich-text',
+ 'name' => 'Introduction',
+ 'type' => 'nf-text',
+ 'content' => '<p>Hello</p><img src=x onerror="alert(1)"><script>alert(2)</script>',
+ ]],
+ ]));
+
+ $content = $created['draft']->definition['properties'][0]['content'];
+ expect($content)->toContain('<p>Hello</p>')
+ ->not->toContain('onerror')
+ ->not->toContain('<script');
+});
+
+it('rate limits only excessive draft creation bursts', function () {
+ config()->set('opnform.mcp.rate_limit.draft_creates_per_minute', 2);
+ config()->set('opnform.mcp.rate_limit.draft_creates_per_hour', 10);
+ $limiter = app(AgentFormDraftRateLimiter::class);
+
+ $limiter->hit('ip:192.0.2.1');
+ $limiter->hit('ip:192.0.2.1');
+
+ expect(fn () => $limiter->hit('ip:192.0.2.1'))
+ ->toThrow(ValidationException::class, 'Too many drafts');
+
+ expect(fn () => $limiter->hit('ip:192.0.2.2'))->not->toThrow(ValidationException::class);
+});
+
+it('purges only expired agent drafts with the scheduled command', function () {
+ $drafts = app(AgentFormDraftService::class);
+ $active = $drafts->create(guestDraftDefinition())['draft'];
+ $expired = $drafts->create(guestDraftDefinition())['draft'];
+ $expired->forceFill(['expires_at' => now()->subMinute()])->save();
+
+ $this->artisan('agent-drafts:purge-expired')
+ ->expectsOutput('Purged 1 expired agent form draft(s).')
+ ->assertSuccessful();
+
+ $this->assertDatabaseHas('agent_form_drafts', ['id' => $active->id]);
+ $this->assertDatabaseMissing('agent_form_drafts', ['id' => $expired->id]);
+});
diff --git a/api/tests/Feature/Mcp/McpAvailabilityTest.php b/api/tests/Feature/Mcp/McpAvailabilityTest.php
new file mode 100644
index 000000000..181e98748
--- /dev/null
+++ b/api/tests/Feature/Mcp/McpAvailabilityTest.php
@@ -0,0 +1,153 @@
+<?php
+
+use App\Support\Mcp\McpAvailability;
+use App\Enums\SettingsKey;
+use App\Models\Setting;
+use Symfony\Component\Process\Process;
+
+function configureOperationalSelfHostedMcp(): void
+{
+ $key = openssl_pkey_new([
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,
+ ]);
+ openssl_pkey_export($key, $privateKey);
+ $details = openssl_pkey_get_details($key);
+
+ config()->set('oauth.enabled', true);
+ config()->set('app.url', 'https://forms.example.com');
+ config()->set('app.front_url', 'https://forms.example.com');
+ config()->set('passport.private_key', $privateKey);
+ config()->set('passport.public_key', $details['key']);
+}
+
+it('enables MCP on cloud instances regardless of the self-hosted opt-in flag', function (bool $configured) {
+ config()->set('app.self_hosted', false);
+ config()->set('opnform.mcp.enabled', $configured);
+
+ expect(app(McpAvailability::class)->enabled())->toBeTrue();
+})->with([false, true]);
+
+it('requires self-hosted instances to opt in to MCP', function (bool $configured, bool $expected) {
+ config()->set('app.self_hosted', true);
+ config()->set('opnform.mcp.enabled', $configured);
+ Setting::forget(SettingsKey::MCP_ENABLED);
+
+ expect(app(McpAvailability::class)->enabled())->toBe($expected);
+})->with([
+ 'disabled' => [false, false],
+ 'enabled' => [true, true],
+]);
+
+it('uses the stored self-hosted setting before the environment default', function (bool $environment, bool $stored, bool $expected) {
+ config()->set('app.self_hosted', true);
+ config()->set('opnform.mcp.enabled', $environment);
+ Setting::set(SettingsKey::MCP_ENABLED, $stored);
+
+ expect(app(McpAvailability::class)->enabled())->toBe($expected);
+})->with([
+ 'stored enable overrides disabled environment' => [false, true, true],
+ 'stored disable overrides enabled environment' => [true, false, false],
+]);
+
+it('allows guest drafts only on cloud instances', function (bool $selfHosted, bool $mcpEnabled, bool $expected) {
+ config()->set('app.self_hosted', $selfHosted);
+ config()->set('opnform.mcp.enabled', $mcpEnabled);
+ Setting::forget(SettingsKey::MCP_ENABLED);
+
+ expect(app(McpAvailability::class)->guestDraftsEnabled())->toBe($expected);
+})->with([
+ 'cloud' => [false, false, true],
+ 'self-hosted disabled' => [true, false, false],
+ 'self-hosted enabled' => [true, true, false],
+]);
+
+it('keeps an enabled self-hosted MCP unavailable until OAuth is ready', function () {
+ config()->set('app.self_hosted', true);
+ config()->set('opnform.mcp.enabled', true);
+ config()->set('oauth.enabled', false);
+ Setting::forget(SettingsKey::MCP_ENABLED);
+
+ expect(app(McpAvailability::class)->enabled())->toBeTrue()
+ ->and(app(McpAvailability::class)->available())->toBeFalse();
+
+ $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/list',
+ 'params' => [],
+ ], ['Accept' => 'application/json, text/event-stream'])->assertNotFound();
+});
+
+it('registers MCP routes even when a self-hosted instance is disabled so runtime settings work with route caching', function () {
+ $process = new Process(
+ [PHP_BINARY, 'artisan', 'route:list', '--json'],
+ base_path(),
+ ['SELF_HOSTED' => 'true', 'MCP_ENABLED' => 'false'],
+ );
+ $process->mustRun();
+
+ $routes = collect(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR));
+
+ expect($routes->pluck('uri')->all())
+ ->toContain('mcp')
+ ->toContain('agent-drafts/preview/{draft}')
+ ->toContain('mcp-oauth/session')
+ ->toContain('oauth/token')
+ ->toContain('oauth/authorize');
+});
+
+it('returns not found from MCP endpoints when a self-hosted admin disables MCP', function (string $method, string $uri) {
+ config()->set('app.self_hosted', true);
+ Setting::set(SettingsKey::MCP_ENABLED, false);
+
+ $this->json($method, $uri)->assertNotFound();
+})->with([
+ 'MCP server request' => ['POST', '/mcp'],
+ 'MCP browser request' => ['GET', '/mcp'],
+ 'MCP session close' => ['DELETE', '/mcp'],
+ 'OAuth discovery' => ['GET', '/.well-known/oauth-authorization-server'],
+ 'OAuth token exchange' => ['POST', '/oauth/token'],
+ 'OAuth authorization' => ['GET', '/oauth/authorize'],
+ 'OAuth dynamic client registration' => ['POST', '/oauth/register'],
+ 'guest preview' => ['GET', '/agent-drafts/preview/1'],
+ 'OAuth session' => ['POST', '/mcp-oauth/session'],
+]);
+
+it('returns not found from every guest draft endpoint on an enabled self-hosted instance', function (string $method, string $uri) {
+ config()->set('app.self_hosted', true);
+ configureOperationalSelfHostedMcp();
+ Setting::set(SettingsKey::MCP_ENABLED, true);
+
+ $this->json($method, $uri)->assertNotFound();
+})->with([
+ 'guest preview' => ['GET', '/agent-drafts/preview/1'],
+ 'guest handoff' => ['POST', '/agent-drafts/handoff/consume'],
+ 'guest editor read' => ['GET', '/agent-drafts/editor/current'],
+ 'guest editor replace' => ['PUT', '/agent-drafts/editor/current'],
+ 'guest editor claim' => ['POST', '/agent-drafts/editor/claim'],
+]);
+
+it('keeps MCP routes registered when delegated OAuth is disabled', function () {
+ $process = new Process(
+ [PHP_BINARY, 'artisan', 'route:list', '--json'],
+ base_path(),
+ [
+ 'SELF_HOSTED' => 'true',
+ 'MCP_ENABLED' => 'true',
+ 'OAUTH_ENABLED' => 'false',
+ ],
+ );
+ $process->mustRun();
+
+ $routes = collect(json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR));
+ $uris = $routes->pluck('uri')->all();
+
+ expect($uris)
+ ->toContain('mcp')
+ ->toContain('agent-drafts/preview/{draft}')
+ ->not->toContain('api/mcp-oauth/session')
+ ->not->toContain('oauth/token')
+ ->not->toContain('oauth/authorize')
+ ->not->toContain('.well-known/oauth-authorization-server');
+});
diff --git a/api/tests/Feature/Mcp/McpFoundationTest.php b/api/tests/Feature/Mcp/McpFoundationTest.php
new file mode 100644
index 000000000..7ad54b4f7
--- /dev/null
+++ b/api/tests/Feature/Mcp/McpFoundationTest.php
@@ -0,0 +1,238 @@
+<?php
+
+use App\Mcp\Resources\FormDefinitionSchemaResource;
+use App\Mcp\Resources\FormFieldCatalogResource;
+use App\Mcp\Servers\OpnFormServer;
+use App\Mcp\Tools\ValidateFormDefinitionTool;
+use App\Service\Forms\AgentFormDefinition;
+use Illuminate\Testing\Fluent\AssertableJson;
+use Illuminate\Support\Facades\RateLimiter;
+
+it('exposes the OpnForm MCP endpoint and initializes the protocol', function () {
+ $response = $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'initialize',
+ 'params' => [
+ 'protocolVersion' => '2025-06-18',
+ 'capabilities' => [],
+ 'clientInfo' => [
+ 'name' => 'OpnForm test client',
+ 'version' => '1.0.0',
+ ],
+ ],
+ ], [
+ 'Accept' => 'application/json, text/event-stream',
+ ]);
+
+ $response->assertOk()
+ ->assertJsonPath('result.serverInfo.name', 'OpnForm')
+ ->assertJsonPath('result.serverInfo.version', '1.0.0')
+ ->assertJsonPath('result.protocolVersion', '2025-06-18')
+ ->assertJsonPath('result.instructions', function (string $instructions): bool {
+ $discoveryInstructions = substr($instructions, 0, 512);
+
+ return str_contains($discoveryInstructions, 'Never invoke Codex or ChatGPT recursively')
+ && str_contains($discoveryInstructions, 'OpnForm selected before the first message')
+ && str_contains($discoveryInstructions, 'account, form, and submission tools require OAuth')
+ && str_contains($discoveryInstructions, 'Enabling the plugin is not OAuth authentication')
+ && str_contains($discoveryInstructions, 'start a new conversation after OAuth');
+ });
+});
+
+it('registers a permissive dedicated rate limiter for MCP traffic', function () {
+ $limits = RateLimiter::limiter('mcp')(request());
+
+ expect($limits)->toHaveCount(2)
+ ->and($limits[0]->maxAttempts)->toBe(120)
+ ->and($limits[1]->maxAttempts)->toBe(3000);
+});
+
+it('publishes the versioned form definition schema', function () {
+ OpnFormServer::resource(FormDefinitionSchemaResource::class)
+ ->assertOk()
+ ->assertSee('agent-form-definition/v1.json')
+ ->assertSee('schema_version')
+ ->assertSee('properties');
+});
+
+it('keeps every normalized top-level key represented in the published schema', function () {
+ $definition = app(AgentFormDefinition::class);
+ $normalized = $definition->normalizeAndValidate([
+ 'title' => 'Schema coverage',
+ 'properties' => [
+ ['name' => 'Name', 'type' => 'text'],
+ ],
+ ]);
+
+ expect(array_diff(array_keys($normalized), array_keys($definition->jsonSchema()['properties'])))->toBe([]);
+});
+
+it('publishes the canonical form field catalog', function () {
+ OpnFormServer::resource(FormFieldCatalogResource::class)
+ ->assertOk()
+ ->assertSee('input_types')
+ ->assertSee('nf-page-break')
+ ->assertSee('payment')
+ ->assertSee('presentation_modes')
+ ->assertSee('focused')
+ ->assertSee('block_media')
+ ->assertSee('trycloudflare.com')
+ ->assertSee('save');
+});
+
+it('requires public durable HTTPS URLs for agent-provided media', function () {
+ $definition = app(AgentFormDefinition::class);
+
+ expect(fn () => $definition->normalizeAndValidate([
+ 'title' => 'Unsafe media',
+ 'cover_picture' => 'http://127.0.0.1/cover.png',
+ 'properties' => [
+ ['name' => 'Name', 'type' => 'text'],
+ ],
+ ]))->toThrow(\Illuminate\Validation\ValidationException::class);
+
+ $validated = $definition->normalizeAndValidate([
+ 'title' => 'Safe media',
+ 'cover_picture' => 'https://cdn.example.com/cover.png',
+ 'logo_picture' => 'https://cdn.example.com/logo.png',
+ 'properties' => [
+ ['name' => 'Name', 'type' => 'text'],
+ ],
+ ]);
+
+ expect($validated['cover_picture'])->toBe('https://cdn.example.com/cover.png')
+ ->and($validated['logo_picture'])->toBe('https://cdn.example.com/logo.png');
+});
+
+it('documents block media in the published form definition schema', function () {
+ $schema = app(AgentFormDefinition::class)->jsonSchema();
+
+ expect($schema['$defs']['block']['properties']['image']['$ref'])
+ ->toBe('#/$defs/blockImage')
+ ->and($schema['$defs']['blockImage'])->not->toHaveKey('required')
+ ->and($schema['$defs']['blockImage']['properties']['url']['type'])->toBe(['string', 'null'])
+ ->and($schema['$defs']['blockImage']['properties']['layout']['enum'])
+ ->toContain('right-split', 'background');
+});
+
+it('applies the public media URL policy to block images', function () {
+ $definition = app(AgentFormDefinition::class);
+
+ expect(fn () => $definition->normalizeAndValidate([
+ 'title' => 'Unsafe block image',
+ 'properties' => [
+ [
+ 'name' => 'Introduction',
+ 'type' => 'nf-text',
+ 'content' => '<p>Welcome</p>',
+ 'image' => ['url' => 'https://draft.trycloudflare.com/image.png'],
+ ],
+ ],
+ ]))->toThrow(\Illuminate\Validation\ValidationException::class);
+
+ $validated = $definition->normalizeAndValidate([
+ 'title' => 'Safe block image',
+ 'properties' => [
+ [
+ 'name' => 'Introduction',
+ 'type' => 'nf-text',
+ 'content' => '<p>Welcome</p>',
+ 'image' => ['url' => 'https://cdn.example.com/image.png'],
+ ],
+ ],
+ ]);
+
+ expect($validated['properties'][0]['image']['url'])->toBe('https://cdn.example.com/image.png');
+});
+it('normalizes and validates a form definition without persistence', function () {
+ OpnFormServer::tool(ValidateFormDefinitionTool::class, [
+ 'definition' => [
+ 'title' => ' Customer intake ',
+ 'properties' => [
+ [
+ 'name' => '<b>Full name</b>',
+ 'type' => 'text',
+ 'help' => '<script>alert(1)</script><p>Legal name</p>',
+ ],
+ [
+ 'name' => 'Plan',
+ 'type' => 'radio',
+ 'select' => [
+ 'options' => [
+ ['name' => 'Basic'],
+ ['name' => 'Pro'],
+ ],
+ ],
+ ],
+ ],
+ ],
+ ])->assertOk()
+ ->assertStructuredContent(function (AssertableJson $json) {
+ $json->where('valid', true)
+ ->where('schema_version', 1)
+ ->where('definition.title', 'Customer intake')
+ ->where('definition.visibility', 'draft')
+ ->where('definition.properties.0.name', 'Full name')
+ ->where('definition.properties.0.hidden', false)
+ ->where('definition.properties.1.type', 'select')
+ ->where('definition.properties.1.without_dropdown', true)
+ ->where('definition.properties.1.select.options.0.id', 'Basic')
+ ->has('definition.properties.0.id')
+ ->etc();
+ });
+
+ $this->assertDatabaseCount('forms', 0);
+});
+
+it('rejects unknown field types and top-level keys', function () {
+ OpnFormServer::tool(ValidateFormDefinitionTool::class, [
+ 'definition' => [
+ 'title' => 'Invalid form',
+ 'surprise' => true,
+ 'properties' => [
+ ['name' => 'Unknown', 'type' => 'not-a-field'],
+ ],
+ ],
+ ])->assertHasErrors();
+});
+
+it('applies the same custom CSS and settings validation as the form API', function () {
+ $definition = [
+ 'title' => 'Unsafe customization',
+ 'properties' => [
+ ['name' => 'Name', 'type' => 'text'],
+ ],
+ ];
+
+ OpnFormServer::tool(ValidateFormDefinitionTool::class, [
+ 'definition' => array_merge($definition, [
+ 'custom_css' => '</style><script>alert(1)</script>',
+ ]),
+ ])->assertHasErrors(['valid CSS']);
+
+ OpnFormServer::tool(ValidateFormDefinitionTool::class, [
+ 'definition' => array_merge($definition, [
+ 'settings' => ['auto_next' => 'yes'],
+ ]),
+ ])->assertHasErrors(['true or false']);
+
+ OpnFormServer::tool(ValidateFormDefinitionTool::class, [
+ 'definition' => array_merge($definition, [
+ 'custom_css' => '.form-root { color: #2563eb; }',
+ 'settings' => ['auto_next' => true],
+ ]),
+ ])->assertOk();
+});
+
+it('rejects unsupported schema versions', function () {
+ OpnFormServer::tool(ValidateFormDefinitionTool::class, [
+ 'definition' => [
+ 'schema_version' => 99,
+ 'title' => 'Future form',
+ 'properties' => [
+ ['name' => 'Name', 'type' => 'text'],
+ ],
+ ],
+ ])->assertHasErrors(['Unsupported schema version']);
+});
diff --git a/api/tests/Feature/Mcp/McpOAuthKeysCommandTest.php b/api/tests/Feature/Mcp/McpOAuthKeysCommandTest.php
new file mode 100644
index 000000000..bb175457b
--- /dev/null
+++ b/api/tests/Feature/Mcp/McpOAuthKeysCommandTest.php
@@ -0,0 +1,73 @@
+<?php
+
+use Illuminate\Support\Facades\File;
+use Laravel\Passport\Passport;
+
+function temporaryPassportKeyPair(): array
+{
+ $key = openssl_pkey_new([
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,
+ ]);
+ openssl_pkey_export($key, $privateKey);
+ $details = openssl_pkey_get_details($key);
+
+ return [$privateKey, $details['key']];
+}
+
+beforeEach(function () {
+ $this->originalPassportKeyPath = Passport::$keyPath;
+ $this->emptyPassportKeyPath = storage_path('framework/testing/passport-keys-'.uniqid());
+ File::ensureDirectoryExists($this->emptyPassportKeyPath);
+ Passport::loadKeysFrom($this->emptyPassportKeyPath);
+ config()->set('passport.private_key');
+ config()->set('passport.public_key');
+});
+
+afterEach(function () {
+ Passport::$keyPath = $this->originalPassportKeyPath;
+ File::deleteDirectory($this->emptyPassportKeyPath);
+});
+
+it('accepts a valid stable Passport key pair from the environment', function () {
+ [$privateKey, $publicKey] = temporaryPassportKeyPair();
+ config()->set('passport.private_key', str_replace("\n", '\\n', $privateKey));
+ config()->set('passport.public_key', str_replace("\n", '\\n', $publicKey));
+
+ $this->artisan('mcp:check-oauth-keys --environment-only')
+ ->expectsOutputToContain('configured and valid')
+ ->assertSuccessful();
+});
+
+it('fails when Passport keys are missing', function () {
+ $this->artisan('mcp:check-oauth-keys --environment-only')
+ ->expectsOutputToContain('requires both')
+ ->assertFailed();
+});
+
+it('fails when only one Passport environment key is configured', function () {
+ [$privateKey] = temporaryPassportKeyPair();
+ config()->set('passport.private_key', $privateKey);
+
+ $this->artisan('mcp:check-oauth-keys --environment-only')
+ ->expectsOutputToContain('requires both')
+ ->assertFailed();
+});
+
+it('fails when Passport keys do not belong to the same pair', function () {
+ [$privateKey] = temporaryPassportKeyPair();
+ [, $publicKey] = temporaryPassportKeyPair();
+ config()->set('passport.private_key', $privateKey);
+ config()->set('passport.public_key', $publicKey);
+
+ $this->artisan('mcp:check-oauth-keys --environment-only')
+ ->expectsOutputToContain('do not belong to the same pair')
+ ->assertFailed();
+});
+
+it('checks OAuth keys before running Vapor migrations', function () {
+ $vaporConfig = file_get_contents(base_path('vapor.yml'));
+ $checkBeforeMigrate = '/deploy:\s*\n\s*- "php artisan mcp:check-oauth-keys --environment-only"\s*\n\s*- "php artisan migrate --force"/';
+
+ expect(preg_match_all($checkBeforeMigrate, $vaporConfig))->toBe(2);
+});
diff --git a/api/tests/Feature/Mcp/McpOAuthTest.php b/api/tests/Feature/Mcp/McpOAuthTest.php
new file mode 100644
index 000000000..a89716b8d
--- /dev/null
+++ b/api/tests/Feature/Mcp/McpOAuthTest.php
@@ -0,0 +1,406 @@
+<?php
+
+use App\Models\User;
+use App\Service\OAuth\McpOAuthSessionService;
+use App\Service\OAuth\McpPassportClientRepository;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Cache;
+use Laravel\Passport\ClientRepository;
+use Laravel\Passport\Passport;
+use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
+
+beforeEach(function () {
+ config()->set('app.front_url', 'https://opnform.test');
+
+ $key = openssl_pkey_new([
+ 'digest_alg' => 'sha256',
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,
+ ]);
+ openssl_pkey_export($key, $privateKey);
+ $publicKey = openssl_pkey_get_details($key)['key'];
+
+ config()->set('passport.private_key', $privateKey);
+ config()->set('passport.public_key', $publicKey);
+});
+
+it('configures delegated OAuth through its dedicated provider', function () {
+ $jwtTtl = config('jwt.ttl');
+
+ expect(app(ClientRepository::class))->toBeInstanceOf(McpPassportClientRepository::class)
+ ->and(route('passport.token'))->toEndWith('/oauth/token')
+ ->and(route('passport.authorizations.authorize'))->toEndWith('/oauth/authorize')
+ ->and(config('auth.guards.oauth.driver'))->toBe('passport')
+ ->and(config('auth.guards.mcp'))->toBeNull()
+ ->and(config('auth.guards.api.driver'))->toBe('jwt');
+
+ config()->set('oauth.access_token_ttl', (int) $jwtTtl + 1);
+
+ expect(config('jwt.ttl'))->toBe($jwtTtl);
+});
+
+function mcpInitializePayload(): array
+{
+ return [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'initialize',
+ 'params' => [
+ 'protocolVersion' => '2025-06-18',
+ 'capabilities' => [],
+ 'clientInfo' => [
+ 'name' => 'OAuth test client',
+ 'version' => '1.0.0',
+ ],
+ ],
+ ];
+}
+
+function mcpHeaders(array $extra = []): array
+{
+ return array_merge([
+ 'Accept' => 'application/json, text/event-stream',
+ ], $extra);
+}
+
+it('publishes OAuth 2.1 discovery metadata for the unified MCP endpoint', function () {
+ $this->getJson('/.well-known/oauth-protected-resource/mcp')
+ ->assertOk()
+ ->assertJsonPath('resource', url('/mcp'))
+ ->assertJsonPath('authorization_servers.0', url('/'))
+ ->assertJsonPath('scopes_supported.0', 'mcp:use');
+
+ $this->getJson('/.well-known/oauth-authorization-server')
+ ->assertOk()
+ ->assertJsonPath('authorization_endpoint', route('passport.authorizations.authorize'))
+ ->assertJsonPath('token_endpoint', route('passport.token'))
+ ->assertJsonPath('registration_endpoint', url('/oauth/register'))
+ ->assertJsonPath('code_challenge_methods_supported.0', 'S256')
+ ->assertJsonPath('token_endpoint_auth_methods_supported.0', 'none')
+ ->assertJsonPath('scopes_supported.0', 'mcp:use');
+});
+
+it('requires S256 PKCE for every delegated authorization request', function (array $query) {
+ $this->getJson('/oauth/authorize?'.http_build_query($query))
+ ->assertBadRequest()
+ ->assertJsonPath('error', 'invalid_request')
+ ->assertJsonPath('error_description', 'The code_challenge_method must be S256.');
+})->with([
+ 'missing method' => [['code_challenge' => 'challenge']],
+ 'plain method' => [[
+ 'code_challenge' => 'challenge',
+ 'code_challenge_method' => 'plain',
+ ]],
+]);
+
+it('returns a tool-level OAuth challenge when an account tool is called anonymously', function () {
+ $response = $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/call',
+ 'params' => [
+ 'name' => 'list_forms',
+ 'arguments' => [],
+ ],
+ ], mcpHeaders())->assertOk()
+ ->assertJsonPath('result.isError', true);
+
+ $challenge = $response->json('result._meta.mcp/www_authenticate.0');
+
+ expect($challenge)
+ ->toContain('Bearer resource_metadata="'.route('mcp.oauth.protected-resource.nested', ['path' => 'mcp']).'"')
+ ->toContain('scope="mcp:use"')
+ ->toContain('error="insufficient_scope"')
+ ->toContain('error_description="Connect your OpnForm account to continue"');
+});
+
+it('does not treat a normal OpnForm web session as MCP authentication', function () {
+ $user = User::factory()->create();
+
+ $this->actingAs($user, 'web')->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/call',
+ 'params' => [
+ 'name' => 'get_account_context',
+ 'arguments' => [],
+ ],
+ ], mcpHeaders())->assertOk()
+ ->assertJsonPath('result.isError', true)
+ ->assertJsonPath('result._meta.mcp/www_authenticate.0', fn (string $challenge) => str_contains(
+ $challenge,
+ 'error="insufficient_scope"',
+ ));
+});
+
+it('uses a scoped MCP bearer token for account tool calls', function () {
+ $user = User::factory()->create();
+ Passport::actingAs($user, ['mcp:use'], 'oauth');
+
+ $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/call',
+ 'params' => [
+ 'name' => 'get_account_context',
+ 'arguments' => [],
+ ],
+ ], mcpHeaders([
+ 'Authorization' => 'Bearer scoped-account-token',
+ ]))->assertOk()
+ ->assertJsonPath('result.isError', false)
+ ->assertJsonPath('result.structuredContent.account.id', $user->id)
+ ->assertJsonMissingPath('result._meta.mcp/www_authenticate');
+});
+
+it('dynamically registers public PKCE clients only for allowed redirects', function () {
+ $this->postJson('/oauth/register', [
+ 'client_name' => 'ChatGPT',
+ 'redirect_uris' => ['https://chatgpt.com/connector/oauth/local-test'],
+ ])->assertCreated()
+ ->assertJsonPath('token_endpoint_auth_method', 'none')
+ ->assertJsonPath('scope', 'mcp:use')
+ ->assertJsonPath('redirect_uris.0', 'https://chatgpt.com/connector/oauth/local-test');
+
+ $this->assertDatabaseCount('oauth_clients', 1);
+
+ $this->postJson('/oauth/register', [
+ 'client_name' => 'Untrusted client',
+ 'redirect_uris' => ['https://attacker.example/callback'],
+ ])->assertBadRequest()
+ ->assertJsonPath('error', 'invalid_redirect_uri');
+
+ $this->assertDatabaseCount('oauth_clients', 1);
+
+ $this->postJson('/oauth/register', [
+ 'client_name' => 'Delimiter injection',
+ 'redirect_uris' => ['https://chatgpt.com/callback,https://attacker.example/callback'],
+ ])->assertBadRequest()
+ ->assertJsonPath('error', 'invalid_redirect_uri');
+
+ $this->assertDatabaseCount('oauth_clients', 1);
+
+ $this->postJson('/oauth/register', [
+ 'client_name' => 'Loopback userinfo injection',
+ 'redirect_uris' => ['http://localhost:[email protected]/callback'],
+ ])->assertBadRequest()
+ ->assertJsonPath('error', 'invalid_redirect_uri');
+
+ $this->assertDatabaseCount('oauth_clients', 1);
+});
+
+it('rejects PKCE methods other than S256', function () {
+ $registration = $this->postJson('/oauth/register', [
+ 'client_name' => 'Plain PKCE client',
+ 'redirect_uris' => ['http://localhost/callback'],
+ ])->assertCreated();
+
+ $this->actingAs(User::factory()->create(), 'web')
+ ->get('/oauth/authorize?'.http_build_query([
+ 'client_id' => $registration->json('client_id'),
+ 'redirect_uri' => 'http://localhost/callback',
+ 'response_type' => 'code',
+ 'scope' => 'mcp:use',
+ 'state' => 'oauth-state',
+ 'code_challenge' => str_repeat('a', 64),
+ 'code_challenge_method' => 'plain',
+ ]))
+ ->assertBadRequest()
+ ->assertJsonPath('error', 'invalid_request')
+ ->assertJsonPath('error_description', 'The code_challenge_method must be S256.');
+});
+
+it('keeps guest MCP available while accepting properly scoped Passport users', function () {
+ $this->postJson('/mcp', mcpInitializePayload(), mcpHeaders())
+ ->assertOk();
+
+ $user = User::factory()->create();
+ Passport::actingAs($user, ['mcp:use'], 'oauth');
+
+ $this->postJson('/mcp', mcpInitializePayload(), mcpHeaders([
+ 'Authorization' => 'Bearer test-passport-token',
+ ]))->assertOk();
+});
+
+it('completes PKCE authorization and uses the issued bearer token on the same endpoint', function () {
+ $registration = $this->postJson('/oauth/register', [
+ 'client_name' => 'MCP integration test',
+ 'redirect_uris' => ['http://localhost/callback'],
+ ])->assertCreated();
+
+ $clientId = $registration->json('client_id');
+ $verifier = str_repeat('a', 64);
+ $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
+ $authorizationQuery = http_build_query([
+ 'client_id' => $clientId,
+ 'redirect_uri' => 'http://localhost/callback',
+ 'response_type' => 'code',
+ 'scope' => 'mcp:use',
+ 'state' => 'oauth-state',
+ 'code_challenge' => $challenge,
+ 'code_challenge_method' => 'S256',
+ ]);
+
+ $user = User::factory()->create();
+ $consent = $this->actingAs($user, 'web')
+ ->get('/oauth/authorize?'.$authorizationQuery)
+ ->assertOk()
+ ->assertSee('Connect MCP integration test')
+ ->assertSee('Use OpnForm MCP features')
+ ->assertSee('http://localhost/callback')
+ ->assertSee('aria-label="OpnForm"', false)
+ ->assertHeader('Content-Security-Policy', "frame-ancestors 'none'")
+ ->assertHeader('X-Frame-Options', 'DENY')
+ ->assertHeader('Referrer-Policy', 'no-referrer')
+ ->assertHeader('Cache-Control', 'no-store, private');
+
+ preg_match('/name="auth_token" value="([^"]+)"/', $consent->getContent(), $authTokenMatch);
+
+ $approval = $this->actingAs($user, 'web')->post('/oauth/authorize', [
+ 'client_id' => $clientId,
+ 'auth_token' => $authTokenMatch[1],
+ ])->assertRedirect();
+
+ parse_str((string) parse_url($approval->headers->get('Location'), PHP_URL_QUERY), $callbackQuery);
+
+ $token = $this->post('/oauth/token', [
+ 'grant_type' => 'authorization_code',
+ 'client_id' => $clientId,
+ 'redirect_uri' => 'http://localhost/callback',
+ 'code_verifier' => $verifier,
+ 'code' => $callbackQuery['code'],
+ ])->assertOk();
+
+ $authorizationHeader = ['Authorization' => 'Bearer '.$token->json('access_token')];
+
+ $this->postJson('/mcp', mcpInitializePayload(), mcpHeaders($authorizationHeader))->assertOk();
+
+ $this->deleteJson('/mcp-oauth/session', [], $authorizationHeader)->assertNoContent();
+
+ $this->app['auth']->forgetGuards();
+ $this->postJson('/mcp', mcpInitializePayload(), mcpHeaders($authorizationHeader))->assertUnauthorized();
+
+ $this->post('/oauth/token', [
+ 'grant_type' => 'refresh_token',
+ 'client_id' => $clientId,
+ 'refresh_token' => $token->json('refresh_token'),
+ ])->assertUnauthorized();
+});
+
+it('rejects an OAuth token without the MCP scope and advertises discovery', function () {
+ $user = User::factory()->create();
+ Passport::actingAs($user, [], 'oauth');
+
+ $this->postJson('/mcp', mcpInitializePayload(), mcpHeaders([
+ 'Authorization' => 'Bearer insufficient-token',
+ ]))->assertUnauthorized()
+ ->assertHeader('WWW-Authenticate');
+});
+
+it('rejects MCP access for blocked authenticated accounts', function () {
+ $user = User::factory()->create(['blocked_at' => now()]);
+ Passport::actingAs($user, ['mcp:use'], 'oauth');
+
+ $this->postJson('/mcp', mcpInitializePayload(), mcpHeaders([
+ 'Authorization' => 'Bearer blocked-user-token',
+ ]))->assertForbidden()
+ ->assertJsonPath('message', 'Your account has been blocked. Please contact support.');
+});
+
+it('bridges normal frontend authentication into a one-time Passport web session', function () {
+ config()->set('app.front_url', 'https://opnform.test');
+ $sessions = app(McpOAuthSessionService::class);
+ $oauthRequest = Request::create(
+ '/oauth/authorize?client_id=7&redirect_uri=https%3A%2F%2Fchatgpt.com%2Fcallback&response_type=code&scope=mcp%3Ause&state=state-1&code_challenge=challenge&code_challenge_method=S256',
+ 'GET'
+ );
+
+ $frontendUrl = $sessions->beginAuthorization($oauthRequest);
+ parse_str((string) parse_url($frontendUrl, PHP_URL_QUERY), $frontendQuery);
+
+ expect($frontendUrl)->toStartWith('https://opnform.test/mcp/authorize?request=')
+ ->and($frontendUrl)->not->toContain('client_id')
+ ->and($frontendQuery['request'])->toHaveLength(64);
+
+ $user = User::factory()->create();
+ $this->actingAs($user, 'api')
+ ->postJson('/mcp-oauth/session', [
+ 'authorization_request_token' => $frontendQuery['request'],
+ ])->assertOk()
+ ->assertJsonPath('authorization_url', fn (string $url) => str_contains($url, 'mcp_login_ticket='));
+
+ $authorizationUrl = $this->actingAs($user, 'api')
+ ->postJson('/mcp-oauth/session', [
+ 'authorization_request_token' => $frontendQuery['request'],
+ ]);
+
+ $authorizationUrl->assertBadRequest();
+});
+
+it('consumes login tickets once and removes them from the authorization URL', function () {
+ $sessions = app(McpOAuthSessionService::class);
+ $user = User::factory()->create();
+ $oauthRequest = Request::create('/oauth/authorize?client_id=7&state=state-1', 'GET');
+ $frontendUrl = $sessions->beginAuthorization($oauthRequest);
+ parse_str((string) parse_url($frontendUrl, PHP_URL_QUERY), $frontendQuery);
+ $authorizationUrl = $sessions->issueLoginTicket($frontendQuery['request'], $user);
+ parse_str((string) parse_url($authorizationUrl, PHP_URL_QUERY), $authorizationQuery);
+
+ $request = Request::create($authorizationUrl, 'GET');
+ $request->setLaravelSession(app('session.store'));
+ $sessions->consumeLoginTicket($authorizationQuery['mcp_login_ticket'], $request);
+
+ expect(auth('web')->id())->toBe($user->id)
+ ->and($sessions->withoutLoginTicket($request))->not->toContain('mcp_login_ticket')
+ ->and($sessions->withoutLoginTicket($request))->toContain('client_id=7')
+ ->and($sessions->withoutLoginTicket($request))->toContain('state=state-1');
+
+ expect(fn () => $sessions->consumeLoginTicket($authorizationQuery['mcp_login_ticket'], $request))
+ ->toThrow(AccessDeniedHttpException::class);
+});
+
+it('does not consume an authorization request while its atomic lock is held', function () {
+ config()->set('app.front_url', 'https://opnform.test');
+ $sessions = app(McpOAuthSessionService::class);
+ $oauthRequest = Request::create(
+ '/oauth/authorize?client_id=7&state=state-1&code_challenge='.str_repeat('a', 64).'&code_challenge_method=S256',
+ 'GET'
+ );
+ $frontendUrl = $sessions->beginAuthorization($oauthRequest);
+ parse_str((string) parse_url($frontendUrl, PHP_URL_QUERY), $frontendQuery);
+
+ $cacheKey = 'mcp:oauth:authorization-request:'.hash('sha256', $frontendQuery['request']);
+ $lock = Cache::lock('mcp:oauth:consume:'.hash('sha256', $cacheKey), 5);
+ expect($lock->get())->toBeTrue();
+
+ try {
+ expect(fn () => $sessions->issueLoginTicket($frontendQuery['request'], User::factory()->create()))
+ ->toThrow(\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class);
+ } finally {
+ $lock->release();
+ }
+
+ expect($sessions->issueLoginTicket($frontendQuery['request'], User::factory()->create()))
+ ->toContain('mcp_login_ticket=');
+});
+
+it('binds each login ticket to the exact OAuth authorization request', function () {
+ $sessions = app(McpOAuthSessionService::class);
+ $user = User::factory()->create();
+ $oauthRequest = Request::create('/oauth/authorize?client_id=7&state=expected', 'GET');
+ $frontendUrl = $sessions->beginAuthorization($oauthRequest);
+ parse_str((string) parse_url($frontendUrl, PHP_URL_QUERY), $frontendQuery);
+ $authorizationUrl = $sessions->issueLoginTicket($frontendQuery['request'], $user);
+ parse_str((string) parse_url($authorizationUrl, PHP_URL_QUERY), $authorizationQuery);
+
+ $swappedRequest = Request::create(
+ '/oauth/authorize?client_id=99&state=attacker&mcp_login_ticket='.$authorizationQuery['mcp_login_ticket'],
+ 'GET'
+ );
+ $swappedRequest->setLaravelSession(app('session.store'));
+
+ expect(fn () => $sessions->consumeLoginTicket(
+ $authorizationQuery['mcp_login_ticket'],
+ $swappedRequest
+ ))->toThrow(AccessDeniedHttpException::class);
+});
diff --git a/api/tests/Feature/Mcp/McpObservabilityTest.php b/api/tests/Feature/Mcp/McpObservabilityTest.php
new file mode 100644
index 000000000..9e5b13747
--- /dev/null
+++ b/api/tests/Feature/Mcp/McpObservabilityTest.php
@@ -0,0 +1,82 @@
+<?php
+
+use App\Service\Telemetry\SendTelemetryJob;
+use App\Service\Telemetry\TelemetryEvent;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Queue;
+
+it('records metadata-only MCP usage without request arguments', function () {
+ Queue::fake();
+ Log::spy();
+
+ $secret = 'never-log-this-secret';
+ $response = $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/call',
+ 'params' => [
+ 'name' => 'missing_tool',
+ 'arguments' => ['draft_token' => $secret],
+ ],
+ ], [
+ 'Accept' => 'application/json, text/event-stream',
+ ]);
+
+ $response->assertOk();
+
+ Queue::assertPushed(SendTelemetryJob::class, function (SendTelemetryJob $job) use ($secret): bool {
+ return $job->eventName === TelemetryEvent::MCP_REQUEST->value()
+ && $job->properties['method'] === 'tools/call'
+ && $job->properties['tool'] === 'missing_tool'
+ && $job->properties['auth_mode'] === 'guest'
+ && $job->properties['outcome'] === 'error'
+ && ! str_contains(json_encode($job->properties), $secret);
+ });
+
+ Log::shouldHaveReceived('info')->once()->withArgs(function (string $message, array $context) use ($secret): bool {
+ return $message === 'MCP request completed'
+ && $context['method'] === 'tools/call'
+ && $context['tool'] === 'missing_tool'
+ && $context['outcome'] === 'error'
+ && ! str_contains(json_encode($context), $secret);
+ });
+});
+
+it('does not fail MCP requests when observability dispatch fails', function () {
+ Log::shouldReceive('info')->once()->andThrow(new RuntimeException('logger unavailable'));
+
+ $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'initialize',
+ 'params' => [
+ 'protocolVersion' => '2025-06-18',
+ 'capabilities' => [],
+ 'clientInfo' => ['name' => 'test', 'version' => '1.0.0'],
+ ],
+ ], [
+ 'Accept' => 'application/json, text/event-stream',
+ ])->assertOk()->assertJsonPath('result.serverInfo.name', 'OpnForm');
+});
+
+it('can disable MCP observability entirely', function () {
+ config()->set('opnform.mcp.observability_enabled', false);
+ Queue::fake();
+ Log::spy();
+
+ $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'initialize',
+ 'params' => [
+ 'protocolVersion' => '2025-06-18',
+ 'capabilities' => [],
+ 'clientInfo' => ['name' => 'test', 'version' => '1.0.0'],
+ ],
+ ], [
+ 'Accept' => 'application/json, text/event-stream',
+ ])->assertOk();
+
+ Queue::assertNothingPushed();
+ Log::shouldNotHaveReceived('info');
+});
diff --git a/api/tests/Feature/Mcp/McpSettingsTest.php b/api/tests/Feature/Mcp/McpSettingsTest.php
new file mode 100644
index 000000000..31768c667
--- /dev/null
+++ b/api/tests/Feature/Mcp/McpSettingsTest.php
@@ -0,0 +1,175 @@
+<?php
+
+use App\Enums\SettingsKey;
+use App\Models\Setting;
+use Laravel\Passport\Passport;
+
+function mcpSettingsPassportKeyPair(): array
+{
+ $key = openssl_pkey_new([
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,
+ ]);
+ openssl_pkey_export($key, $privateKey);
+ $details = openssl_pkey_get_details($key);
+
+ return [$privateKey, $details['key']];
+}
+
+beforeEach(function () {
+ Passport::$keyPath = null;
+ config()->set('app.self_hosted', true);
+ config()->set('app.url', 'https://forms.example.com');
+ config()->set('app.front_url', 'https://forms.example.com');
+ config()->set('opnform.mcp.enabled', false);
+ config()->set('oauth.enabled', true);
+
+ [$privateKey, $publicKey] = mcpSettingsPassportKeyPair();
+ config()->set('passport.private_key', $privateKey);
+ config()->set('passport.public_key', $publicKey);
+
+ $this->user = $this->actingAsUser();
+ $this->workspace = $this->createUserWorkspace($this->user);
+});
+
+it('returns connection details generated for the self-hosted instance', function () {
+ $response = $this->getJson('/settings/mcp');
+
+ $response->assertSuccessful()
+ ->assertJson([
+ 'enabled' => false,
+ 'available' => false,
+ 'configured_value' => null,
+ 'source' => 'environment',
+ 'ready' => true,
+ 'server_url' => 'https://forms.example.com/mcp',
+ 'settings_url' => 'https://forms.example.com/?user-settings=mcp',
+ ]);
+
+ expect($response->json('snippets.cursor'))
+ ->toContain('https://forms.example.com/mcp')
+ ->not->toContain('api.opnform.com');
+ expect($response->json('snippets.claude_code'))->toBe("claude mcp add --transport http opnform 'https://forms.example.com/mcp'");
+ expect($response->json('snippets.chatgpt'))->toContain('Authentication: OAuth');
+ expect($response->json('snippets.codex'))->toBe("codex mcp add opnform --url 'https://forms.example.com/mcp'");
+ expect($response->json('snippets.other'))->toContain('"type": "http"');
+ expect($response->json('snippets.portable'))->toContain('streamable-http');
+ expect($response->json('install_urls.cursor'))->toStartWith('cursor://anysphere.cursor-deeplink/mcp/install');
+
+ parse_str(parse_url($response->json('install_urls.cursor'), PHP_URL_QUERY), $cursorQuery);
+ expect(json_decode(base64_decode($cursorQuery['config'], true), true, flags: JSON_THROW_ON_ERROR))
+ ->toBe(['url' => 'https://forms.example.com/mcp']);
+});
+
+it('stores an enabled override that wins over the environment default', function () {
+ $this->putJson('/settings/mcp', ['enabled' => true])
+ ->assertSuccessful()
+ ->assertJson([
+ 'enabled' => true,
+ 'available' => true,
+ 'configured_value' => true,
+ 'source' => 'settings',
+ ]);
+
+ expect(Setting::get(SettingsKey::MCP_ENABLED))->toBeTrue();
+});
+
+it('stores a disabled override without revoking existing OAuth state', function () {
+ Setting::set(SettingsKey::MCP_ENABLED, true);
+
+ $this->putJson('/settings/mcp', ['enabled' => false])
+ ->assertSuccessful()
+ ->assertJson([
+ 'enabled' => false,
+ 'available' => false,
+ 'configured_value' => false,
+ ]);
+
+ expect(Setting::get(SettingsKey::MCP_ENABLED))->toBeFalse();
+});
+
+it('refuses activation until Passport and public URLs are ready', function () {
+ config()->set('passport.private_key', null);
+ config()->set('passport.public_key', null);
+ Passport::loadKeysFrom(base_path('tests/Fixtures/missing-passport-keys'));
+ config()->set('app.front_url', 'http://forms.example.com');
+
+ $response = $this->putJson('/settings/mcp', ['enabled' => true]);
+
+ $response->assertUnprocessable()
+ ->assertJsonPath('message', 'Complete the MCP OAuth prerequisites before enabling MCP.');
+
+ expect(collect($response->json('blockers'))->pluck('code')->all())
+ ->toContain('passport_keys_missing', 'front_url_invalid');
+ expect(Setting::get(SettingsKey::MCP_ENABLED))->toBeNull();
+});
+
+it('still exposes readiness guidance when the API URL is invalid', function () {
+ config()->set('app.url', 'forms.example.com');
+
+ $this->getJson('/settings/mcp')
+ ->assertSuccessful()
+ ->assertJsonPath('ready', false)
+ ->assertJsonPath('blockers.0.code', 'app_url_invalid');
+});
+
+it('rejects base URLs that would produce ambiguous MCP endpoints', function (string $url) {
+ config()->set('app.url', $url);
+
+ $response = $this->getJson('/settings/mcp')
+ ->assertSuccessful()
+ ->assertJsonPath('ready', false);
+
+ expect(collect($response->json('blockers'))->pluck('code')->all())
+ ->toContain('app_url_invalid');
+})->with([
+ 'credentials' => 'https://user:[email protected]',
+ 'query parameters' => 'https://forms.example.com?tenant=one',
+ 'fragment' => 'https://forms.example.com#settings',
+]);
+
+it('supports self-hosted instances installed below a URL path', function () {
+ config()->set('app.url', 'https://forms.example.com/opnform/');
+ config()->set('app.front_url', 'https://forms.example.com/opnform/');
+
+ $this->getJson('/settings/mcp')
+ ->assertSuccessful()
+ ->assertJson([
+ 'ready' => true,
+ 'server_url' => 'https://forms.example.com/opnform/mcp',
+ 'settings_url' => 'https://forms.example.com/opnform/?user-settings=mcp',
+ ]);
+});
+
+it('allows disabling even when OAuth readiness is broken', function () {
+ Setting::set(SettingsKey::MCP_ENABLED, true);
+ config()->set('passport.private_key', null);
+ config()->set('passport.public_key', null);
+ Passport::loadKeysFrom(base_path('tests/Fixtures/missing-passport-keys'));
+
+ $this->putJson('/settings/mcp', ['enabled' => false])
+ ->assertSuccessful()
+ ->assertJson([
+ 'enabled' => false,
+ 'available' => false,
+ 'ready' => false,
+ ]);
+});
+
+it('requires a workspace admin to read or update instance MCP settings', function (string $method) {
+ $member = $this->createUser();
+ $this->workspace->users()->attach($member, ['role' => 'user']);
+ $this->actingAs($member, 'api');
+
+ $this->json($method, '/settings/mcp', ['enabled' => true])->assertForbidden();
+})->with(['GET', 'PUT']);
+
+it('hides MCP settings from cloud instances', function (string $method) {
+ config()->set('app.self_hosted', false);
+
+ $this->json($method, '/settings/mcp', ['enabled' => true])
+ ->assertNotFound()
+ ->assertJson([
+ 'error' => 'Only available on self-hosted instances.',
+ ]);
+})->with(['GET', 'PUT']);
diff --git a/api/tests/Feature/Mcp/SubmissionToolsTest.php b/api/tests/Feature/Mcp/SubmissionToolsTest.php
new file mode 100644
index 000000000..717226f61
--- /dev/null
+++ b/api/tests/Feature/Mcp/SubmissionToolsTest.php
@@ -0,0 +1,254 @@
+<?php
+
+use App\Jobs\Form\ExportFormSubmissionsJob;
+use App\Mcp\Servers\OpnFormServer;
+use App\Mcp\Tools\ExportSubmissionsTool;
+use App\Mcp\Tools\GetSubmissionExportTool;
+use App\Mcp\Tools\GetSubmissionStatsTool;
+use App\Mcp\Tools\GetSubmissionTool;
+use App\Mcp\Tools\ListSubmissionsTool;
+use App\Models\Forms\FormSubmission;
+use App\Models\User;
+use App\Service\Billing\Feature;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Facades\Queue;
+use Laravel\Passport\Passport;
+
+function submissionFixture(array $completedValues = ['Alice', 'Bob'], ?User $user = null): array
+{
+ $user ??= User::factory()->create();
+ $workspace = createUserWorkspace($user);
+ $form = createForm($user, $workspace, ['enable_partial_submissions' => true]);
+ $fieldId = $form->properties[0]['id'];
+ $submissions = collect($completedValues)->map(fn (string $value) => $form->submissions()->create([
+ 'data' => [$fieldId => $value],
+ 'status' => FormSubmission::STATUS_COMPLETED,
+ 'completion_time' => 30,
+ ]));
+
+ return compact('user', 'workspace', 'form', 'fieldId', 'submissions');
+}
+
+it('advertises OAuth-protected submission tools and no submission mutation tools', function () {
+ $payload = [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/list',
+ 'params' => [],
+ ];
+ $headers = ['Accept' => 'application/json, text/event-stream'];
+
+ $response = $this->postJson('/mcp', $payload, $headers)->assertOk();
+ $tools = collect($response->json('result.tools'))->keyBy('name');
+
+ expect($tools)->toHaveKeys(['list_submissions', 'get_submission_stats', 'export_submissions'])
+ ->and($tools['list_submissions']['securitySchemes'])->toBe([
+ [
+ 'type' => 'oauth2',
+ 'scopes' => ['mcp:use'],
+ ],
+ ]);
+
+ $response->assertDontSee(['update_submission', 'delete_submission', 'create_submission']);
+
+ $user = User::factory()->create();
+ Passport::actingAs($user, ['mcp:use'], 'oauth');
+
+ $response = $this->postJson('/mcp', $payload, array_merge($headers, [
+ 'Authorization' => 'Bearer submission-scope-token',
+ ]))->assertOk()
+ ->assertSee(['list_submissions', 'get_submission_stats', 'export_submissions'])
+ ->assertDontSee(['update_submission', 'delete_submission', 'create_submission']);
+
+ $tools = collect($response->json('result.tools'))->keyBy('name');
+
+ expect($tools['list_submissions']['annotations']['readOnlyHint'])->toBeTrue()
+ ->and($tools['export_submissions']['annotations']['readOnlyHint'] ?? false)->toBeFalse();
+});
+
+it('searches response values and filters submission status without leaking other forms', function () {
+ $fixture = submissionFixture(['Alice Example', 'Bob Example']);
+ $partial = $fixture['form']->submissions()->create([
+ 'data' => [$fixture['fieldId'] => 'Alice Partial'],
+ 'status' => FormSubmission::STATUS_PARTIAL,
+ ]);
+ $other = submissionFixture(['Alice Secret']);
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ListSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'search' => 'Alice',
+ 'status' => 'completed',
+ ])->assertOk()
+ ->assertSee('Alice Example')
+ ->assertDontSee(['Bob Example', 'Alice Partial', 'Alice Secret']);
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ListSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'status' => 'partial',
+ ])->assertOk()->assertSee((string) $partial->id)->assertSee('Alice Partial');
+
+ expect($other['form']->id)->not->toBe($fixture['form']->id);
+});
+
+it('lets readonly workspace members read submissions and rejects cross-form IDs', function () {
+ $fixture = submissionFixture();
+ $readonly = User::factory()->create();
+ $fixture['workspace']->users()->attach($readonly, ['role' => User::ROLE_READONLY]);
+ $submission = $fixture['submissions']->first();
+
+ OpnFormServer::actingAs($readonly, 'oauth')->tool(GetSubmissionTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'submission_id' => $submission->id,
+ ])->assertOk()->assertSee('Alice');
+
+ $other = submissionFixture(['Outside']);
+ OpnFormServer::actingAs($readonly, 'oauth')->tool(GetSubmissionTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'submission_id' => $other['submissions']->first()->id,
+ ])->assertHasErrors(['not found or not accessible']);
+});
+
+it('returns bounded existing form analytics with filtered field summaries', function () {
+ $fixture = submissionFixture(['Alice', 'Bob'], $this->createProUser());
+ $fixture['form']->submissions()->create([
+ 'data' => [$fixture['fieldId'] => 'In progress'],
+ 'status' => FormSubmission::STATUS_PARTIAL,
+ 'completion_time' => 10,
+ ]);
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionStatsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'status' => 'completed',
+ ])->assertOk()
+ ->assertSee(['completed_submissions', 'partial_submissions', 'field_summary', 'processed_submissions'])
+ ->assertSee('Alice')
+ ->assertDontSee('In progress');
+});
+
+it('preserves the form summary plan entitlement', function () {
+ $fixture = submissionFixture();
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionStatsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertHasErrors(['Pro plan is required']);
+});
+
+it('requires both analytics and summary feature entitlements', function (string $grantedFeature) {
+ $fixture = submissionFixture();
+ $fixture['workspace']->update([
+ 'plan_overrides' => ['features' => [$grantedFeature]],
+ ]);
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionStatsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertHasErrors(['Pro plan is required']);
+})->with([
+ 'summary only' => Feature::FORM_SUMMARY,
+ 'analytics only' => Feature::FORM_ANALYTICS,
+]);
+
+it('accepts open-ended submission date filters', function () {
+ $dateFrom = now()->subDay()->toDateString();
+ $fixture = submissionFixture(['Alice'], $this->createProUser());
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ListSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'date_from' => $dateFrom,
+ ])->assertOk()->assertSee('Alice');
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionStatsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'date_from' => $dateFrom,
+ ])->assertOk()->assertSee('field_summary');
+});
+
+it('rate limits repeated submission statistics requests', function () {
+ config()->set('opnform.form_summary_rate_limit_per_minute', 1);
+ $fixture = submissionFixture(['Alice'], $this->createProUser());
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionStatsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertOk();
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionStatsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertHasErrors(['Too many submission statistics requests']);
+});
+
+it('shares the form summary rate limit between MCP and REST', function () {
+ config()->set('opnform.form_summary_rate_limit_per_minute', 1);
+ $fixture = submissionFixture(['Alice'], $this->createProUser());
+
+ $this->actingAsUser($fixture['user']);
+ $this->getJson(route('open.workspaces.form.summary', [$fixture['workspace'], $fixture['form']]))
+ ->assertOk()
+ ->assertHeader('X-RateLimit-Remaining', '0');
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionStatsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertHasErrors(['Too many submission statistics requests']);
+});
+
+it('queues private CSV exports and scopes status polling to the requesting account', function () {
+ Queue::fake();
+ $fixture = submissionFixture();
+ $selectedId = $fixture['submissions']->first()->id;
+
+ $response = OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ExportSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'submission_ids' => [$selectedId],
+ ]);
+ $response->assertOk()->assertSee(['job_id', 'queued', 'get_submission_export']);
+
+ Queue::assertPushed(ExportFormSubmissionsJob::class, fn (ExportFormSubmissionsJob $job) => $job->userId === $fixture['user']->id
+ && $job->form->is($fixture['form'])
+ && $job->submissionIds === [$selectedId]);
+
+ $jobId = Queue::pushed(ExportFormSubmissionsJob::class)->first()->jobId;
+ $job = Cache::get('form_export_job:'.$jobId);
+ expect($job['status'])->toBe('queued');
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(GetSubmissionExportTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'job_id' => $jobId,
+ ])->assertOk()->assertSee(['queued', 'progress']);
+
+ $otherMember = User::factory()->create();
+ $fixture['workspace']->users()->attach($otherMember, ['role' => User::ROLE_USER]);
+ OpnFormServer::actingAs($otherMember, 'oauth')->tool(GetSubmissionExportTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'job_id' => $jobId,
+ ])->assertHasErrors(['not accessible']);
+});
+
+it('rejects exports containing submission IDs from another form', function () {
+ Queue::fake();
+ $fixture = submissionFixture();
+ $other = submissionFixture(['Secret']);
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ExportSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ 'submission_ids' => [$other['submissions']->first()->id],
+ ])->assertHasErrors(['not found in this form']);
+
+ Queue::assertNotPushed(ExportFormSubmissionsJob::class);
+});
+
+it('rate limits repeated heavy export requests without affecting submission reads', function () {
+ Queue::fake();
+ config()->set('opnform.mcp.rate_limit.submission_exports_per_minute', 1);
+ config()->set('opnform.mcp.rate_limit.submission_exports_per_hour', 10);
+ $fixture = submissionFixture();
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ExportSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertOk();
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ExportSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertHasErrors(['Too many submission exports']);
+
+ OpnFormServer::actingAs($fixture['user'], 'oauth')->tool(ListSubmissionsTool::class, [
+ 'form_id' => $fixture['form']->id,
+ ])->assertOk()->assertSee('Alice');
+});
diff --git a/api/tests/Unit/Models/SettingTest.php b/api/tests/Unit/Models/SettingTest.php
index 9ae8b1917..66f9395a2 100644
--- a/api/tests/Unit/Models/SettingTest.php
+++ b/api/tests/Unit/Models/SettingTest.php
@@ -12,6 +12,7 @@ describe('Setting', function () {
Setting::whereIn('key', [
SettingsKey::INSTANCE_ID->value,
SettingsKey::INSTANCE_CREATED_AT->value,
+ SettingsKey::MCP_ENABLED->value,
])->delete();
});
@@ -67,4 +68,14 @@ describe('Setting', function () {
expect(Setting::get(SettingsKey::INSTANCE_ID))->toBe(123);
});
});
+
+ it('stores boolean feature overrides without losing false values', function () {
+ Setting::set(SettingsKey::MCP_ENABLED, false);
+
+ expect(Setting::get(SettingsKey::MCP_ENABLED))->toBeFalse();
+
+ Setting::set(SettingsKey::MCP_ENABLED, true);
+
+ expect(Setting::get(SettingsKey::MCP_ENABLED))->toBeTrue();
+ });
});
diff --git a/api/tests/Unit/Rules/PaymentPropertyValidatorTest.php b/api/tests/Unit/Rules/PaymentPropertyValidatorTest.php
index c4d29c52e..ba4248dfd 100644
--- a/api/tests/Unit/Rules/PaymentPropertyValidatorTest.php
+++ b/api/tests/Unit/Rules/PaymentPropertyValidatorTest.php
@@ -128,3 +128,19 @@ describe('non-payment blocks', function () {
expect($errors)->toBeEmpty();
});
});
+
+describe('guest validation', function () {
+ it('defers provider lookup when no workspace security boundary exists', function () {
+ $validator = new PaymentPropertyValidator();
+ $property = [
+ 'type' => 'payment',
+ 'amount' => 10,
+ 'currency' => 'USD',
+ 'stripe_account_id' => 999999,
+ ];
+
+ $errors = $validator->validate($property, 0, ['properties' => [$property]]);
+
+ expect($errors)->toBeEmpty();
+ });
+});
diff --git a/api/tests/Unit/Rules/PublicMediaUrlRuleTest.php b/api/tests/Unit/Rules/PublicMediaUrlRuleTest.php
new file mode 100644
index 000000000..150dfab6a
--- /dev/null
+++ b/api/tests/Unit/Rules/PublicMediaUrlRuleTest.php
@@ -0,0 +1,34 @@
+<?php
+
+use App\Rules\PublicMediaUrlRule;
+use Illuminate\Support\Facades\Validator;
+
+it('accepts durable public HTTPS media URLs', function () {
+ $validator = Validator::make([
+ 'media_url' => 'https://cdn.example.com/forms/header.png',
+ ], [
+ 'media_url' => [new PublicMediaUrlRule()],
+ ]);
+
+ expect($validator->passes())->toBeTrue();
+});
+
+it('rejects unsafe or temporary media URLs', function (string $url, string $message) {
+ $validator = Validator::make([
+ 'media_url' => $url,
+ ], [
+ 'media_url' => [new PublicMediaUrlRule()],
+ ]);
+
+ expect($validator->fails())->toBeTrue()
+ ->and($validator->errors()->first('media_url'))->toContain($message);
+})->with([
+ 'plain HTTP' => ['http://cdn.example.com/header.png', 'HTTPS'],
+ 'embedded credentials' => ['https://[email protected]/header.png', 'embedded credentials'],
+ 'localhost' => ['https://localhost/header.png', 'public host'],
+ 'private IPv4' => ['https://192.168.1.12/header.png', 'public host'],
+ 'loopback IPv6' => ['https://[::1]/header.png', 'public host'],
+ 'private hostname' => ['https://assets.internal/header.png', 'public host'],
+ 'temporary tunnel' => ['https://draft.trycloudflare.com/header.png', 'temporary tunnel'],
+ 'expiring signature' => ['https://cdn.example.com/header.png?expires=123&signature=secret', 'expiring or signed'],
+]);
diff --git a/api/tests/Unit/Service/Forms/FormCleanerDataTest.php b/api/tests/Unit/Service/Forms/FormCleanerDataTest.php
new file mode 100644
index 000000000..777707ab7
--- /dev/null
+++ b/api/tests/Unit/Service/Forms/FormCleanerDataTest.php
@@ -0,0 +1,48 @@
+<?php
+
+use App\Models\Forms\Form;
+use App\Service\Forms\FormCleaner;
+
+uses(Tests\TestCase::class);
+
+it('sanitizes raw MCP form data with the same common cleaner', function () {
+ $cleaned = app(FormCleaner::class)->processData([
+ 'title' => 'MCP draft',
+ 'properties' => [
+ [
+ 'id' => 'intro',
+ 'name' => 'Introduction',
+ 'type' => 'nf-text',
+ 'content' => '<script>alert(1)</script><p>Safe introduction</p>',
+ ],
+ [
+ 'id' => 'custom-code',
+ 'name' => 'Custom code',
+ 'type' => 'nf-code',
+ 'content' => '<script>window.example = true</script>',
+ ],
+ ],
+ ])->getData();
+
+ expect($cleaned['properties'])->toHaveCount(1)
+ ->and($cleaned['properties'][0]['content'])->not->toContain('<script>')
+ ->and($cleaned['properties'][0]['content'])->toContain('Safe introduction');
+});
+
+it('keeps custom code when the target form has a custom domain', function () {
+ $form = new Form(['custom_domain' => 'forms.example.test']);
+
+ $cleaned = app(FormCleaner::class)->processData([
+ 'properties' => [
+ [
+ 'id' => 'custom-code',
+ 'name' => 'Custom code',
+ 'type' => 'nf-code',
+ 'content' => '<script>window.example = true</script>',
+ ],
+ ],
+ ], $form)->getData();
+
+ expect($cleaned['properties'])->toHaveCount(1)
+ ->and($cleaned['properties'][0]['type'])->toBe('nf-code');
+});
diff --git a/api/tests/Unit/Service/Forms/FormDataNormalizerTest.php b/api/tests/Unit/Service/Forms/FormDataNormalizerTest.php
new file mode 100644
index 000000000..b0d050925
--- /dev/null
+++ b/api/tests/Unit/Service/Forms/FormDataNormalizerTest.php
@@ -0,0 +1,29 @@
+<?php
+
+use App\Service\Forms\FormDataNormalizer;
+
+uses(Tests\TestCase::class);
+
+it('uses one normalization path for form titles, properties, and select options', function () {
+ $normalized = app(FormDataNormalizer::class)->normalize([
+ 'title' => ' My form ',
+ 'properties' => [
+ [
+ 'name' => ' <strong>Choice</strong> ',
+ 'type' => 'select',
+ 'help' => '<script>alert(1)</script><p>Pick one</p>',
+ 'select' => [
+ 'options' => [
+ ['name' => 'First'],
+ ],
+ ],
+ ],
+ ],
+ ], backfillPropertyIds: true);
+
+ expect($normalized['title'])->toBe('My form')
+ ->and($normalized['properties'][0]['name'])->toBe('Choice')
+ ->and($normalized['properties'][0]['help'])->not->toContain('<script>')
+ ->and($normalized['properties'][0]['select']['options'][0]['id'])->toBe('First')
+ ->and($normalized['properties'][0]['id'])->toBeString()->not->toBeEmpty();
+});
diff --git a/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php b/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php
index 42d351045..004a30e76 100644
--- a/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php
+++ b/api/tests/Unit/Service/Telemetry/TelemetryEventTest.php
@@ -4,7 +4,7 @@ use App\Service\Telemetry\TelemetryEvent;
describe('TelemetryEvent', function () {
it('has all required event cases', function () {
- expect(TelemetryEvent::cases())->toHaveCount(8);
+ expect(TelemetryEvent::cases())->toHaveCount(9);
});
it('has INSTANCE_CREATED case with correct value', function () {
@@ -39,6 +39,10 @@ describe('TelemetryEvent', function () {
expect(TelemetryEvent::SSO_CREATED->value)->toBe('sso.created');
});
+ it('has MCP_REQUEST case with correct value', function () {
+ expect(TelemetryEvent::MCP_REQUEST->value)->toBe('mcp.request');
+ });
+
it('value method returns the enum value', function () {
expect(TelemetryEvent::INSTANCE_CREATED->value())->toBe('instance.created');
expect(TelemetryEvent::USER_CREATED->value())->toBe('user.created');
diff --git a/api/vapor.yml b/api/vapor.yml
index 09d5a4527..f8a81a28d 100644
--- a/api/vapor.yml
+++ b/api/vapor.yml
@@ -24,6 +24,7 @@ environments:
- "php artisan optimize"
- "php artisan disposable:update"
deploy:
+ - "php artisan mcp:check-oauth-keys --environment-only"
- "php artisan migrate --force"
firewall:
rate-limit: 1000
@@ -41,6 +42,7 @@ environments:
- "php artisan optimize"
- "php artisan disposable:update"
deploy:
+ - "php artisan mcp:check-oauth-keys --environment-only"
- "php artisan migrate --force"
firewall:
rate-limit: 1000
diff --git a/client/api/index.js b/client/api/index.js
index c5902a15d..c44fe42b6 100644
--- a/client/api/index.js
+++ b/client/api/index.js
@@ -10,4 +10,5 @@ export { tokensApi } from './tokens'
export { adminApi } from './admin'
export { uploadsApi } from './uploads'
export { contentApi } from './content'
-export { licenseApi } from './license'
\ No newline at end of file
+export { licenseApi } from './license'
+export { mcpApi } from './mcp'
diff --git a/client/api/mcp.js b/client/api/mcp.js
new file mode 100644
index 000000000..b80c48bb1
--- /dev/null
+++ b/client/api/mcp.js
@@ -0,0 +1,8 @@
+import { apiService } from './base'
+
+const BASE_PATH = '/settings/mcp'
+
+export const mcpApi = {
+ status: () => apiService.get(BASE_PATH),
+ update: (enabled) => apiService.put(BASE_PATH, { enabled }),
+}
diff --git a/client/components/open/forms/BlockRenderer.vue b/client/components/open/forms/BlockRenderer.vue
index f6010f12c..6269d7f35 100644
--- a/client/components/open/forms/BlockRenderer.vue
+++ b/client/components/open/forms/BlockRenderer.vue
@@ -36,8 +36,15 @@
:id="block.id"
:key="'code-' + block.id"
class="nf-code w-full px-2 my-1.5"
- v-html="block.content"
- />
+ >
+ <div
+ v-if="disableCustomCodeExecution"
+ class="rounded-lg border border-dashed bg-neutral-50 p-4 text-sm text-neutral-500"
+ >
+ Custom code is preserved but does not execute in an agent draft preview.
+ </div>
+ <div v-else v-html="block.content" />
+ </div>
<div
v-else-if="block.type === 'nf-divider'"
:id="block.id"
@@ -143,6 +150,7 @@ const dataForm = computed(() => props.formManager?.form || {})
const darkMode = computed(() => props.formManager?.darkMode?.value || false)
const strategy = computed(() => props.formManager?.strategy?.value || {})
const isAdminPreview = computed(() => strategy.value?.admin?.showAdminControls || false)
+const disableCustomCodeExecution = inject('disableCustomCodeExecution', false)
// Debounce form data changes to avoid excessive re-renders when user types
const formDataForMentions = computed(() => dataForm.value?.data?.() || {})
diff --git a/client/components/open/forms/FormProgressbar.vue b/client/components/open/forms/FormProgressbar.vue
index 23ef2d69c..a45b7c6b4 100644
--- a/client/components/open/forms/FormProgressbar.vue
+++ b/client/components/open/forms/FormProgressbar.vue
@@ -35,25 +35,29 @@ const isSubmitted = computed(() => props.formManager?.state?.isSubmitted ?? fals
// Wrapper classes - different positioning for iframe vs standalone
const wrapperClasses = computed(() => {
- return isIframe.value
- ? 'mb-4 p-2'
+ if (isIframe && isFocusedMode.value) {
+ return 'shrink-0'
+ }
+
+ return isIframe
+ ? 'mb-4 p-2'
: 'fixed top-0 left-0 right-0 z-50'
})
// Bar container classes - border/rounded for iframe, height varies by mode
const barContainerClasses = computed(() => {
- const heightClass = isIframe.value
+ const heightClass = isIframe
? (isFocusedMode.value ? 'h-1' : 'h-1')
: (isFocusedMode.value ? 'h-1' : 'h-[0.2rem]')
- const borderClass = isIframe.value ? 'border rounded-full' : ''
+ const borderClass = isIframe && !isFocusedMode.value ? 'border rounded-full' : ''
return [heightClass, borderClass].filter(Boolean).join(' ')
})
// Bar fill classes - rounded for iframe
const barFillClasses = computed(() => {
- return isIframe.value ? 'rounded-r-full' : ''
+ return isIframe && !isFocusedMode.value ? 'rounded-r-full' : ''
})
const formProgress = computed(() => {
@@ -86,4 +90,4 @@ const formProgress = computed(() => {
return Math.round(progress)
}
})
-</script>
\ No newline at end of file
+</script>
diff --git a/client/components/open/forms/components/FormEditor.vue b/client/components/open/forms/components/FormEditor.vue
index 694761ce4..798928095 100644
--- a/client/components/open/forms/components/FormEditor.vue
+++ b/client/components/open/forms/components/FormEditor.vue
@@ -160,6 +160,11 @@ const props = defineProps({
required: false,
type: Boolean,
default: false,
+ },
+ saveHandler: {
+ required: false,
+ type: Function,
+ default: null,
}
})
@@ -363,6 +368,11 @@ const proceedWithSave = () => {
form.value.properties = validatePropertiesLogic(form.value.properties)
}
+ if (props.saveHandler) {
+ props.saveHandler(form.value.data())
+ return
+ }
+
if (props.isGuest) {
saveFormGuest()
} else if (props.isEdit) {
diff --git a/client/components/pages/OpenFormFooter.vue b/client/components/pages/OpenFormFooter.vue
index 8927aef86..07af6c037 100644
--- a/client/components/pages/OpenFormFooter.vue
+++ b/client/components/pages/OpenFormFooter.vue
@@ -320,6 +320,7 @@ const linkGroups = computed(() => [
{
title: "Developers",
links: [
+ { label: "MCP for AI agents", to: { name: "mcp" } },
{ label: "Open-source", href: opnformConfig.links.github_url },
{ label: "Self-hosting", href: opnformConfig.links.self_hosting },
{ label: "Documentation", href: opnformConfig.links.tech_docs },
diff --git a/client/components/users/settings/Mcp.vue b/client/components/users/settings/Mcp.vue
new file mode 100644
index 000000000..d2768807a
--- /dev/null
+++ b/client/components/users/settings/Mcp.vue
@@ -0,0 +1,377 @@
+<template>
+ <div class="space-y-6">
+ <div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
+ <div>
+ <div class="flex items-center gap-2">
+ <div class="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-600">
+ <Icon name="i-heroicons-cpu-chip" class="h-5 w-5" />
+ </div>
+ <div>
+ <h3 class="text-lg font-semibold text-neutral-900">
+ MCP & AI agents
+ </h3>
+ <p class="text-sm text-neutral-500">
+ Connect AI assistants directly to this OpnForm instance.
+ </p>
+ </div>
+ </div>
+ </div>
+
+ <UButton
+ to="https://docs.opnform.com/integrations/mcp"
+ target="_blank"
+ label="Setup guide"
+ icon="i-heroicons-arrow-up-right"
+ variant="outline"
+ color="neutral"
+ />
+ </div>
+
+ <div v-if="isLoading" class="space-y-3">
+ <USkeleton class="h-28 w-full" />
+ <USkeleton class="h-40 w-full" />
+ </div>
+
+ <section
+ v-else-if="loadError"
+ class="rounded-xl border border-red-200 bg-red-50 p-5"
+ data-testid="mcp-load-error"
+ >
+ <div class="flex items-start gap-3">
+ <Icon name="i-heroicons-exclamation-circle" class="mt-0.5 h-5 w-5 shrink-0 text-red-600" />
+ <div>
+ <h4 class="font-semibold text-red-900">MCP settings could not be loaded</h4>
+ <p class="mt-1 text-sm text-red-800">Check the API connection and try again.</p>
+ <UButton class="mt-3" label="Retry" color="error" variant="soft" @click="loadSettings" />
+ </div>
+ </div>
+ </section>
+
+ <template v-else-if="settings">
+ <section class="overflow-hidden rounded-xl border border-neutral-200 bg-white">
+ <div class="flex flex-col gap-5 p-5 sm:flex-row sm:items-start sm:justify-between">
+ <div class="flex min-w-0 items-start gap-3">
+ <div
+ class="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-full"
+ :class="statusIconClasses"
+ >
+ <Icon :name="statusIcon" class="h-5 w-5" />
+ </div>
+ <div>
+ <div class="flex flex-wrap items-center gap-2">
+ <p class="font-semibold text-neutral-900">
+ {{ statusTitle }}
+ </p>
+ <UBadge :color="statusBadgeColor" variant="subtle">
+ {{ statusBadgeLabel }}
+ </UBadge>
+ </div>
+ <p class="mt-1 max-w-xl text-sm leading-6 text-neutral-600">
+ {{ statusDescription }}
+ </p>
+ </div>
+ </div>
+
+ <div class="flex shrink-0 items-center gap-3 rounded-lg border border-neutral-200 bg-neutral-50 px-3 py-2">
+ <span class="text-sm font-medium text-neutral-700">Enable MCP</span>
+ <USwitch
+ :model-value="settings.enabled"
+ :disabled="isSaving || (!settings.ready && !settings.enabled)"
+ aria-label="Enable MCP"
+ data-testid="mcp-enabled-switch"
+ @update:model-value="updateEnabled"
+ />
+ </div>
+ </div>
+
+ </section>
+
+ <section
+ v-if="!settings.ready"
+ class="rounded-xl border border-red-200 bg-red-50 p-5"
+ data-testid="mcp-readiness-blockers"
+ >
+ <div class="flex items-start gap-3">
+ <Icon name="i-heroicons-exclamation-triangle" class="mt-0.5 h-5 w-5 shrink-0 text-red-600" />
+ <div>
+ <h4 class="font-semibold text-red-900">
+ Complete the server setup first
+ </h4>
+ <p class="mt-1 text-sm leading-6 text-red-800">
+ MCP cannot be enabled until OAuth is ready on this instance.
+ </p>
+ <ul class="mt-3 space-y-2 text-sm text-red-800">
+ <li v-for="blocker in settings.blockers" :key="blocker.code" class="flex gap-2">
+ <span aria-hidden="true">•</span>
+ <span>{{ blocker.message }}</span>
+ </li>
+ </ul>
+ </div>
+ </div>
+ </section>
+
+ <section
+ v-if="isMcpAvailable"
+ class="space-y-4 rounded-xl border border-neutral-200 bg-white p-5"
+ data-testid="mcp-connection-settings"
+ >
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
+ <div>
+ <p class="text-xs font-semibold uppercase tracking-wider text-blue-600">
+ Connection endpoint
+ </p>
+ <h4 class="mt-1 font-semibold text-neutral-900">
+ Connect your AI assistant
+ </h4>
+ <p class="mt-1 text-sm leading-6 text-neutral-600">
+ Use the server URL directly in ChatGPT, or copy the configuration for your agent client.
+ </p>
+ </div>
+ <UButton
+ label="Copy settings link"
+ icon="i-heroicons-link"
+ variant="soft"
+ color="neutral"
+ @click="copyValue(sharedSettingsUrl, 'Settings link copied')"
+ />
+ </div>
+
+ <div>
+ <p class="mb-2 text-sm font-medium text-neutral-700">MCP server URL</p>
+ <CopyContent :content="settings.server_url" label="Copy URL" />
+ </div>
+
+ </section>
+
+ <section v-if="isMcpAvailable" data-testid="mcp-snippet-settings">
+ <McpCodeSnippet
+ :content="activeSnippet.content"
+ :label="activeSnippet.label"
+ @copy="copyValue(activeSnippet.content, `${activeSnippet.label} configuration copied`)"
+ >
+ <template #selector>
+ <div class="flex min-w-0 items-center gap-1 overflow-x-auto" role="group" aria-label="MCP client configuration">
+ <button
+ v-for="snippet in snippetOptions"
+ :key="snippet.key"
+ type="button"
+ :aria-pressed="activeSnippetKey === snippet.key"
+ :data-testid="`mcp-snippet-${snippet.key}`"
+ class="inline-flex shrink-0 items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors"
+ :class="activeSnippetKey === snippet.key
+ ? 'bg-white text-neutral-950 shadow-sm'
+ : 'text-neutral-400 hover:bg-white/10 hover:text-white'"
+ @click="selectSnippet(snippet.key)"
+ >
+ <Icon :name="snippet.icon" class="h-3.5 w-3.5" />
+ {{ snippet.label }}
+ </button>
+ </div>
+ </template>
+ <template #instructions>
+ <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <p class="text-sm leading-6 text-neutral-300">
+ {{ activeSnippet.description }}
+ </p>
+ <UButton
+ v-if="activeSnippet.installUrl"
+ :label="activeSnippet.installLabel"
+ :to="activeSnippet.installUrl"
+ icon="i-heroicons-arrow-top-right-on-square"
+ color="neutral"
+ variant="solid"
+ class="shrink-0"
+ />
+ </div>
+ </template>
+ </McpCodeSnippet>
+
+ <details class="mt-3 overflow-hidden rounded-xl border border-neutral-200 bg-white" data-testid="mcp-portable-config">
+ <summary class="cursor-pointer px-4 py-3 text-sm font-medium text-neutral-700">
+ Portable Agent Plugin configuration
+ </summary>
+ <div class="border-t border-neutral-200 bg-neutral-950">
+ <div class="flex justify-end border-b border-white/10 p-2">
+ <UButton
+ label="Copy"
+ icon="i-heroicons-clipboard-document"
+ color="neutral"
+ variant="solid"
+ size="xs"
+ @click.prevent="copyValue(settings.snippets.portable, 'Agent Plugin configuration copied')"
+ />
+ </div>
+ <pre class="max-h-72 overflow-auto p-4 text-xs leading-6 text-blue-100"><code>{{ settings.snippets.portable }}</code></pre>
+ </div>
+ </details>
+ </section>
+ </template>
+ </div>
+</template>
+
+<script setup>
+import { mcpApi } from '~/api'
+import CopyContent from '~/components/open/forms/components/CopyContent.vue'
+import McpCodeSnippet from '~/components/users/settings/mcp/McpCodeSnippet.vue'
+
+const alert = useAlert()
+const { copy } = useClipboard()
+const route = useRoute()
+const router = useRouter()
+const settings = ref(null)
+const isLoading = ref(true)
+const isSaving = ref(false)
+const loadError = ref(false)
+
+const snippetOptions = [
+ {
+ key: 'cursor',
+ label: 'Cursor',
+ icon: 'i-heroicons-cursor-arrow-rays',
+ description: 'Install OpnForm directly in Cursor, or copy the JSON configuration below.',
+ installLabel: 'Install in Cursor',
+ },
+ {
+ key: 'claude_code',
+ label: 'Claude Code',
+ icon: 'i-heroicons-chat-bubble-left-right',
+ description: 'Run this command, then use /mcp in Claude Code to authenticate with OpnForm.',
+ },
+ {
+ key: 'chatgpt',
+ label: 'ChatGPT',
+ icon: 'i-heroicons-sparkles',
+ description: 'On a plan that supports custom MCP apps, create an app in ChatGPT developer mode with this server URL and OAuth.',
+ },
+ {
+ key: 'codex',
+ label: 'Codex',
+ icon: 'i-heroicons-command-line',
+ description: 'Add this MCP server to Codex. OAuth starts when you use an account-scoped tool.',
+ },
+ {
+ key: 'other',
+ label: 'Other',
+ icon: 'i-heroicons-ellipsis-horizontal',
+ description: 'Use this streamable HTTP configuration in another OAuth-capable MCP client.',
+ },
+]
+
+const activeSnippetKey = ref(resolveSnippetKey(route.query.agent))
+
+const activeSnippet = computed(() => {
+ const option = snippetOptions.find(snippet => snippet.key === activeSnippetKey.value) || snippetOptions[0]
+
+ return {
+ ...option,
+ content: settings.value?.snippets?.[option.key] || '',
+ installUrl: settings.value?.install_urls?.[option.key] || null,
+ }
+})
+
+const sharedSettingsUrl = computed(() => {
+ if (!settings.value?.settings_url) return ''
+
+ const url = new URL(settings.value.settings_url)
+ url.searchParams.set('agent', activeSnippetKey.value)
+
+ return url.toString()
+})
+
+const isMcpAvailable = computed(() => settings.value?.available === true)
+
+const statusTitle = computed(() => {
+ if (!settings.value?.ready) return 'Server setup required'
+ return isMcpAvailable.value ? 'MCP is available' : 'Ready to connect'
+})
+
+const statusDescription = computed(() => {
+ if (!settings.value?.ready) return 'Resolve the prerequisites below before exposing the MCP endpoint.'
+ if (isMcpAvailable.value) return 'Connected AI assistants can create and manage forms and read submissions using your OpnForm account.'
+ return 'OAuth is ready. Enable MCP when you want this instance to accept agent connections.'
+})
+
+const statusIcon = computed(() => {
+ if (!settings.value?.ready) return 'i-heroicons-exclamation-triangle'
+ return settings.value?.enabled ? 'i-heroicons-check' : 'i-heroicons-pause'
+})
+
+const statusIconClasses = computed(() => {
+ if (!settings.value?.ready) return 'bg-red-100 text-red-600'
+ return settings.value?.enabled ? 'bg-emerald-100 text-emerald-600' : 'bg-neutral-100 text-neutral-500'
+})
+
+const statusBadgeLabel = computed(() => {
+ if (!settings.value?.ready && settings.value?.enabled) return 'Unavailable'
+ return settings.value?.enabled ? 'Enabled' : 'Disabled'
+})
+
+const statusBadgeColor = computed(() => {
+ if (!settings.value?.ready && settings.value?.enabled) return 'error'
+ return settings.value?.enabled ? 'success' : 'neutral'
+})
+
+function resolveSnippetKey(value) {
+ return snippetOptions.some(snippet => snippet.key === value) ? value : 'codex'
+}
+
+function selectSnippet(key) {
+ activeSnippetKey.value = resolveSnippetKey(key)
+ router.replace({
+ query: {
+ ...route.query,
+ agent: activeSnippetKey.value,
+ },
+ }).catch(() => {})
+}
+
+function loadSettings() {
+ isLoading.value = true
+ loadError.value = false
+ mcpApi.status()
+ .then((response) => {
+ settings.value = response
+ })
+ .catch((error) => {
+ loadError.value = true
+ alert.error(error?.data?.message || 'Failed to load MCP settings.')
+ })
+ .finally(() => {
+ isLoading.value = false
+ })
+}
+
+function updateEnabled(enabled) {
+ isSaving.value = true
+ mcpApi.update(enabled)
+ .then((response) => {
+ settings.value = response
+ alert.success(enabled ? 'MCP enabled for this instance.' : 'MCP disabled for this instance.')
+ })
+ .catch((error) => {
+ if (error?.data?.blockers) {
+ settings.value = {
+ ...settings.value,
+ ready: false,
+ available: false,
+ blockers: error.data.blockers,
+ }
+ }
+ alert.error(error?.data?.message || 'Failed to update MCP settings.')
+ })
+ .finally(() => {
+ isSaving.value = false
+ })
+}
+
+function copyValue(value, message) {
+ copy(value)
+ alert.success(message)
+}
+
+onMounted(loadSettings)
+
+watch(() => route.query.agent, (agent) => {
+ activeSnippetKey.value = resolveSnippetKey(agent)
+})
+</script>
diff --git a/client/components/users/settings/Modal.vue b/client/components/users/settings/Modal.vue
index af2b24e19..29f76eaf1 100644
--- a/client/components/users/settings/Modal.vue
+++ b/client/components/users/settings/Modal.vue
@@ -48,6 +48,15 @@
<LazyUsersSettingsLicense />
</SettingsModalPage>
+ <SettingsModalPage
+ v-if="canManageInstanceSettings"
+ id="mcp"
+ label="MCP & AI agents"
+ icon="i-heroicons-cpu-chip"
+ >
+ <LazyUsersSettingsMcp />
+ </SettingsModalPage>
+
<SettingsModalPage
v-if="!isSelfHosted && user && (user.has_customer_id || user.active_license)"
id="billing"
@@ -73,10 +82,11 @@ const props = defineProps({
}
})
-const { current: workspace } = useCurrentWorkspace()
+const { current: workspace, workspaces } = useCurrentWorkspace()
const { data: user } = useAuth().user()
const isSelfHosted = computed(() => useFeatureFlag('self_hosted'))
-const canManageLicense = computed(() => isSelfHosted.value && !!workspace.value?.is_admin)
+const canManageInstanceSettings = computed(() => isSelfHosted.value && !!workspaces.value?.some(candidate => candidate.is_admin))
+const canManageLicense = canManageInstanceSettings
// Modal state is now derived from the presence of an active tab
const isOpen = computed({
diff --git a/client/components/users/settings/mcp/McpCodeSnippet.vue b/client/components/users/settings/mcp/McpCodeSnippet.vue
new file mode 100644
index 000000000..78ee9774b
--- /dev/null
+++ b/client/components/users/settings/mcp/McpCodeSnippet.vue
@@ -0,0 +1,39 @@
+<template>
+ <div class="overflow-hidden rounded-xl border border-neutral-200 bg-neutral-950 text-white">
+ <div class="flex items-center justify-between gap-3 border-b border-white/10 p-2 pl-2.5">
+ <slot name="selector" />
+ <UButton
+ label="Copy"
+ icon="i-heroicons-clipboard-document"
+ size="xs"
+ color="neutral"
+ variant="soft"
+ @click="$emit('copy')"
+ />
+ </div>
+ <div v-if="$slots.instructions" class="border-b border-white/10 px-4 py-3">
+ <slot name="instructions" />
+ </div>
+ <pre
+ id="mcp-client-config-panel"
+ role="region"
+ :aria-label="`${label} configuration`"
+ class="max-h-72 overflow-auto p-4 text-xs leading-6 text-blue-100"
+ ><code>{{ content }}</code></pre>
+ </div>
+</template>
+
+<script setup>
+defineProps({
+ label: {
+ type: String,
+ required: true,
+ },
+ content: {
+ type: String,
+ required: true,
+ },
+})
+
+defineEmits(['copy'])
+</script>
diff --git a/client/composables/query/useCurrentWorkspace.js b/client/composables/query/useCurrentWorkspace.js
index 24f801a42..2197084f2 100644
--- a/client/composables/query/useCurrentWorkspace.js
+++ b/client/composables/query/useCurrentWorkspace.js
@@ -108,6 +108,7 @@ export function useCurrentWorkspace() {
// Primary state
current,
currentId,
+ workspaces: workspacesQuery.data,
// Status indicators
isLoading,
@@ -118,4 +119,4 @@ export function useCurrentWorkspace() {
// Actions
switchTo,
}
-}
\ No newline at end of file
+}
diff --git a/client/lib/forms/agent-draft-autosave.js b/client/lib/forms/agent-draft-autosave.js
new file mode 100644
index 000000000..b65725ac5
--- /dev/null
+++ b/client/lib/forms/agent-draft-autosave.js
@@ -0,0 +1,25 @@
+export function createAgentDraftAutosave(sync, delay = 900) {
+ let timer = null
+
+ function clear() {
+ if (timer === null) return
+ clearTimeout(timer)
+ timer = null
+ }
+
+ function schedule() {
+ clear()
+ timer = setTimeout(() => {
+ timer = null
+ sync({ keepalive: false }).catch(() => {})
+ }, delay)
+ }
+
+ function flush() {
+ if (timer === null) return Promise.resolve()
+ clear()
+ return sync({ keepalive: true })
+ }
+
+ return { schedule, flush }
+}
diff --git a/client/lib/forms/agent-draft-errors.js b/client/lib/forms/agent-draft-errors.js
new file mode 100644
index 000000000..1f87afc86
--- /dev/null
+++ b/client/lib/forms/agent-draft-errors.js
@@ -0,0 +1,9 @@
+export function isAgentDraftVersionConflict(exception) {
+ const status = exception?.statusCode ?? exception?.status ?? exception?.response?.status
+ const errors = exception?.data?.errors ?? exception?.response?._data?.errors
+
+ return status === 422
+ && errors !== null
+ && typeof errors === 'object'
+ && Object.prototype.hasOwnProperty.call(errors, 'expected_version')
+}
diff --git a/client/lib/forms/agent-draft-session.js b/client/lib/forms/agent-draft-session.js
new file mode 100644
index 000000000..adfbecfc8
--- /dev/null
+++ b/client/lib/forms/agent-draft-session.js
@@ -0,0 +1,20 @@
+export function getAgentDraftSessionRequest(hash = '') {
+ const handoffToken = new URLSearchParams(hash.replace(/^#/, '')).get('handoff')
+
+ if (!handoffToken) {
+ return {
+ url: '/api/agent-drafts/current',
+ options: undefined,
+ consumesHandoff: false,
+ }
+ }
+
+ return {
+ url: '/api/agent-drafts/handoff',
+ options: {
+ method: 'POST',
+ body: { handoff_token: handoffToken },
+ },
+ consumesHandoff: true,
+ }
+}
diff --git a/client/pages/agent-drafts/edit.vue b/client/pages/agent-drafts/edit.vue
new file mode 100644
index 000000000..546b3d89d
--- /dev/null
+++ b/client/pages/agent-drafts/edit.vue
@@ -0,0 +1,269 @@
+<template>
+ <div class="flex min-h-screen flex-col bg-white">
+ <div v-if="loading" class="flex grow items-center justify-center">
+ <div class="text-center">
+ <Loader class="mx-auto h-7 w-7 text-blue-500" />
+ <p class="mt-3 text-sm text-neutral-500">Opening your private draft…</p>
+ </div>
+ </div>
+
+ <div v-else-if="fatalError" class="mx-auto flex max-w-xl grow items-center p-6">
+ <UAlert color="error" title="Unable to open this draft" :description="fatalError" />
+ </div>
+
+ <FormEditor
+ v-else
+ class="w-full grow"
+ :loading="saving"
+ :save-handler="syncDraft"
+ :back-button="false"
+ >
+ <template #before-save>
+ <div class="mr-2 hidden items-center gap-2 sm:flex">
+ <span class="text-xs text-neutral-500">{{ syncLabel }}</span>
+ <UButton
+ size="sm"
+ color="neutral"
+ variant="outline"
+ :loading="claiming"
+ @click.stop="prepareClaim"
+ >
+ Save to my account
+ </UButton>
+ </div>
+ </template>
+ </FormEditor>
+
+ <UModal v-model:open="workspaceModalOpen" :ui="{ content: 'sm:max-w-md' }">
+ <template #header>
+ <div>
+ <h2 class="font-semibold">Choose a workspace</h2>
+ <p class="mt-1 text-sm font-normal text-neutral-500">The form will be saved as an unpublished draft.</p>
+ </div>
+ </template>
+ <template #body>
+ <SelectInput
+ v-model="selectedWorkspaceId"
+ name="workspace"
+ label="Workspace"
+ :options="workspaceOptions"
+ :required="true"
+ />
+ </template>
+ <template #footer>
+ <div class="flex w-full justify-end gap-2">
+ <UButton color="neutral" variant="outline" @click="workspaceModalOpen = false">Cancel</UButton>
+ <UButton :loading="claiming" @click="claimDraft">Save draft</UButton>
+ </div>
+ </template>
+ </UModal>
+ </div>
+</template>
+
+<script setup>
+import FormEditor from '~/components/open/forms/components/FormEditor.vue'
+import { workspaceApi } from '~/api'
+import { WindowMessageTypes } from '~/composables/useWindowMessage'
+import { createAgentDraftAutosave } from '~/lib/forms/agent-draft-autosave'
+import { getAgentDraftSessionRequest } from '~/lib/forms/agent-draft-session'
+import { isAgentDraftVersionConflict } from '~/lib/forms/agent-draft-errors.js'
+
+definePageMeta({ layout: 'empty' })
+useOpnSeoMeta({ title: 'Edit private form draft' })
+
+const appStore = useAppStore()
+const workingFormStore = useWorkingFormStore()
+const { isAuthenticated } = useIsAuthenticated()
+provide('disableCustomCodeExecution', true)
+
+const loading = ref(true)
+const saving = ref(false)
+const claiming = ref(false)
+const fatalError = ref(null)
+const version = ref(null)
+const lastSavedFingerprint = ref(null)
+const syncState = ref('saved')
+const workspaces = ref([])
+const selectedWorkspaceId = ref(null)
+const workspaceModalOpen = ref(false)
+const claimAfterLogin = ref(false)
+const hydratingEditor = ref(true)
+let syncPromise = null
+
+const syncLabel = computed(() => ({
+ saving: 'Saving draft…',
+ error: 'Draft not saved',
+ saved: `Draft saved · v${version.value || '?'}`,
+}[syncState.value]))
+const workspaceOptions = computed(() => workspaces.value.map(workspace => ({
+ name: workspace.name,
+ value: workspace.id,
+})))
+
+const cleanDefinition = (data) => {
+ const definition = JSON.parse(JSON.stringify(data))
+ delete definition.id
+ delete definition.slug
+ delete definition.workspace_id
+ delete definition.workspace
+ delete definition.bypass_success_page
+ delete definition.share_url
+ delete definition.created_at
+ delete definition.updated_at
+ return definition
+}
+
+const applyDraft = (draft) => {
+ version.value = draft.version
+ const definition = cleanDefinition(draft.definition)
+ lastSavedFingerprint.value = JSON.stringify(definition)
+ workingFormStore.set(useForm(definition))
+ syncState.value = 'saved'
+}
+
+const refreshDraft = () => $fetch('/api/agent-drafts/current').then((response) => {
+ applyDraft(response.draft)
+ return response.draft
+})
+
+const performSync = (rawData, keepalive = false) => {
+ const definition = cleanDefinition(rawData || workingFormStore.content?.data())
+ const fingerprint = JSON.stringify(definition)
+ if (!definition || fingerprint === lastSavedFingerprint.value) {
+ return Promise.resolve()
+ }
+ if (syncPromise) {
+ return syncPromise.then(() => performSync(definition, keepalive))
+ }
+
+ saving.value = true
+ syncState.value = 'saving'
+ syncPromise = $fetch('/api/agent-drafts/current', {
+ method: 'PUT',
+ body: { expected_version: version.value, definition },
+ keepalive,
+ }).then((response) => {
+ version.value = response.draft.version
+ lastSavedFingerprint.value = JSON.stringify(cleanDefinition(response.draft.definition))
+ syncState.value = 'saved'
+ }).catch((exception) => {
+ syncState.value = 'error'
+ if (isAgentDraftVersionConflict(exception)) {
+ return refreshDraft().then(() => {
+ useAlert().warning('The draft changed in the conversation. The editor was refreshed with the latest version.')
+ })
+ }
+ useAlert().error(exception?.data?.message || 'Unable to save this draft right now.')
+ throw exception
+ }).finally(() => {
+ saving.value = false
+ syncPromise = null
+ })
+
+ return syncPromise
+}
+
+const syncDraft = (data) => performSync(data).then(() => {
+ useAlert().success('Draft saved.')
+})
+
+const draftAutosave = createAgentDraftAutosave(({ keepalive }) => performSync(undefined, keepalive))
+
+const scheduleSync = () => {
+ if (loading.value || claiming.value || hydratingEditor.value) return
+ draftAutosave.schedule()
+}
+
+const flushPendingSync = () => draftAutosave.flush().catch(() => {})
+
+watch(() => workingFormStore.content?.data?.(), scheduleSync, { deep: true })
+
+const prepareClaim = () => {
+ if (!isAuthenticated.value) {
+ claimAfterLogin.value = true
+ appStore.quickRegisterModal = true
+ return
+ }
+
+ claiming.value = true
+ performSync().then(() => workspaceApi.list()).then((availableWorkspaces) => {
+ workspaces.value = availableWorkspaces || []
+ if (workspaces.value.length === 1) {
+ selectedWorkspaceId.value = workspaces.value[0].id
+ return claimDraft()
+ }
+ if (workspaces.value.length === 0) {
+ throw new Error('Your account does not have a workspace yet.')
+ }
+ selectedWorkspaceId.value = null
+ claiming.value = false
+ workspaceModalOpen.value = true
+ }).catch((exception) => {
+ useAlert().error(exception?.data?.message || exception.message || 'Unable to prepare this draft for your account.')
+ }).finally(() => {
+ if (!workspaceModalOpen.value) claiming.value = false
+ })
+}
+
+const claimDraft = () => {
+ if (!selectedWorkspaceId.value) {
+ useAlert().error('Please select a workspace.')
+ return Promise.resolve()
+ }
+
+ claiming.value = true
+ return performSync().then(() => $fetch('/api/agent-drafts/claim', {
+ method: 'POST',
+ body: {
+ expected_version: version.value,
+ workspace_id: selectedWorkspaceId.value,
+ },
+ })).then((response) => {
+ workspaceModalOpen.value = false
+ if (response.cleanings && Object.keys(response.cleanings).length > 0) {
+ useAlert().warning('The form was saved. Some premium features will stay disabled when the form is shared.', 10000, { form: response.form })
+ } else {
+ useAlert().success('Form saved to your account as an unpublished draft.')
+ }
+ window.location.assign(response.editor_url)
+ }).catch((exception) => {
+ useAlert().error(exception?.data?.message || 'Unable to save this form to your account.')
+ }).finally(() => {
+ claiming.value = false
+ })
+}
+
+onMounted(() => {
+ window.addEventListener('pagehide', flushPendingSync)
+
+ const sessionRequest = getAgentDraftSessionRequest(window.location.hash)
+ if (sessionRequest.consumesHandoff) {
+ window.history.replaceState({}, '', '/agent-drafts/edit')
+ }
+ $fetch(sessionRequest.url, sessionRequest.options).then((response) => {
+ applyDraft(response.draft)
+ }).catch((exception) => {
+ fatalError.value = exception?.data?.message || 'This editor link is invalid or expired. Ask the agent for a fresh link.'
+ }).finally(() => {
+ loading.value = false
+ if (!fatalError.value) {
+ nextTick().then(() => {
+ lastSavedFingerprint.value = JSON.stringify(cleanDefinition(workingFormStore.content?.data()))
+ hydratingEditor.value = false
+ })
+ }
+ })
+
+ useWindowMessage(WindowMessageTypes.AFTER_LOGIN).listen(() => {
+ if (claimAfterLogin.value) {
+ claimAfterLogin.value = false
+ prepareClaim()
+ }
+ }, { useMessageChannel: false })
+})
+
+onBeforeUnmount(() => {
+ window.removeEventListener('pagehide', flushPendingSync)
+ flushPendingSync()
+})
+</script>
diff --git a/client/pages/agent-drafts/preview.vue b/client/pages/agent-drafts/preview.vue
new file mode 100644
index 000000000..cb8e6ab52
--- /dev/null
+++ b/client/pages/agent-drafts/preview.vue
@@ -0,0 +1,130 @@
+<template>
+ <div
+ class="relative bg-transparent"
+ :class="isEmbedded && isFocused ? 'h-screen' : (!isEmbedded ? 'min-h-screen pt-2' : '')"
+ >
+ <div :class="isEmbedded && isFocused ? 'h-full w-full' : 'mx-auto max-w-5xl'">
+ <header
+ v-if="!isEmbedded || isSubmitted"
+ class="flex min-h-8 items-center gap-3"
+ :class="isEmbedded ? 'absolute right-4 top-4 z-30' : 'mb-2'"
+ >
+ <p v-if="!isEmbedded" class="flex items-center gap-2 text-sm font-medium text-neutral-700">
+ <span class="size-2 rounded-full bg-blue-500" aria-hidden="true" />
+ Private preview
+ </p>
+ <UButton
+ v-if="isSubmitted"
+ color="neutral"
+ variant="outline"
+ size="sm"
+ icon="i-lucide-rotate-ccw"
+ class="ml-auto"
+ :loading="isResetting"
+ :disabled="isResetting"
+ aria-label="Reset form"
+ @click="resetForm"
+ >
+ Reset form
+ </UButton>
+ </header>
+
+ <div v-if="loading" class="rounded-xl border bg-white p-12 text-center">
+ <Loader class="mx-auto h-6 w-6 text-blue-500" />
+ </div>
+ <UAlert
+ v-else-if="error"
+ color="error"
+ :title="errorTitle"
+ :description="error"
+ />
+ <div
+ v-else
+ class="overflow-hidden border border-neutral-200 bg-white shadow-sm"
+ :class="isEmbedded && isFocused ? 'h-full' : (isEmbedded ? '' : 'min-h-[650px] rounded-xl')"
+ >
+ <OpenCompleteForm
+ ref="formPreview"
+ :form="form"
+ :mode="FormMode.TEST"
+ class="w-full"
+ :class="{
+ 'h-full': isEmbedded && isFocused,
+ 'min-h-[650px]': !isEmbedded,
+ 'pt-3 sm:pt-4': !isFocused,
+ }"
+ @submitted="isSubmitted = true"
+ @restarted="isSubmitted = false"
+ />
+ </div>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import OpenCompleteForm from '~/components/open/forms/OpenCompleteForm.vue'
+import { FormMode } from '~/lib/forms/FormModeStrategy.js'
+
+definePageMeta({ layout: 'empty' })
+useOpnSeoMeta({ title: 'Private form draft preview' })
+useHead({
+ script: [{ src: '/widgets/iframeResizer.contentWindow.min.js' }],
+})
+
+const route = useRoute()
+const config = useRuntimeConfig()
+const alert = useAlert()
+const loading = ref(true)
+const errorTitle = ref('This preview is unavailable')
+const error = ref(null)
+const form = ref(null)
+const formPreview = ref(null)
+const isSubmitted = ref(false)
+const isResetting = ref(false)
+const isEmbedded = computed(() => route.query.embedded === '1')
+const isFocused = computed(() => form.value?.presentation_style === 'focused')
+provide('disableCustomCodeExecution', true)
+
+const resetForm = () => {
+ if (!formPreview.value?.restart || isResetting.value) return
+
+ isResetting.value = true
+ formPreview.value.restart()
+ .catch(() => {
+ alert.error('The form could not be reset. Please try again.')
+ })
+ .finally(() => {
+ isResetting.value = false
+ })
+}
+
+onMounted(() => {
+ try {
+ const source = new URL(String(route.query.source || ''))
+ const configuredApi = config.public.apiBase ? new URL(config.public.apiBase, window.location.origin) : null
+ const expectedOrigin = configuredApi?.origin || window.location.origin
+ if (source.origin !== expectedOrigin || !source.pathname.includes('/agent-drafts/preview/')) {
+ throw new Error('The preview link is invalid.')
+ }
+
+ $fetch(source.toString()).then((response) => {
+ form.value = {
+ ...response.draft.definition,
+ no_branding: true,
+ plan_tier: 'pro',
+ is_trialing: false,
+ max_file_size: 10,
+ workspace: { plan_tier: 'pro', features: [], limits: {} },
+ }
+ }).catch(() => {
+ errorTitle.value = 'This preview link has expired'
+ error.value = 'Your draft is usually still available for seven days. Ask your AI assistant: “Generate a new preview of this form.”'
+ }).finally(() => {
+ loading.value = false
+ })
+ } catch (exception) {
+ error.value = exception.message || 'The preview link is invalid.'
+ loading.value = false
+ }
+})
+</script>
diff --git a/client/pages/mcp/authorize.vue b/client/pages/mcp/authorize.vue
new file mode 100644
index 000000000..0c855c3c9
--- /dev/null
+++ b/client/pages/mcp/authorize.vue
@@ -0,0 +1,48 @@
+<template>
+ <div class="flex min-h-screen items-center justify-center bg-neutral-50 px-6">
+ <div class="w-full max-w-md rounded-2xl border border-neutral-200 bg-white p-8 text-center shadow-sm">
+ <div class="mx-auto flex w-fit items-center gap-2.5" aria-label="OpnForm">
+ <img src="/img/logo.svg" alt="" class="h-10 w-10">
+ <span class="text-lg font-semibold tracking-tight text-neutral-950">OpnForm</span>
+ </div>
+ <h1 class="mt-4 text-xl font-semibold text-neutral-950">Connecting your OpnForm account</h1>
+ <p class="mt-2 text-sm text-neutral-600">
+ You will be redirected to review the access requested by your AI assistant.
+ </p>
+ <UProgress class="mt-6" animation="carousel" />
+ <p v-if="error" class="mt-4 text-sm text-red-600">{{ error }}</p>
+ </div>
+ </div>
+</template>
+
+<script setup>
+definePageMeta({ middleware: 'auth' })
+
+const route = useRoute()
+const error = ref('')
+
+onMounted(() => {
+ const requestToken = typeof route.query.request === 'string' ? route.query.request : ''
+
+ if (!/^[A-Za-z0-9]{64}$/.test(requestToken)) {
+ error.value = 'This authorization request is invalid or has expired.'
+ return
+ }
+
+ opnFetch('/mcp-oauth/session', {
+ method: 'POST',
+ body: { authorization_request_token: requestToken },
+ })
+ .then((response) => {
+ window.location.assign(response.authorization_url)
+ })
+ .catch((requestError) => {
+ error.value = requestError?.data?.message || 'Unable to continue the authorization flow.'
+ })
+})
+
+useOpnSeoMeta({
+ title: 'Connect your OpnForm account',
+ robots: 'noindex, nofollow',
+})
+</script>
diff --git a/client/pages/mcp/index.vue b/client/pages/mcp/index.vue
new file mode 100644
index 000000000..f20fba2b8
--- /dev/null
+++ b/client/pages/mcp/index.vue
@@ -0,0 +1,804 @@
+<template>
+ <div class="flex-1 overflow-hidden bg-white">
+ <section class="relative border-b border-neutral-200 bg-[#f7f9fc]">
+ <div
+ aria-hidden="true"
+ class="absolute inset-0 opacity-70 [background-image:linear-gradient(to_right,#dbe4f0_1px,transparent_1px),linear-gradient(to_bottom,#dbe4f0_1px,transparent_1px)] [background-size:32px_32px] [mask-image:linear-gradient(to_bottom,black,transparent_90%)]"
+ />
+ <div
+ aria-hidden="true"
+ class="absolute -left-24 top-28 h-72 w-72 rounded-full bg-blue-200/40 blur-3xl"
+ />
+ <div
+ aria-hidden="true"
+ class="absolute -right-20 bottom-8 h-64 w-64 rounded-full bg-amber-100/70 blur-3xl"
+ />
+
+ <div
+ class="relative mx-auto grid max-w-7xl items-center gap-14 px-5 py-16 sm:px-8 sm:py-20 lg:grid-cols-[0.92fr_1.08fr] lg:px-12 lg:py-28"
+ >
+ <div class="max-w-2xl">
+ <div
+ class="inline-flex items-center gap-2 rounded-full border border-blue-200 bg-white/80 px-3.5 py-1.5 text-sm font-medium text-blue-700 shadow-xs backdrop-blur"
+ >
+ <span class="relative flex h-2 w-2">
+ <span
+ class="absolute inline-flex h-full w-full animate-ping rounded-full bg-blue-400 opacity-60 motion-reduce:animate-none"
+ />
+ <span class="relative inline-flex h-2 w-2 rounded-full bg-blue-600" />
+ </span>
+ OpnForm for AI agents
+ </div>
+
+ <h1
+ class="mt-6 text-4xl font-semibold tracking-[-0.04em] text-neutral-950 sm:text-5xl lg:text-6xl lg:leading-[1.05]"
+ >
+ The MCP form builder that turns
+ <span class="text-blue-600">conversations into forms</span>
+ </h1>
+ <p
+ class="mt-6 max-w-xl text-lg leading-8 text-neutral-600 sm:text-xl sm:leading-9"
+ >
+ Ask your AI assistant for the form you need. OpnForm creates a private
+ draft, lets you preview it, and hands it back to you in the full editor
+ when you are ready.
+ </p>
+
+ <div class="mt-8 flex flex-col gap-3 sm:flex-row">
+ <UButton
+ to="https://docs.opnform.com/integrations/mcp"
+ external
+ size="lg"
+ label="Connect your AI assistant"
+ trailing-icon="i-heroicons-arrow-up-right-20-solid"
+ class="justify-center rounded-xl px-5"
+ />
+ <UButton
+ to="#how-it-works"
+ size="lg"
+ color="neutral"
+ variant="outline"
+ label="See how it works"
+ trailing-icon="i-heroicons-arrow-down-20-solid"
+ class="justify-center rounded-xl px-5"
+ />
+ </div>
+
+ <ul class="mt-8 flex flex-wrap gap-x-6 gap-y-3 text-sm font-medium text-neutral-700">
+ <li v-for="proof in heroProofs" :key="proof" class="flex items-center gap-2">
+ <UIcon
+ name="i-heroicons-check-circle-20-solid"
+ class="h-5 w-5 text-emerald-600"
+ />
+ {{ proof }}
+ </li>
+ </ul>
+ </div>
+
+ <div class="relative mx-auto w-full max-w-2xl lg:mx-0">
+ <div
+ aria-hidden="true"
+ class="absolute -inset-5 rotate-2 rounded-[2rem] border border-blue-200 bg-blue-100/50"
+ />
+ <div
+ class="relative overflow-hidden rounded-[1.75rem] border border-neutral-200 bg-white p-4 shadow-2xl shadow-blue-950/10 sm:p-6"
+ >
+ <div class="flex items-center justify-between border-b border-neutral-100 pb-4">
+ <div class="flex items-center gap-3">
+ <div
+ class="flex h-9 w-9 items-center justify-center rounded-xl bg-neutral-950 text-white"
+ >
+ <UIcon name="i-heroicons-sparkles-20-solid" class="h-4 w-4" />
+ </div>
+ <div>
+ <p class="text-sm font-semibold text-neutral-950">Your AI assistant</p>
+ <p class="text-xs text-neutral-500">Connected to OpnForm</p>
+ </div>
+ </div>
+ <span
+ class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors duration-300"
+ :class="
+ isHeroDemoWorking
+ ? 'bg-blue-50 text-blue-700'
+ : 'bg-emerald-50 text-emerald-700'
+ "
+ >
+ <span
+ class="h-1.5 w-1.5 rounded-full"
+ :class="isHeroDemoWorking ? 'animate-pulse bg-blue-500' : 'bg-emerald-500'"
+ />
+ {{ heroDemoStatusLabel }}
+ </span>
+ </div>
+
+ <div
+ class="mt-5 min-h-[88px] max-w-[88%] rounded-2xl rounded-tl-sm bg-neutral-100 p-4"
+ >
+ <p class="text-sm leading-6 text-neutral-700" :aria-label="heroPrompt">
+ <span aria-hidden="true">{{ displayedHeroPrompt }}</span>
+ <span
+ v-if="heroDemoPhase === 'typing'"
+ aria-hidden="true"
+ class="ml-0.5 inline-block h-4 w-px translate-y-0.5 animate-pulse bg-neutral-500"
+ />
+ </p>
+ </div>
+
+ <div class="mt-4 min-h-8">
+ <Transition name="hero-demo-status" mode="out-in">
+ <div
+ v-if="heroDemoPhase === 'building'"
+ key="building"
+ class="flex items-center gap-3 text-sm font-medium text-neutral-600"
+ >
+ <span class="flex h-8 w-8 items-center justify-center rounded-full bg-blue-50">
+ <span class="relative h-4 w-4">
+ <span class="absolute inset-0 rounded-full border-2 border-blue-200" />
+ <span
+ class="absolute inset-0 animate-spin rounded-full border-2 border-transparent border-t-blue-600 motion-reduce:animate-none"
+ />
+ </span>
+ </span>
+ Building your private draft
+ <span class="flex gap-1" aria-hidden="true">
+ <span class="hero-demo-dot" />
+ <span class="hero-demo-dot [animation-delay:120ms]" />
+ <span class="hero-demo-dot [animation-delay:240ms]" />
+ </span>
+ </div>
+ <div
+ v-else-if="heroDemoPhase === 'complete'"
+ key="complete"
+ class="flex items-center gap-3 text-sm font-medium text-blue-700"
+ >
+ <span class="flex h-8 w-8 items-center justify-center rounded-full bg-blue-50">
+ <UIcon name="i-heroicons-arrow-turn-down-right-20-solid" class="h-4 w-4" />
+ </span>
+ Draft created. Here is your preview.
+ </div>
+ </Transition>
+ </div>
+
+ <div
+ class="mt-4 min-h-[314px] overflow-hidden rounded-2xl border bg-[#fffdf9] transition-all duration-300"
+ :class="
+ isHeroPreviewVisible
+ ? 'translate-y-0 border-neutral-200 opacity-100 shadow-lg shadow-neutral-950/5'
+ : 'translate-y-2 border-neutral-100 opacity-0 shadow-none'
+ "
+ >
+ <div class="flex items-center justify-between border-b border-neutral-200 px-5 py-3">
+ <div class="flex items-center gap-2">
+ <span class="h-2.5 w-2.5 rounded-full bg-red-300" />
+ <span class="h-2.5 w-2.5 rounded-full bg-amber-300" />
+ <span class="h-2.5 w-2.5 rounded-full bg-emerald-300" />
+ </div>
+ <span class="text-[11px] font-medium uppercase tracking-[0.14em] text-neutral-400">
+ Private preview
+ </span>
+ </div>
+ <div class="p-5 sm:p-6">
+ <div
+ class="flex items-start justify-between gap-4 transition-all duration-300"
+ :class="heroDemoBlockClass(1)"
+ >
+ <div>
+ <p class="text-xl font-semibold tracking-tight text-neutral-950">
+ Summer dinner registration
+ </p>
+ <p class="mt-1 text-sm text-neutral-500">We would love to see you there.</p>
+ </div>
+ <span
+ class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-100 text-amber-700"
+ >
+ <UIcon name="i-heroicons-sun-20-solid" class="h-5 w-5" />
+ </span>
+ </div>
+ <div class="mt-6 grid gap-3 sm:grid-cols-2">
+ <div
+ v-for="(field, index) in previewFields"
+ :key="field"
+ class="rounded-xl border border-neutral-200 bg-white px-3.5 py-3 text-sm text-neutral-500 transition-all duration-300"
+ :class="heroDemoBlockClass(index + 2)"
+ >
+ {{ field }}
+ </div>
+ </div>
+ <div
+ class="mt-5 flex justify-center transition-all duration-300"
+ :class="heroDemoBlockClass(6)"
+ >
+ <span
+ class="rounded-lg bg-blue-600 px-6 py-2 text-sm font-medium text-white shadow-sm"
+ >
+ Submit
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="border-b border-neutral-200 bg-white py-16 sm:py-20 lg:py-24">
+ <div class="mx-auto grid max-w-6xl gap-10 px-5 sm:px-8 lg:grid-cols-[0.75fr_1.25fr] lg:px-12">
+ <div>
+ <p class="text-sm font-semibold uppercase tracking-[0.14em] text-blue-600">
+ In plain English
+ </p>
+ <h2 class="mt-4 text-3xl font-semibold tracking-tight text-neutral-950 sm:text-4xl">
+ What is an MCP form builder?
+ </h2>
+ </div>
+ <div class="space-y-5 text-lg leading-8 text-neutral-600">
+ <p>
+ MCP is a shared way for AI assistants to work with products like OpnForm.
+ Instead of copying questions between a chat and a form builder, your
+ assistant can create the draft for you.
+ </p>
+ <p>
+ You stay in control: review the real form, ask for changes in the
+ conversation, then continue in OpnForm to customize, save, and publish it.
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <section id="how-it-works" class="scroll-mt-20 bg-neutral-950 py-16 text-white sm:py-20 lg:py-24">
+ <div class="mx-auto max-w-7xl px-5 sm:px-8 lg:px-12">
+ <div class="max-w-3xl">
+ <p class="text-sm font-semibold uppercase tracking-[0.14em] text-blue-300">
+ From idea to live form
+ </p>
+ <h2 class="mt-4 text-3xl font-semibold tracking-tight !text-white sm:text-4xl lg:text-5xl">
+ You describe it. Your agent builds it. You make it yours.
+ </h2>
+ </div>
+
+ <ol class="mt-12 grid gap-px overflow-hidden rounded-3xl bg-white/15 lg:grid-cols-3">
+ <li
+ v-for="(step, index) in steps"
+ :key="step.title"
+ class="relative bg-neutral-950 p-7 sm:p-8"
+ >
+ <span
+ class="text-6xl font-semibold tracking-tighter text-white/25"
+ aria-hidden="true"
+ >
+ 0{{ index + 1 }}
+ </span>
+ <UIcon :name="step.icon" class="mt-8 h-7 w-7 text-blue-300" />
+ <h3 class="mt-4 text-xl font-semibold text-white">{{ step.title }}</h3>
+ <p class="mt-3 leading-7 text-neutral-300">{{ step.description }}</p>
+ </li>
+ </ol>
+ </div>
+ </section>
+
+ <section class="bg-[#f7f9fc] py-16 sm:py-20 lg:py-24">
+ <div class="mx-auto max-w-7xl px-5 sm:px-8 lg:px-12">
+ <div class="mx-auto max-w-3xl text-center">
+ <p class="text-sm font-semibold uppercase tracking-[0.14em] text-blue-600">
+ One connection, two ways to work
+ </p>
+ <h2 class="mt-4 text-3xl font-semibold tracking-tight text-neutral-950 sm:text-4xl lg:text-5xl">
+ Start without an account. Connect when you need more.
+ </h2>
+ <p class="mt-5 text-lg leading-8 text-neutral-600">
+ OpnForm keeps the first experience frictionless without giving an agent
+ more access than it needs.
+ </p>
+ </div>
+
+ <div class="mx-auto mt-12 grid max-w-5xl gap-6 lg:grid-cols-2">
+ <article
+ v-for="mode in modes"
+ :key="mode.title"
+ class="relative overflow-hidden rounded-3xl border border-neutral-200 bg-white p-7 shadow-sm sm:p-9"
+ >
+ <div
+ class="absolute right-0 top-0 h-36 w-36 rounded-bl-full opacity-60"
+ :class="mode.accentClass"
+ aria-hidden="true"
+ />
+ <div
+ class="relative flex h-12 w-12 items-center justify-center rounded-2xl"
+ :class="mode.iconClass"
+ >
+ <UIcon :name="mode.icon" class="h-6 w-6" />
+ </div>
+ <p class="relative mt-6 text-sm font-semibold uppercase tracking-[0.12em] text-neutral-500">
+ {{ mode.eyebrow }}
+ </p>
+ <h3 class="relative mt-2 text-2xl font-semibold text-neutral-950">{{ mode.title }}</h3>
+ <p class="relative mt-3 leading-7 text-neutral-600">{{ mode.description }}</p>
+ <ul class="relative mt-6 space-y-3">
+ <li v-for="item in mode.items" :key="item" class="flex gap-3 text-neutral-700">
+ <UIcon
+ name="i-heroicons-check-20-solid"
+ class="mt-0.5 h-5 w-5 shrink-0 text-emerald-600"
+ />
+ <span>{{ item }}</span>
+ </li>
+ </ul>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <section class="border-y border-neutral-200 bg-white py-16 sm:py-20 lg:py-24">
+ <div class="mx-auto max-w-7xl px-5 sm:px-8 lg:px-12">
+ <div class="grid gap-12 lg:grid-cols-[0.85fr_1.15fr] lg:items-center">
+ <div>
+ <p class="text-sm font-semibold uppercase tracking-[0.14em] text-blue-600">
+ Useful from day one
+ </p>
+ <h2 class="mt-4 text-3xl font-semibold tracking-tight text-neutral-950 sm:text-4xl">
+ Forms are work. Your assistant can take the first pass.
+ </h2>
+ <p class="mt-5 text-lg leading-8 text-neutral-600">
+ Give it the context you already have — an event, a hiring process, a
+ customer request, or a research goal — and start from a usable form
+ instead of an empty canvas.
+ </p>
+ <UButton
+ :to="{ name: 'ai-form-builder' }"
+ variant="link"
+ label="Explore OpnForm's built-in AI form builder"
+ trailing-icon="i-heroicons-arrow-right-20-solid"
+ class="mt-5 px-0"
+ />
+ </div>
+
+ <div class="grid gap-4 sm:grid-cols-2">
+ <article
+ v-for="useCase in useCases"
+ :key="useCase.title"
+ class="rounded-2xl border border-neutral-200 p-5 transition hover:-translate-y-0.5 hover:border-blue-200 hover:shadow-md"
+ >
+ <UIcon :name="useCase.icon" class="h-6 w-6 text-blue-600" />
+ <h3 class="mt-4 font-semibold text-neutral-950">{{ useCase.title }}</h3>
+ <p class="mt-2 text-sm leading-6 text-neutral-600">{{ useCase.description }}</p>
+ </article>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="bg-white py-16 sm:py-20 lg:py-24">
+ <div class="mx-auto max-w-7xl px-5 sm:px-8 lg:px-12">
+ <div class="mx-auto max-w-3xl text-center">
+ <p class="text-sm font-semibold uppercase tracking-[0.14em] text-blue-600">
+ Control stays with you
+ </p>
+ <h2 class="mt-4 text-3xl font-semibold tracking-tight text-neutral-950 sm:text-4xl lg:text-5xl">
+ Helpful automation, with sensible boundaries
+ </h2>
+ </div>
+
+ <div class="mt-12 grid gap-6 md:grid-cols-2 lg:grid-cols-4">
+ <article v-for="guardrail in guardrails" :key="guardrail.title" class="p-2">
+ <div
+ class="flex h-11 w-11 items-center justify-center rounded-full bg-emerald-50 text-emerald-700"
+ >
+ <UIcon :name="guardrail.icon" class="h-5 w-5" />
+ </div>
+ <h3 class="mt-5 font-semibold text-neutral-950">{{ guardrail.title }}</h3>
+ <p class="mt-2 text-sm leading-6 text-neutral-600">{{ guardrail.description }}</p>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <section class="border-y border-neutral-200 bg-neutral-50 py-16 sm:py-20 lg:py-24">
+ <div class="mx-auto max-w-5xl px-5 sm:px-8 lg:px-12">
+ <div class="grid gap-10 lg:grid-cols-[0.8fr_1.2fr]">
+ <div>
+ <p class="text-sm font-semibold uppercase tracking-[0.14em] text-blue-600">FAQ</p>
+ <h2 class="mt-4 text-3xl font-semibold tracking-tight text-neutral-950 sm:text-4xl">
+ Questions about the OpnForm MCP
+ </h2>
+ </div>
+ <div class="divide-y divide-neutral-200 border-y border-neutral-200">
+ <details v-for="faq in faqs" :key="faq.question" class="group py-5">
+ <summary
+ class="flex cursor-pointer list-none items-center justify-between gap-5 font-semibold text-neutral-950"
+ >
+ {{ faq.question }}
+ <UIcon
+ name="i-heroicons-plus-20-solid"
+ class="h-5 w-5 shrink-0 text-neutral-500 transition group-open:rotate-45"
+ />
+ </summary>
+ <p class="mt-3 max-w-2xl pr-8 leading-7 text-neutral-600">{{ faq.answer }}</p>
+ </details>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="bg-white px-5 py-16 sm:px-8 sm:py-20 lg:px-12 lg:py-24">
+ <div
+ class="relative mx-auto max-w-6xl overflow-hidden rounded-[2rem] bg-blue-700 px-6 py-12 text-center text-white shadow-xl shadow-blue-950/15 sm:px-12 sm:py-16"
+ >
+ <div
+ aria-hidden="true"
+ class="absolute inset-0 opacity-20 [background-image:radial-gradient(circle_at_center,white_1px,transparent_1.5px)] [background-size:22px_22px]"
+ />
+ <div class="relative mx-auto max-w-3xl">
+ <p class="text-sm font-semibold uppercase tracking-[0.14em] text-blue-100">
+ Your next form can start as a conversation
+ </p>
+ <h2 class="mt-4 text-3xl font-semibold tracking-tight !text-white sm:text-4xl lg:text-5xl">
+ Connect OpnForm to your AI assistant
+ </h2>
+ <p class="mx-auto mt-5 max-w-2xl text-lg leading-8 text-blue-100">
+ Start with a private draft — no OpnForm account required. Connect your
+ account later when you want to save, publish, or manage existing forms.
+ </p>
+ <div class="mt-8 flex flex-col justify-center gap-3 sm:flex-row">
+ <UButton
+ to="https://docs.opnform.com/integrations/mcp"
+ external
+ size="lg"
+ color="neutral"
+ label="Follow the setup guide"
+ trailing-icon="i-heroicons-arrow-up-right-20-solid"
+ class="justify-center rounded-xl bg-white px-5 text-blue-700 hover:bg-blue-50"
+ />
+ <UButton
+ :to="createFormTarget"
+ size="lg"
+ variant="solid"
+ color="neutral"
+ label="Create a form in OpnForm"
+ trailing-icon="i-heroicons-arrow-right-20-solid"
+ class="justify-center rounded-xl px-5 !bg-blue-950 !text-white hover:!bg-blue-900"
+ />
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <OpenFormFooter :show-cta="false" />
+ </div>
+</template>
+
+<script setup>
+definePageMeta({
+ layout: "default",
+ middleware: ["root-redirect", "self-hosted"],
+})
+
+useOpnSeoMeta({
+ title: "MCP Form Builder for AI Agents",
+ description:
+ "Create, preview, and refine forms with your AI assistant using OpnForm MCP. Start without an account, then save and manage forms when ready.",
+})
+
+defineRouteRules({
+ swr: 3600,
+})
+
+const { isAuthenticated: authenticated } = useIsAuthenticated()
+const isHydrated = ref(false)
+const heroPrompt =
+ "Create a friendly event registration form. Ask for a name, email, dietary requirements, and one guest."
+const displayedHeroPrompt = ref(heroPrompt)
+const heroDemoPhase = ref("complete")
+const isHeroPreviewVisible = ref(true)
+const visibleHeroBlocks = ref(6)
+const heroDemoTimeouts = []
+let reducedMotionQuery
+
+onMounted(() => {
+ isHydrated.value = true
+ reducedMotionQuery = window.matchMedia("(prefers-reduced-motion: reduce)")
+ reducedMotionQuery.addEventListener("change", handleReducedMotionChange)
+
+ if (!reducedMotionQuery.matches) {
+ scheduleHeroDemo(startHeroDemo, 1200)
+ }
+})
+
+onBeforeUnmount(() => {
+ clearHeroDemoTimeouts()
+ reducedMotionQuery?.removeEventListener("change", handleReducedMotionChange)
+})
+
+const isHeroDemoWorking = computed(() =>
+ ["typing", "building"].includes(heroDemoPhase.value),
+)
+
+const heroDemoStatusLabel = computed(() => {
+ if (heroDemoPhase.value === "typing") return "Listening"
+ if (heroDemoPhase.value === "building") return "Building"
+
+ return "Ready"
+})
+
+function scheduleHeroDemo(callback, delay) {
+ const timeoutId = window.setTimeout(callback, delay)
+ heroDemoTimeouts.push(timeoutId)
+}
+
+function clearHeroDemoTimeouts() {
+ heroDemoTimeouts.splice(0).forEach((timeoutId) => window.clearTimeout(timeoutId))
+}
+
+function showCompletedHeroDemo() {
+ displayedHeroPrompt.value = heroPrompt
+ heroDemoPhase.value = "complete"
+ isHeroPreviewVisible.value = true
+ visibleHeroBlocks.value = 6
+}
+
+function handleReducedMotionChange(event) {
+ clearHeroDemoTimeouts()
+
+ if (event.matches) {
+ showCompletedHeroDemo()
+ return
+ }
+
+ startHeroDemo()
+}
+
+function startHeroDemo() {
+ clearHeroDemoTimeouts()
+ displayedHeroPrompt.value = ""
+ heroDemoPhase.value = "typing"
+ isHeroPreviewVisible.value = false
+ visibleHeroBlocks.value = 0
+ typeHeroPrompt(1)
+}
+
+function typeHeroPrompt(characterCount) {
+ displayedHeroPrompt.value = heroPrompt.slice(0, characterCount)
+
+ if (characterCount < heroPrompt.length) {
+ scheduleHeroDemo(() => typeHeroPrompt(characterCount + 1), 12)
+ return
+ }
+
+ scheduleHeroDemo(buildHeroPreview, 180)
+}
+
+function buildHeroPreview() {
+ heroDemoPhase.value = "building"
+ isHeroPreviewVisible.value = true
+ scheduleHeroDemo(() => revealHeroBlock(1), 180)
+}
+
+function revealHeroBlock(blockNumber) {
+ visibleHeroBlocks.value = blockNumber
+
+ if (blockNumber < 6) {
+ scheduleHeroDemo(() => revealHeroBlock(blockNumber + 1), 150)
+ return
+ }
+
+ scheduleHeroDemo(completeHeroDemo, 260)
+}
+
+function completeHeroDemo() {
+ heroDemoPhase.value = "complete"
+ scheduleHeroDemo(resetHeroDemo, 2300)
+}
+
+function resetHeroDemo() {
+ heroDemoPhase.value = "resetting"
+ isHeroPreviewVisible.value = false
+ visibleHeroBlocks.value = 0
+ displayedHeroPrompt.value = ""
+ scheduleHeroDemo(startHeroDemo, 320)
+}
+
+function heroDemoBlockClass(blockNumber) {
+ return visibleHeroBlocks.value >= blockNumber
+ ? "translate-y-0 scale-100 opacity-100"
+ : "translate-y-2 scale-[0.985] opacity-0"
+}
+
+const createFormTarget = computed(() => ({
+ name: isHydrated.value && authenticated.value ? "forms-create" : "forms-create-guest",
+}))
+
+const heroProofs = ["No account to start", "Preview before saving", "Open source"]
+
+const previewFields = ["Full name", "Email address", "Dietary requirements", "Bringing a guest?"]
+
+const steps = [
+ {
+ icon: "i-heroicons-chat-bubble-left-right-20-solid",
+ title: "Describe what you need",
+ description:
+ "Tell your AI assistant who the form is for, what you want to learn, and any questions you already have in mind.",
+ },
+ {
+ icon: "i-heroicons-eye-20-solid",
+ title: "Review the real form",
+ description:
+ "Open an interactive preview, test the flow, and ask the agent to add, remove, or rewrite questions before anything goes live.",
+ },
+ {
+ icon: "i-heroicons-pencil-square-20-solid",
+ title: "Finish it in OpnForm",
+ description:
+ "Move the draft into the visual editor, adjust the design, sign in when you want to save, and publish only when you decide.",
+ },
+]
+
+const modes = [
+ {
+ eyebrow: "Guest mode",
+ title: "Create first, sign up later",
+ description:
+ "Try the MCP form builder from a compatible AI assistant without creating an OpnForm account.",
+ icon: "i-heroicons-sparkles-20-solid",
+ iconClass: "bg-amber-100 text-amber-700",
+ accentClass: "bg-amber-100",
+ items: [
+ "Create a private draft that lasts seven days",
+ "Preview and revise the form in your conversation",
+ "Open the draft in OpnForm's visual editor",
+ ],
+ },
+ {
+ eyebrow: "Connected account",
+ title: "Keep managing the work",
+ description:
+ "Securely connect your account when you want your assistant to help with existing forms and responses.",
+ icon: "i-heroicons-link-20-solid",
+ iconClass: "bg-blue-100 text-blue-700",
+ accentClass: "bg-blue-100",
+ items: [
+ "Create, update, review, and publish forms",
+ "Find and inspect the submissions you need",
+ "See form results without changing response data",
+ ],
+ },
+]
+
+const useCases = [
+ {
+ icon: "i-heroicons-calendar-days-20-solid",
+ title: "Events and registrations",
+ description: "Turn a date, audience, and agenda into a complete registration flow.",
+ },
+ {
+ icon: "i-heroicons-user-group-20-solid",
+ title: "Hiring and onboarding",
+ description: "Build application forms and internal check-ins from an existing brief.",
+ },
+ {
+ icon: "i-heroicons-chat-bubble-bottom-center-text-20-solid",
+ title: "Feedback and research",
+ description: "Shape clear surveys, interviews, and customer feedback forms with less setup.",
+ },
+ {
+ icon: "i-heroicons-inbox-arrow-down-20-solid",
+ title: "Requests and intake",
+ description: "Capture the details your team needs for leads, support, projects, or approvals.",
+ },
+]
+
+const guardrails = [
+ {
+ icon: "i-heroicons-eye-20-solid",
+ title: "Preview before saving",
+ description: "A generated form stays a private draft until you choose what happens next.",
+ },
+ {
+ icon: "i-heroicons-hand-raised-20-solid",
+ title: "Confirmation before publishing",
+ description: "Your agent asks before publishing or moving a form to trash.",
+ },
+ {
+ icon: "i-heroicons-lock-closed-20-solid",
+ title: "Secure account connection",
+ description: "Connect with OpnForm directly instead of sharing a password in the conversation.",
+ },
+ {
+ icon: "i-heroicons-document-magnifying-glass-20-solid",
+ title: "Read-only responses",
+ description: "Agents can help find and analyze submissions, but cannot alter or delete them.",
+ },
+]
+
+const faqs = [
+ {
+ question: "What is the OpnForm MCP form builder?",
+ answer:
+ "It connects a compatible AI assistant to OpnForm. You can describe a form in a conversation, receive a working preview, refine it, and then continue in OpnForm's visual editor.",
+ },
+ {
+ question: "Do I need an OpnForm account to create a form with an AI agent?",
+ answer:
+ "No. Guest mode can create a private draft without an account. The draft lasts seven days, and you only need to sign in when you want to save it to a workspace.",
+ },
+ {
+ question: "Can the agent publish or delete a form by itself?",
+ answer:
+ "No. Publishing and moving a form to trash require your confirmation. Guest drafts are never published automatically.",
+ },
+ {
+ question: "Can an AI assistant access my form submissions?",
+ answer:
+ "Only after you securely connect your OpnForm account. It can search, read, summarize, and export accessible submissions, but it cannot edit or delete response data.",
+ },
+ {
+ question: "Which AI assistants work with OpnForm MCP?",
+ answer:
+ "OpnForm is designed for ChatGPT and other AI assistants or agent clients that support remote MCP servers or Agent Plugins. Setup details vary by client, so check the integration guide for current instructions.",
+ },
+]
+
+const faqSchema = {
+ "@context": "https://schema.org",
+ "@type": "FAQPage",
+ mainEntity: faqs.map((faq) => ({
+ "@type": "Question",
+ name: faq.question,
+ acceptedAnswer: {
+ "@type": "Answer",
+ text: faq.answer,
+ },
+ })),
+}
+
+useHead({
+ script: [
+ {
+ key: "mcp-faq-schema",
+ type: "application/ld+json",
+ textContent: JSON.stringify(faqSchema),
+ },
+ ],
+})
+</script>
+
+<style scoped>
+.hero-demo-status-enter-active,
+.hero-demo-status-leave-active {
+ transition:
+ opacity 180ms ease,
+ transform 180ms ease;
+}
+
+.hero-demo-status-enter-from,
+.hero-demo-status-leave-to {
+ opacity: 0;
+ transform: translateY(4px);
+}
+
+.hero-demo-dot {
+ width: 4px;
+ height: 4px;
+ border-radius: 9999px;
+ background: rgb(96 165 250);
+ animation: hero-demo-dot 720ms ease-in-out infinite alternate;
+}
+
+@keyframes hero-demo-dot {
+ from {
+ opacity: 0.35;
+ transform: translateY(1px);
+ }
+
+ to {
+ opacity: 1;
+ transform: translateY(-1px);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .hero-demo-status-enter-active,
+ .hero-demo-status-leave-active,
+ .hero-demo-dot {
+ animation: none;
+ transition: none;
+ }
+}
+</style>
diff --git a/client/server/api/agent-drafts/claim.post.js b/client/server/api/agent-drafts/claim.post.js
new file mode 100644
index 000000000..c10b8083b
--- /dev/null
+++ b/client/server/api/agent-drafts/claim.post.js
@@ -0,0 +1,7 @@
+import { agentDraftApi } from '../../utils/agentDraftApi'
+
+export default defineEventHandler(async (event) => agentDraftApi(event, '/agent-drafts/editor/claim', {
+ method: 'POST',
+ body: await readBody(event),
+ includeAuth: true,
+}))
diff --git a/client/server/api/agent-drafts/current.get.js b/client/server/api/agent-drafts/current.get.js
new file mode 100644
index 000000000..11238db0a
--- /dev/null
+++ b/client/server/api/agent-drafts/current.get.js
@@ -0,0 +1,3 @@
+import { agentDraftApi } from '../../utils/agentDraftApi'
+
+export default defineEventHandler((event) => agentDraftApi(event, '/agent-drafts/editor/current'))
diff --git a/client/server/api/agent-drafts/current.put.js b/client/server/api/agent-drafts/current.put.js
new file mode 100644
index 000000000..ab989dbbd
--- /dev/null
+++ b/client/server/api/agent-drafts/current.put.js
@@ -0,0 +1,6 @@
+import { agentDraftApi } from '../../utils/agentDraftApi'
+
+export default defineEventHandler(async (event) => agentDraftApi(event, '/agent-drafts/editor/current', {
+ method: 'PUT',
+ body: await readBody(event),
+}))
diff --git a/client/server/api/agent-drafts/handoff.post.js b/client/server/api/agent-drafts/handoff.post.js
new file mode 100644
index 000000000..9da271030
--- /dev/null
+++ b/client/server/api/agent-drafts/handoff.post.js
@@ -0,0 +1,13 @@
+import { agentDraftApi, setAgentDraftSession } from '../../utils/agentDraftApi'
+
+export default defineEventHandler(async (event) => {
+ const body = await readBody(event)
+ const response = await agentDraftApi(event, '/agent-drafts/handoff/consume', {
+ method: 'POST',
+ body: { handoff_token: body?.handoff_token },
+ })
+
+ setAgentDraftSession(event, response.editor_session, response.draft.expires_at)
+
+ return { draft: response.draft }
+})
diff --git a/client/server/plugins/embeddable.js b/client/server/plugins/embeddable.js
index d2c1e4d3e..38dd570a0 100644
--- a/client/server/plugins/embeddable.js
+++ b/client/server/plugins/embeddable.js
@@ -17,7 +17,9 @@ export default defineNitroPlugin((nitroApp) => {
delete response.headers["X-Frame-Options"]
delete response.headers["x-frame-options"]
- if (routePath && !routePath.startsWith("/forms/")) {
+ const isEmbeddableRoute = routePath?.startsWith('/forms/') || routePath?.startsWith('/agent-drafts/preview')
+
+ if (routePath && !isEmbeddableRoute) {
// Build frame-ancestors for non-form routes: localhost variants + matching allowlisted domain (if Referer present)
// Note: CSP frame-ancestors doesn't support port wildcards, so we list common dev ports
const commonPorts = ['', ':3000', ':3001', ':4200', ':5000', ':5173', ':8000', ':8080', ':8081', ':9000']
@@ -46,7 +48,7 @@ export default defineNitroPlugin((nitroApp) => {
// Restrict embedding to localhost + (optionally) matched allowlisted domain
response.headers["Content-Security-Policy"] = `frame-ancestors ${ancestors.join(' ')};`
} else {
- // Forms: embeddable anywhere, omit CSP directive
+ // Public forms and short-lived signed agent previews are embeddable anywhere.
delete response.headers["Content-Security-Policy"]
}
diff --git a/client/server/utils/agentDraftApi.js b/client/server/utils/agentDraftApi.js
new file mode 100644
index 000000000..87806b1ab
--- /dev/null
+++ b/client/server/utils/agentDraftApi.js
@@ -0,0 +1,55 @@
+const SESSION_COOKIE = 'opnform_agent_draft_session'
+
+function apiHeaders(event, includeAuth = false) {
+ const config = useRuntimeConfig(event)
+ const headers = {
+ accept: 'application/json',
+ 'x-api-secret': config.apiSecret,
+ }
+ const session = getCookie(event, SESSION_COOKIE)
+ if (session) {
+ headers['x-agent-draft-session'] = session
+ }
+ if (includeAuth) {
+ const token = getCookie(event, 'opnform_token')
+ if (token) {
+ headers.authorization = `Bearer ${token}`
+ }
+ }
+ return headers
+}
+
+export async function agentDraftApi(event, path, options = {}) {
+ const config = useRuntimeConfig(event)
+ const apiBase = config.privateApiBase || config.public.apiBase
+ const { includeAuth = false, headers: optionHeaders, ...fetchOptions } = options
+
+ try {
+ return await $fetch(path, {
+ baseURL: apiBase,
+ ...fetchOptions,
+ headers: {
+ ...apiHeaders(event, includeAuth),
+ ...optionHeaders,
+ },
+ })
+ } catch (error) {
+ throw createError({
+ statusCode: error?.statusCode || error?.response?.status || 500,
+ statusMessage: error?.data?.message || error?.message || 'Agent draft request failed',
+ data: error?.data,
+ })
+ }
+}
+
+export function setAgentDraftSession(event, session, expiresAt) {
+ const requestUrl = getRequestURL(event)
+ const maxAge = Math.max(1, Math.floor((new Date(expiresAt).getTime() - Date.now()) / 1000))
+ setCookie(event, SESSION_COOKIE, session, {
+ httpOnly: true,
+ secure: requestUrl.protocol === 'https:',
+ sameSite: 'lax',
+ path: '/',
+ maxAge,
+ })
+}
diff --git a/client/sitemap.js b/client/sitemap.js
index e2a2a7077..f4cfc1faa 100644
--- a/client/sitemap.js
+++ b/client/sitemap.js
@@ -36,6 +36,11 @@ function getCloudMarketingUrls () {
if (isSelfHostedBuild) return []
return [
+ {
+ url: '/mcp',
+ changefreq: 'monthly',
+ priority: 0.9
+ },
{
url: '/self-hosted/license',
changefreq: 'monthly',
diff --git a/client/test/nuxt/mcp-settings.spec.ts b/client/test/nuxt/mcp-settings.spec.ts
new file mode 100644
index 000000000..1d03e3af2
--- /dev/null
+++ b/client/test/nuxt/mcp-settings.spec.ts
@@ -0,0 +1,188 @@
+import { flushPromises, mount } from '@vue/test-utils'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import McpSettings from '~/components/users/settings/Mcp.vue'
+
+const mocks = vi.hoisted(() => ({
+ status: vi.fn(),
+ update: vi.fn(),
+ success: vi.fn(),
+ error: vi.fn(),
+ copy: vi.fn(),
+}))
+
+vi.mock('~/api', () => ({
+ mcpApi: {
+ status: mocks.status,
+ update: mocks.update,
+ },
+}))
+
+vi.mock('~/composables/useAlert.js', () => ({
+ useAlert: () => ({
+ success: mocks.success,
+ error: mocks.error,
+ }),
+}))
+
+const readySettings = {
+ enabled: false,
+ available: false,
+ configured_value: null,
+ source: 'environment',
+ ready: true,
+ blockers: [],
+ server_url: 'https://forms.example.com/mcp',
+ settings_url: 'https://forms.example.com/?user-settings=mcp',
+ snippets: {
+ cursor: '{"mcpServers":{"opnform":{"url":"https://forms.example.com/mcp"}}}',
+ claude_code: "claude mcp add --transport http opnform 'https://forms.example.com/mcp'",
+ chatgpt: 'Server URL: https://forms.example.com/mcp\nAuthentication: OAuth',
+ codex: "codex mcp add opnform --url 'https://forms.example.com/mcp'",
+ other: '{"mcpServers":{"opnform":{"type":"http"}}}',
+ portable: '{"$schema":"https://agent-plugins.org"}',
+ },
+ install_urls: {
+ cursor: 'cursor://install-opnform',
+ },
+}
+
+function mountSettings() {
+ return mount(McpSettings, {
+ global: {
+ stubs: {
+ Icon: true,
+ UBadge: {
+ template: '<span><slot /></span>',
+ props: ['color', 'variant'],
+ },
+ UButton: {
+ template: '<button :disabled="disabled" @click="$emit(\'click\')">{{ label }}<slot /></button>',
+ props: ['color', 'disabled', 'icon', 'label', 'target', 'to', 'variant'],
+ emits: ['click'],
+ },
+ USkeleton: true,
+ USwitch: {
+ template: '<button data-testid="mcp-enabled-switch" :disabled="disabled" @click="$emit(\'update:modelValue\', !modelValue)" />',
+ props: ['disabled', 'modelValue'],
+ emits: ['update:modelValue'],
+ },
+ CopyContent: {
+ template: '<div data-testid="server-url">{{ content }}</div>',
+ props: ['content', 'label'],
+ },
+ McpCodeSnippet: {
+ template: '<div class="snippet"><slot name="selector" /><slot name="instructions" /><pre>{{ content }}</pre></div>',
+ props: ['content', 'label'],
+ emits: ['copy'],
+ },
+ },
+ },
+ })
+}
+
+describe('MCP self-hosted settings', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal('useAlert', () => ({
+ success: mocks.success,
+ error: mocks.error,
+ }))
+ vi.stubGlobal('useClipboard', () => ({ copy: mocks.copy }))
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
+ it('shows the generated connection details and enables MCP', async () => {
+ mocks.status.mockResolvedValue(readySettings)
+ mocks.update.mockResolvedValue({ ...readySettings, enabled: true, available: true, source: 'settings' })
+
+ const wrapper = mountSettings()
+ await flushPromises()
+
+ expect(wrapper.text()).toContain('Ready to connect')
+ expect(wrapper.find('[data-testid="mcp-connection-settings"]').exists()).toBe(false)
+ expect(wrapper.find('[data-testid="mcp-snippet-settings"]').exists()).toBe(false)
+
+ await wrapper.get('[data-testid="mcp-enabled-switch"]').trigger('click')
+ await flushPromises()
+
+ expect(mocks.update).toHaveBeenCalledWith(true)
+ expect(wrapper.text()).toContain('MCP is available')
+ expect(wrapper.text()).toContain('Connected AI assistants can create and manage forms')
+ expect(wrapper.text()).not.toContain('Guest draft creation')
+ expect(wrapper.get('[data-testid="server-url"]').text()).toBe('https://forms.example.com/mcp')
+ expect(wrapper.get('[data-testid="mcp-snippet-settings"]').text()).toContain(readySettings.snippets.codex)
+ expect(mocks.success).toHaveBeenCalledWith('MCP enabled for this instance.')
+
+ await wrapper.get('[data-testid="mcp-snippet-cursor"]').trigger('click')
+ expect(wrapper.get('[data-testid="mcp-snippet-settings"]').text()).toContain(readySettings.snippets.cursor)
+ expect(wrapper.get('[data-testid="mcp-snippet-settings"]').text()).not.toContain(readySettings.snippets.codex)
+ expect(wrapper.text()).toContain('Install in Cursor')
+
+ const copySettingsLink = wrapper.findAll('button').find(button => button.text().includes('Copy settings link'))
+ await copySettingsLink!.trigger('click')
+ expect(mocks.copy).toHaveBeenCalledWith('https://forms.example.com/?user-settings=mcp&agent=cursor')
+ expect(wrapper.get('[data-testid="mcp-portable-config"]').text()).toContain('Portable Agent Plugin configuration')
+ })
+
+ it('blocks activation and explains every missing prerequisite', async () => {
+ mocks.status.mockResolvedValue({
+ ...readySettings,
+ ready: false,
+ blockers: [
+ { code: 'passport_keys_missing', message: 'Passport keys are missing.' },
+ { code: 'front_url_invalid', message: 'FRONT_URL must use HTTPS.' },
+ ],
+ })
+
+ const wrapper = mountSettings()
+ await flushPromises()
+
+ expect(wrapper.get('[data-testid="mcp-enabled-switch"]').attributes('disabled')).toBeDefined()
+ expect(wrapper.get('[data-testid="mcp-readiness-blockers"]').text()).toContain('Passport keys are missing.')
+ expect(wrapper.get('[data-testid="mcp-readiness-blockers"]').text()).toContain('FRONT_URL must use HTTPS.')
+ expect(mocks.update).not.toHaveBeenCalled()
+ })
+
+ it('keeps connection details hidden when an enabled server is not operational', async () => {
+ mocks.status.mockResolvedValue({
+ ...readySettings,
+ enabled: true,
+ available: false,
+ ready: false,
+ blockers: [
+ { code: 'passport_keys_missing', message: 'Passport keys are missing.' },
+ ],
+ })
+
+ const wrapper = mountSettings()
+ await flushPromises()
+
+ expect(wrapper.text()).toContain('Server setup required')
+ expect(wrapper.text()).toContain('Unavailable')
+ expect(wrapper.find('[data-testid="mcp-connection-settings"]').exists()).toBe(false)
+ expect(wrapper.find('[data-testid="mcp-snippet-settings"]').exists()).toBe(false)
+ expect(wrapper.get('[data-testid="mcp-enabled-switch"]').attributes('disabled')).toBeUndefined()
+ })
+
+ it('offers a retry when the settings request fails', async () => {
+ mocks.status
+ .mockRejectedValueOnce({ data: { message: 'API unavailable' } })
+ .mockResolvedValueOnce(readySettings)
+
+ const wrapper = mountSettings()
+ await flushPromises()
+
+ expect(wrapper.get('[data-testid="mcp-load-error"]').text()).toContain('MCP settings could not be loaded')
+ expect(mocks.error).toHaveBeenCalledWith('API unavailable')
+
+ const retry = wrapper.findAll('button').find(button => button.text().includes('Retry'))
+ await retry!.trigger('click')
+ await flushPromises()
+
+ expect(mocks.status).toHaveBeenCalledTimes(2)
+ expect(wrapper.text()).toContain('Ready to connect')
+ })
+})
diff --git a/client/test/nuxt/user-settings-modal.spec.ts b/client/test/nuxt/user-settings-modal.spec.ts
new file mode 100644
index 000000000..792ca3927
--- /dev/null
+++ b/client/test/nuxt/user-settings-modal.spec.ts
@@ -0,0 +1,107 @@
+import { mount } from '@vue/test-utils'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ currentWorkspace: { id: 1, is_admin: false, is_readonly: false },
+ isSelfHosted: true,
+ workspaces: [] as Array<{ id: number, is_admin: boolean, is_readonly: boolean }>,
+}))
+
+vi.mock('#imports', async () => {
+ const vue = await import('vue')
+
+ return {
+ useAuth: () => ({
+ user: () => ({ data: vue.ref({}) }),
+ }),
+ useCurrentWorkspace: () => ({
+ current: vue.computed(() => mocks.currentWorkspace),
+ workspaces: vue.computed(() => mocks.workspaces),
+ }),
+ useFeatureFlag: (key: string) => key === 'self_hosted' && mocks.isSelfHosted,
+ }
+})
+
+vi.mock('~/composables/query/useAuth.js', async () => {
+ const vue = await import('vue')
+
+ return {
+ useAuth: () => ({
+ user: () => ({ data: vue.ref({}) }),
+ }),
+ }
+})
+
+vi.mock('~/composables/query/useCurrentWorkspace.js', async () => {
+ const vue = await import('vue')
+
+ return {
+ useCurrentWorkspace: () => ({
+ current: vue.computed(() => mocks.currentWorkspace),
+ workspaces: vue.computed(() => mocks.workspaces),
+ }),
+ }
+})
+
+vi.mock('~/composables/useFeatureFlag.js', () => ({
+ useFeatureFlag: (key: string) => key === 'self_hosted' && mocks.isSelfHosted,
+}))
+
+import UserSettingsModal from '~/components/users/settings/Modal.vue'
+
+function mountModal() {
+ return mount(UserSettingsModal, {
+ props: {
+ activeTab: 'mcp',
+ },
+ global: {
+ stubs: {
+ SettingsModal: {
+ template: '<div><slot /></div>',
+ props: ['modelValue', 'activeTab'],
+ emits: ['close', 'update:modelValue', 'update:activeTab'],
+ },
+ SettingsModalPage: {
+ template: '<section :data-page-id="id" />',
+ props: ['icon', 'id', 'label'],
+ },
+ LazyUsersSettingsAccessTokens: true,
+ LazyUsersSettingsAccount: true,
+ LazyUsersSettingsBilling: true,
+ LazyUsersSettingsConnections: true,
+ LazyUsersSettingsLicense: true,
+ LazyUsersSettingsMcp: true,
+ LazyUsersSettingsSecurity: true,
+ },
+ },
+ })
+}
+
+describe('User settings instance administration', () => {
+ beforeEach(() => {
+ mocks.currentWorkspace = { id: 1, is_admin: false, is_readonly: false }
+ mocks.isSelfHosted = true
+ mocks.workspaces = []
+ })
+
+ it('shows instance settings when the user administers another workspace', () => {
+ mocks.workspaces = [
+ mocks.currentWorkspace,
+ { id: 2, is_admin: true, is_readonly: false },
+ ]
+
+ const wrapper = mountModal()
+
+ expect(wrapper.find('[data-page-id="license"]').exists()).toBe(true)
+ expect(wrapper.find('[data-page-id="mcp"]').exists()).toBe(true)
+ })
+
+ it('hides instance settings when the user administers no workspace', () => {
+ mocks.workspaces = [mocks.currentWorkspace]
+
+ const wrapper = mountModal()
+
+ expect(wrapper.find('[data-page-id="license"]').exists()).toBe(false)
+ expect(wrapper.find('[data-page-id="mcp"]').exists()).toBe(false)
+ })
+})
diff --git a/client/test/unit/agent-draft-autosave.test.ts b/client/test/unit/agent-draft-autosave.test.ts
new file mode 100644
index 000000000..2f7cf20f3
--- /dev/null
+++ b/client/test/unit/agent-draft-autosave.test.ts
@@ -0,0 +1,33 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createAgentDraftAutosave } from '../../lib/forms/agent-draft-autosave.js'
+
+describe('agent draft autosave', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('runs a scheduled save after the debounce', async () => {
+ vi.useFakeTimers()
+ const sync = vi.fn().mockResolvedValue(undefined)
+ const autosave = createAgentDraftAutosave(sync, 900)
+
+ autosave.schedule()
+ await vi.advanceTimersByTimeAsync(900)
+
+ expect(sync).toHaveBeenCalledOnce()
+ expect(sync).toHaveBeenCalledWith({ keepalive: false })
+ })
+
+ it('flushes a pending save with keepalive and cancels the debounce', async () => {
+ vi.useFakeTimers()
+ const sync = vi.fn().mockResolvedValue(undefined)
+ const autosave = createAgentDraftAutosave(sync, 900)
+
+ autosave.schedule()
+ await autosave.flush()
+ await vi.advanceTimersByTimeAsync(900)
+
+ expect(sync).toHaveBeenCalledOnce()
+ expect(sync).toHaveBeenCalledWith({ keepalive: true })
+ })
+})
diff --git a/client/test/unit/agent-draft-errors.test.ts b/client/test/unit/agent-draft-errors.test.ts
new file mode 100644
index 000000000..0633e265b
--- /dev/null
+++ b/client/test/unit/agent-draft-errors.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest'
+import { isAgentDraftVersionConflict } from '../../lib/forms/agent-draft-errors.js'
+
+describe('isAgentDraftVersionConflict', () => {
+ it('recognizes an expected version validation error', () => {
+ expect(isAgentDraftVersionConflict({
+ statusCode: 422,
+ data: {
+ errors: {
+ expected_version: ['Draft version conflict.'],
+ },
+ },
+ })).toBe(true)
+ })
+
+ it('does not treat definition validation errors as version conflicts', () => {
+ expect(isAgentDraftVersionConflict({
+ statusCode: 422,
+ data: {
+ errors: {
+ 'definition.properties.0.select.options': ['At least one option is required.'],
+ },
+ },
+ })).toBe(false)
+ })
+
+ it('does not treat non-validation failures as version conflicts', () => {
+ expect(isAgentDraftVersionConflict({
+ statusCode: 500,
+ data: {
+ errors: {
+ expected_version: ['Unexpected error.'],
+ },
+ },
+ })).toBe(false)
+ })
+})
diff --git a/client/test/unit/agent-draft-session.test.ts b/client/test/unit/agent-draft-session.test.ts
new file mode 100644
index 000000000..8392d5cee
--- /dev/null
+++ b/client/test/unit/agent-draft-session.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest'
+import { getAgentDraftSessionRequest } from '../../lib/forms/agent-draft-session'
+
+describe('agent draft editor session requests', () => {
+ it('consumes a handoff capability from the URL fragment', () => {
+ expect(getAgentDraftSessionRequest('#handoff=secret-capability')).toEqual({
+ url: '/api/agent-drafts/handoff',
+ options: {
+ method: 'POST',
+ body: { handoff_token: 'secret-capability' },
+ },
+ consumesHandoff: true,
+ })
+ })
+
+ it('restores the existing cookie session after a refresh', () => {
+ expect(getAgentDraftSessionRequest()).toEqual({
+ url: '/api/agent-drafts/current',
+ options: undefined,
+ consumesHandoff: false,
+ })
+ })
+})
diff --git a/docker/php-fpm-entrypoint b/docker/php-fpm-entrypoint
index 84f41c94b..3989032e8 100644
--- a/docker/php-fpm-entrypoint
+++ b/docker/php-fpm-entrypoint
@@ -28,6 +28,7 @@ main() {
echo "Running setup for API role..."
apply_db_migrations
initialize_instance
+ initialize_mcp_oauth_keys
optimize_application
echo "Starting server for API role with command: $@"
exec "$@"
@@ -130,6 +131,34 @@ initialize_instance() {
php ./artisan telemetry:initialize-instance
}
+initialize_mcp_oauth_keys() {
+ if [ -n "${PASSPORT_PRIVATE_KEY:-}" ] && [ -n "${PASSPORT_PUBLIC_KEY:-}" ]; then
+ echo "Using Passport keys from the environment"
+ return 0
+ fi
+
+ if [ -n "${PASSPORT_PRIVATE_KEY:-}" ] || [ -n "${PASSPORT_PUBLIC_KEY:-}" ]; then
+ echo "PASSPORT_PRIVATE_KEY and PASSPORT_PUBLIC_KEY must be configured together" >&2
+ exit 1
+ fi
+
+ if [ -f ./storage/oauth-private.key ] && [ -f ./storage/oauth-public.key ]; then
+ echo "Reusing Passport keys from storage"
+ return 0
+ fi
+
+ if [ -f ./storage/oauth-private.key ] || [ -f ./storage/oauth-public.key ]; then
+ echo "Incomplete Passport key pair in storage" >&2
+ exit 1
+ fi
+
+ echo "Generating Passport keys for MCP OAuth"
+ php ./artisan passport:keys --force
+ chown www-data:www-data ./storage/oauth-private.key ./storage/oauth-public.key
+ chmod 600 ./storage/oauth-private.key
+ chmod 644 ./storage/oauth-public.key
+}
+
optimize_application() {
echo "Clearing application cache"
php ./artisan optimize:clear
@@ -138,4 +167,4 @@ optimize_application() {
php ./artisan optimize
}
-main "$@"
\ No newline at end of file
+main "$@"
diff --git a/docs/configuration/environment-variables.mdx b/docs/configuration/environment-variables.mdx
index 0df747661..fb21f862f 100644
--- a/docs/configuration/environment-variables.mdx
+++ b/docs/configuration/environment-variables.mdx
@@ -68,6 +68,9 @@ There are dedicated configuration pages available for more detailed setup instru
| `JWT_TTL` | Time to live for JSON Web Tokens (JWT). |
| `JWT_SECRET` | Secret key used to sign JWTs. |
| `JWT_SKIP_IP_UA_VALIDATION` | Set to `true` to disable JWT User Agent validation (defaults to `false`). Keep this disabled in production and Docker deployments. For local Docker development, `docker-compose.dev.yml` sets this to `true` automatically. |
+| `OAUTH_ENABLED` | Enables the delegated OAuth 2.1 infrastructure. Defaults to `true`; set it to `false` only when you need to disable OAuth routes independently of the MCP setting. |
+| `OAUTH_ACCESS_TOKEN_TTL` | Passport access token lifetime in minutes. Defaults to `10080` (7 days) and does not change the first-party JWT lifetime. |
+| `OAUTH_REFRESH_TOKEN_TTL_DAYS` | Passport refresh token lifetime in days. Defaults to `30`. |
| `PUBLIC_UPLOADS_RATE_LIMIT_PER_MINUTE` | Maximum public upload requests allowed per client IP or authenticated user per route each minute. Defaults to `30`. |
| `PUBLIC_UPLOADS_RATE_LIMIT_PER_HOUR` | Maximum public upload requests allowed per client IP or authenticated user per route each hour. Defaults to `300`. |
| `OIDC_FORCE_LOGIN` | When set to `true`, password-based authentication is disabled and users must authenticate via OIDC SSO. See [Force Login Mode](../configuration/oidc-sso#7-force-login-mode) for details. |
@@ -171,6 +174,23 @@ This data will only be used by OpnForm team for:
Set `OPNFORM_ANONYMOUS_TELEMETRY_DISABLED=true` in your environment variables to disable data collection.
+### MCP and AI agents
+
+MCP is disabled by default on self-hosted instances. Enable it from **Settings → MCP & AI agents** after configuring public HTTPS origins and Laravel Passport. Form and submission tools require OAuth. See the [MCP integration guide](../integrations/mcp) for the complete setup.
+
+| Variable Name | Default | Description |
+| --- | --- | --- |
+| `MCP_ENABLED` | `false` | Default MCP state for self-hosted instances. Set it in `api/.env`, the API service `environment` block in Docker Compose, or the API container environment. A value saved in **Settings → MCP & AI agents** overrides it. |
+| `MCP_OBSERVABILITY_ENABLED` | `true` | Records metadata-only MCP usage events and structured logs. No arguments, tokens, form content, or submission values are recorded. |
+| `MCP_RATE_LIMIT_PER_MINUTE` | `120` | MCP requests allowed per minute per OAuth user or unauthenticated client IP. |
+| `MCP_RATE_LIMIT_PER_HOUR` | `3000` | MCP requests allowed per hour per OAuth user or unauthenticated client IP. |
+| `MCP_SUBMISSION_EXPORTS_PER_MINUTE` | `5` | Submission exports allowed per minute per user and form. |
+| `MCP_SUBMISSION_EXPORTS_PER_HOUR` | `30` | Submission exports allowed per hour per user and form. |
+| `FORM_SUMMARY_RATE_LIMIT_PER_MINUTE` | `30` | REST and MCP submission summary requests allowed per minute in one shared per-user bucket. |
+| `MCP_OAUTH_REDIRECT_DOMAINS` | See `.env.example` | Comma-separated HTTPS or loopback callback origins accepted during dynamic client registration. |
+| `MCP_OAUTH_CUSTOM_SCHEMES` | `chatgpt,claude,cursor,vscode` | Comma-separated callback URI schemes accepted for trusted native clients. |
+| `MCP_AUTHORIZATION_SERVER` | Application URL | Optional external OAuth authorization-server URL advertised by MCP discovery. |
+
## Front-end Environment Variables
| Variable Name | Description |
diff --git a/docs/contributing/authentication-architecture.mdx b/docs/contributing/authentication-architecture.mdx
new file mode 100644
index 000000000..1b63a4711
--- /dev/null
+++ b/docs/contributing/authentication-architecture.mdx
@@ -0,0 +1,56 @@
+---
+title: Authentication architecture
+description: Understand when OpnForm uses JWT, Sanctum personal access tokens, and Passport OAuth 2.1.
+---
+
+OpnForm intentionally uses three authentication mechanisms. They serve different clients and should not be substituted for one another without a dedicated migration.
+
+| Mechanism | Client | Purpose |
+| --- | --- | --- |
+| JWT | First-party Nuxt application | Existing browser login and authenticated application requests |
+| Sanctum personal access tokens | API users and integrations | Long-lived tokens created by a user, constrained by token abilities and the `auth.multi` route policy |
+| Passport OAuth 2.1 | Third-party delegated clients | Authorization Code with PKCE, consent, scoped access, and refresh tokens |
+
+<Warning>
+Do not migrate first-party login to Passport. Passport is for delegated access by external clients. A future first-party authentication migration should evaluate Sanctum's stateful cookie authentication as a separate project.
+</Warning>
+
+## Delegated OAuth flow
+
+The `OAuthServiceProvider` owns Passport configuration, routes, token lifetimes, consent rendering, and scope descriptions. MCP adds its own dynamic client registration policy, login bridge, metadata, and `mcp:use` scope requirement on top of that generic layer.
+
+1. The client dynamically registers an allowed redirect URI for the MCP integration.
+2. The authorization request must use Authorization Code with PKCE and the `S256` challenge method.
+3. OpnForm authenticates the account through the existing first-party login flow.
+4. The generic consent screen displays the callback destination and every requested scope description.
+5. Passport issues a scoped access token and refresh token.
+6. The MCP endpoint accepts the token only when it includes `mcp:use` and the account is not blocked.
+
+Guest MCP requests remain available without a bearer token. A bearer token that is invalid or missing the required scope is rejected rather than treated as a guest request.
+
+## Configuration
+
+```dotenv
+# Optional override. The default follows Cloud or self-hosted MCP availability.
+OAUTH_ENABLED=true
+
+# Seven days, in minutes.
+OAUTH_ACCESS_TOKEN_TTL=10080
+
+# Refresh tokens remain valid for 30 days.
+OAUTH_REFRESH_TOKEN_TTL_DAYS=30
+```
+
+These values are independent of `JWT_TTL`. Changing a delegated OAuth token lifetime must not change first-party sessions.
+
+## Adding another delegated client
+
+When you add another OAuth consumer:
+
+1. Add a narrowly defined scope and a user-readable description to `config/oauth.php`.
+2. Keep redirect URI validation specific to the client registration endpoint.
+3. Require PKCE `S256` for public clients.
+4. Enforce the scope at the protected resource boundary.
+5. Add consent, token, insufficient-scope, account-blocking, and revocation tests.
+
+Do not add product-specific permissions directly to the generic OAuth consent template. The template renders the scopes requested and validated by Passport.
diff --git a/docs/docs.json b/docs/docs.json
index 1eb801d1d..d5ace6199 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -69,6 +69,12 @@
"embedding/javascript-sdk",
"embedding/editor-embed"
]
+ },
+ {
+ "group": "Integrations",
+ "pages": [
+ "integrations/mcp"
+ ]
}
]
},
@@ -156,6 +162,7 @@
"group": "Contributing",
"pages": [
"contributing/getting-started",
+ "contributing/authentication-architecture",
"contributing/new-form-block",
"contributing/new-integration"
]
diff --git a/docs/integrations/mcp.mdx b/docs/integrations/mcp.mdx
new file mode 100644
index 000000000..d147e98e4
--- /dev/null
+++ b/docs/integrations/mcp.mdx
@@ -0,0 +1,202 @@
+---
+title: "Connect AI assistants with MCP"
+description: "Enable the OpnForm MCP server on a self-hosted instance and connect Cursor, Claude Code, ChatGPT, Codex, or another MCP client."
+---
+
+OpnForm includes a remote [Model Context Protocol](https://modelcontextprotocol.io) server. It lets AI assistants create and manage forms, then search, analyze, and export submissions using the permissions of the connected OpnForm account.
+
+Your MCP endpoint uses your API origin:
+
+```text
+https://forms.example.com/mcp
+```
+
+MCP is disabled by default. A workspace administrator must verify the instance configuration and enable it from OpnForm settings.
+
+## Prerequisites
+
+Before you enable MCP, verify that your instance has:
+
+- public HTTPS values for `APP_URL` and `FRONT_URL`;
+- a valid Laravel Passport key pair;
+- persistent storage for the Passport keys so existing OAuth connections survive container replacement;
+- a trusted MCP client that supports remote streamable HTTP servers and OAuth.
+
+<Warning>
+Do not expose a production MCP endpoint over plain HTTP. Localhost URLs are suitable only for local client testing.
+</Warning>
+
+## Enable MCP
+
+<Steps>
+<Step title="Open the MCP settings">
+Sign in as a workspace administrator, then open **Settings → MCP & AI agents**.
+</Step>
+
+<Step title="Resolve the setup checks">
+OpnForm verifies the public URLs and Passport keys. If a requirement is missing, the page identifies what you need to configure before activation.
+</Step>
+
+<Step title="Enable the server">
+Turn on **Enable MCP**. The connection URL and client-specific setup instructions appear immediately.
+
+<Check>
+The status changes to **MCP is available** and the page displays your `/mcp` endpoint.
+</Check>
+</Step>
+</Steps>
+
+The switch is stored in the OpnForm database and applies without restarting the application. Until an administrator changes it, OpnForm uses `MCP_ENABLED` from the API environment as the default:
+
+```dotenv
+MCP_ENABLED=false
+MCP_OBSERVABILITY_ENABLED=true
+```
+
+## Connect an AI assistant
+
+The settings page generates the correct command or configuration for your instance. Select a client, then copy the displayed value.
+
+<Tabs>
+<Tab title="Cursor">
+Use **Install in Cursor** for one-click setup, or copy the generated `mcpServers` JSON configuration.
+</Tab>
+
+<Tab title="Claude Code">
+Run the generated command:
+
+```bash
+claude mcp add --transport http opnform https://forms.example.com/mcp
+```
+</Tab>
+
+<Tab title="ChatGPT">
+On a plan that supports custom MCP apps, enable [ChatGPT developer mode](https://help.openai.com/en/articles/12584461-developer-mode-and-full-mcp-connectors-in-chatgpt), create an app, and paste your server URL. Select OAuth when prompted. ChatGPT discovers the authorization metadata from the endpoint.
+
+<Note>
+ChatGPT plan and workspace controls determine whether custom apps and write actions are available. An administrator may need to enable developer mode before you can add the server.
+</Note>
+</Tab>
+
+<Tab title="Codex">
+Run the generated command:
+
+```bash
+codex mcp add opnform --url https://forms.example.com/mcp
+```
+</Tab>
+
+<Tab title="Other clients">
+Use the generated streamable HTTP configuration in any OAuth-capable MCP client:
+
+```json
+{
+ "mcpServers": {
+ "opnform": {
+ "type": "http",
+ "url": "https://forms.example.com/mcp"
+ }
+ }
+}
+```
+</Tab>
+</Tabs>
+
+Open the advanced section on the settings page if you need the portable [Agent Plugins](https://agent-plugins.org) configuration.
+
+To share instructions for a particular client, include the selected client in the settings URL:
+
+```text
+https://forms.example.com/?user-settings=mcp&agent=cursor
+```
+
+Supported values are `cursor`, `claude_code`, `chatgpt`, `codex`, and `other`.
+
+## Authenticate the connection
+
+Form, workspace, and submission tools always require OAuth. The MCP client discovers OpnForm's authorization metadata, opens the OpnForm consent screen, and uses authorization code flow with PKCE `S256`. You never paste an OpnForm password or access token into a conversation.
+
+The schema resources, field catalog, and `validate_form_definition` tool remain available before authentication because they do not read or store instance data.
+
+<Note>
+After authenticating a local Codex connection, start a new conversation with OpnForm selected so the MCP client loads the stored credential.
+</Note>
+
+A connected user can revoke the current access and refresh tokens by sending an authenticated `DELETE` request to `/mcp-oauth/session`.
+
+## Available capabilities
+
+After OAuth, an assistant can:
+
+- list accessible workspaces;
+- list and inspect forms;
+- create a form as an unpublished draft in a writable workspace;
+- return an `edit_url` so you can review the draft in the OpnForm editor;
+- update, publish, and move forms to the trash;
+- list, search, filter, inspect, summarize, and export submissions.
+
+Workspace administration and submission mutations are unavailable. Publishing and moving a form to the trash require explicit confirmation. MCP does not expose permanent form deletion, form restoration, submission deletion, or submission restoration.
+
+Normal workspace permissions and plan limits continue to apply. If saving a form disables unavailable premium features, the tool response lists those changes.
+
+## OAuth and callback configuration
+
+Configure the callback destinations accepted by your instance:
+
+| Variable | Purpose |
+| --- | --- |
+| `MCP_OAUTH_REDIRECT_DOMAINS` | Comma-separated HTTPS or loopback callback origins accepted during dynamic client registration. |
+| `MCP_OAUTH_CUSTOM_SCHEMES` | Comma-separated callback URI schemes accepted for trusted native clients. |
+| `MCP_AUTHORIZATION_SERVER` | Optional external authorization-server URL advertised by MCP discovery. |
+
+The consent screen displays the callback destination before approval.
+
+OAuth authorization requests and login tickets use atomic cache locks. If you run multiple application instances, configure Laravel's default cache as a shared, lock-capable store such as Redis or DynamoDB. File and array cache drivers are suitable only for single-instance development.
+
+## Rate limits
+
+The default limits are permissive for normal agent use:
+
+| Variable | Default | Scope |
+| --- | ---: | --- |
+| `MCP_RATE_LIMIT_PER_MINUTE` | `120` | All MCP requests, per OAuth user or unauthenticated client IP |
+| `MCP_RATE_LIMIT_PER_HOUR` | `3000` | All MCP requests, per OAuth user or unauthenticated client IP |
+| `MCP_SUBMISSION_EXPORTS_PER_MINUTE` | `5` | Exports, per user and form |
+| `MCP_SUBMISSION_EXPORTS_PER_HOUR` | `30` | Exports, per user and form |
+| `FORM_SUMMARY_RATE_LIMIT_PER_MINUTE` | `30` | REST and MCP submission summaries, shared per user |
+
+## Privacy and observability
+
+When `MCP_OBSERVABILITY_ENABLED=true`, OpnForm records only the MCP method, tool name, authentication mode, outcome, HTTP status, and duration.
+
+OpnForm does not include request arguments, OAuth tokens, form definitions, submission values, export URLs, user identifiers, or IP addresses in MCP telemetry or structured MCP request logs.
+
+Set `MCP_OBSERVABILITY_ENABLED=false` to disable MCP usage events and their structured logs. General anonymous instance telemetry remains controlled by `OPNFORM_ANONYMOUS_TELEMETRY_DISABLED`.
+
+## Troubleshooting
+
+<AccordionGroup>
+<Accordion title="The Enable MCP switch is unavailable">
+Verify that `APP_URL` and `FRONT_URL` use public HTTPS origins and that the API container can read a persistent Passport key pair. Reload the settings page after correcting the configuration.
+</Accordion>
+
+<Accordion title="The client connects but account tools require authentication">
+Enabling MCP only exposes the server. Complete the OAuth flow from the MCP client. For local Codex testing, start a new conversation after authentication.
+</Accordion>
+
+<Accordion title="OAuth returns to the wrong host">
+Check the client callback against `MCP_OAUTH_REDIRECT_DOMAINS` and `MCP_OAUTH_CUSTOM_SCHEMES`. Also verify that `APP_URL`, `FRONT_URL`, and reverse-proxy forwarding headers reflect the public origins.
+</Accordion>
+
+<Accordion title="The client cannot reach the MCP server">
+Confirm that `https://forms.example.com/mcp` is reachable from outside your private network, that your reverse proxy allows streamable HTTP responses, and that no firewall or authentication proxy blocks MCP discovery requests.
+</Accordion>
+</AccordionGroup>
+
+## Agent safety behavior
+
+- Fetch the current form revision before updating, publishing, or trashing it.
+- Re-fetch and reconcile the form after a revision conflict.
+- Ask before publishing or moving a form to the trash.
+- Use submission data only when it is necessary for the user's request.
+- Respect validation, workspace permissions, plan cleaning, and rate limits.
diff --git a/plugins/opnform/.codex-plugin/plugin.json b/plugins/opnform/.codex-plugin/plugin.json
new file mode 100644
index 000000000..9c3e155f7
--- /dev/null
+++ b/plugins/opnform/.codex-plugin/plugin.json
@@ -0,0 +1,44 @@
+{
+ "name": "opnform",
+ "version": "1.0.0",
+ "description": "Build private form drafts without signing in, then connect OpnForm to manage forms and read submissions.",
+ "author": {
+ "name": "OpnForm",
+ "url": "https://opnform.com"
+ },
+ "homepage": "https://docs.opnform.com/integrations/mcp",
+ "repository": "https://github.com/OpnForm/OpnForm",
+ "license": "AGPL-3.0-or-later",
+ "keywords": [
+ "forms",
+ "mcp",
+ "agent",
+ "submissions",
+ "no-code"
+ ],
+ "skills": "./skills/",
+ "mcpServers": "./.mcp.json",
+ "interface": {
+ "displayName": "OpnForm",
+ "shortDescription": "Build and manage forms with your AI assistant",
+ "longDescription": "Create and preview private form drafts without an account. Connect OpnForm only when you need to save, publish, manage existing forms, or search and export submissions.",
+ "developerName": "OpnForm",
+ "category": "Productivity",
+ "capabilities": [
+ "Interactive previews",
+ "Form creation and management",
+ "Read-only submission access"
+ ],
+ "websiteURL": "https://opnform.com",
+ "privacyPolicyURL": "https://opnform.com/privacy-policy",
+ "termsOfServiceURL": "https://opnform.com/terms-conditions",
+ "defaultPrompt": [
+ "Create a contact form for my business and show me a preview.",
+ "Find recent submissions containing a specific email address.",
+ "Update my form, then ask me before publishing it."
+ ],
+ "brandColor": "#2563EB",
+ "composerIcon": "./assets/logo.svg",
+ "logo": "./assets/logo.svg"
+ }
+}
diff --git a/plugins/opnform/.mcp.json b/plugins/opnform/.mcp.json
new file mode 100644
index 000000000..824d1ed91
--- /dev/null
+++ b/plugins/opnform/.mcp.json
@@ -0,0 +1,9 @@
+{
+ "mcpServers": {
+ "opnform": {
+ "type": "http",
+ "url": "https://api.opnform.com/mcp",
+ "auth": "oauth"
+ }
+ }
+}
diff --git a/plugins/opnform/README.md b/plugins/opnform/README.md
new file mode 100644
index 000000000..36781a7ff
--- /dev/null
+++ b/plugins/opnform/README.md
@@ -0,0 +1,27 @@
+# OpnForm agent plugin
+
+This directory is the installable OpnForm plugin package. It contains both the portable Agent Plugins 1.0 manifests and the native OpenAI wrapper.
+
+## Package formats
+
+- `plugin.json`, `mcp.json`, and `skills/opnform/SKILL.md` are the portable [agent-plugins.org](https://agent-plugins.org) package.
+- `.codex-plugin/plugin.json` and `.mcp.json` let Codex load the hosted OpnForm MCP server directly.
+
+Both integrations use `https://api.opnform.com/mcp`. They contain no credentials or environment-specific endpoint.
+
+## Remaining ChatGPT publication step
+
+ChatGPT public distribution uses a registered MCP connection rather than the direct Codex MCP declaration. Before submitting the plugin to the public directory:
+
+1. Enable Developer mode in ChatGPT.
+2. Register `https://api.opnform.com/mcp` from the ChatGPT Plugins page.
+3. Copy the technical app ID that ChatGPT creates.
+4. Add `.app.json` with that real registered app mapping.
+5. Add `"apps": "./.app.json"` to `.codex-plugin/plugin.json`.
+6. Re-run the package validators and test the installed plugin in a new conversation.
+
+Do not add `.app.json` before the real registered app ID is available. A fabricated identifier makes the package look publishable while leaving the ChatGPT integration unusable.
+
+## Local installation
+
+Use a personal or temporary marketplace outside this repository. A local marketplace entry should point to a copy of this directory, then install `opnform` from that marketplace and test it in a new conversation. Do not commit a repository marketplace file.
diff --git a/plugins/opnform/assets/logo.svg b/plugins/opnform/assets/logo.svg
new file mode 100644
index 000000000..00a0be906
--- /dev/null
+++ b/plugins/opnform/assets/logo.svg
@@ -0,0 +1,7 @@
+<svg fill="none" height="120" viewBox="0 0 120 120" width="120" xmlns="http://www.w3.org/2000/svg">
+ <linearGradient id="opnform-gradient" gradientUnits="userSpaceOnUse" x1="60" x2="60" y1="2" y2="118.352">
+ <stop offset="0" stop-color="#2563eb"/>
+ <stop offset="1" stop-color="#60a5fa"/>
+ </linearGradient>
+ <path clip-rule="evenodd" d="m80.6502 118.352c22.9638-8.418 39.3498-30.4712 39.3498-56.352 0-33.1371-26.8629-60-60-60s-60 26.8629-60 60c0 25.8808 16.3862 47.934 39.3498 56.352l16.631-38.9411c-7.4746-1.9924-12.9808-8.8086-12.9808-16.9109 0-9.665 7.835-17.5 17.5-17.5s17.5 7.835 17.5 17.5c0 8.4269-5.9563 15.4627-13.8885 17.1269z" fill="url(#opnform-gradient)" fill-rule="evenodd"/>
+</svg>
diff --git a/plugins/opnform/mcp.json b/plugins/opnform/mcp.json
new file mode 100644
index 000000000..e825e2afa
--- /dev/null
+++ b/plugins/opnform/mcp.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
+ "mcpServers": {
+ "opnform": {
+ "type": "streamable-http",
+ "url": "https://api.opnform.com/mcp"
+ }
+ }
+}
diff --git a/plugins/opnform/plugin.json b/plugins/opnform/plugin.json
new file mode 100644
index 000000000..b16a0a705
--- /dev/null
+++ b/plugins/opnform/plugin.json
@@ -0,0 +1,20 @@
+{
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
+ "name": "opnform",
+ "version": "1.0.0",
+ "description": "Create, preview, and manage OpnForm forms and read their submissions with an AI agent.",
+ "author": {
+ "name": "OpnForm",
+ "url": "https://opnform.com"
+ },
+ "homepage": "https://docs.opnform.com/integrations/mcp",
+ "repository": "https://github.com/OpnForm/OpnForm",
+ "license": "AGPL-3.0-or-later",
+ "keywords": [
+ "forms",
+ "mcp",
+ "agent",
+ "submissions",
+ "no-code"
+ ]
+}
diff --git a/plugins/opnform/skills/opnform/SKILL.md b/plugins/opnform/skills/opnform/SKILL.md
new file mode 100644
index 000000000..73ab52e8b
--- /dev/null
+++ b/plugins/opnform/skills/opnform/SKILL.md
@@ -0,0 +1,68 @@
+---
+name: opnform
+description: Use this when a user asks to create, preview, revise, claim, or manage an OpnForm form through MCP, or to search, inspect, analyze, or export OpnForm submissions.
+---
+
+# OpnForm
+
+Use the OpnForm MCP server for OpnForm operations. Start as a guest when the user only needs a new form and an interactive preview. Connect an account only when account or workspace data is required.
+
+## Require native MCP access
+
+- Use only the OpnForm MCP tools and resources exposed by the current host session.
+- Never launch another Codex or ChatGPT agent, run `codex exec`, call OpnForm through shell commands or raw HTTP, inspect a repository or plugin cache for live product data, or switch to another OpnForm connector as a fallback.
+- If the required OpnForm tools or resources are absent, stop. Explain that OpnForm is not attached to the current conversation and ask the user to start a new conversation with the OpnForm plugin selected before sending the first message. Do not attempt login, installation, or discovery through another route.
+- Distinguish missing tools from missing authentication. Missing tools require a correctly attached plugin; an OAuth challenge from an available account tool means the OpnForm MCP server itself is not authenticated.
+- Enabling or selecting the plugin is not OAuth authentication. In local Codex, tell the user to open **Settings → MCP servers → OpnForm → Authenticate** (or run `codex mcp login opnform` themselves). After OAuth completes, start a new conversation with OpnForm selected before the first message so Codex creates the MCP client with the stored credential. Existing local conversations can remain attached to their original guest client and may not hot-reload OAuth credentials. In hosted ChatGPT, use the connection flow presented by the host and retry in the same conversation only if the host supports it.
+- If the tool still returns the OAuth challenge afterward, do not loop or claim the connection succeeded. In local Codex, first verify the OpnForm MCP server is authenticated, then move the request to a new conversation. If a fresh conversation still challenges, explain that no bearer credential reached the MCP server and ask the user to verify the server's authentication status.
+
+## Build and revise a guest draft
+
+1. Read `opnform://schemas/agent-form-definition/v1` and `opnform://reference/form-fields/v1` before generating a definition. Re-read the field reference before changing presentation style, fields, layout, or media later in the conversation. Do not inspect the OpnForm source tree or guess product behavior when the MCP resources describe it.
+2. Call `validate_form_definition`. Resolve every validation error before creating or saving a draft.
+3. Call `create_form_draft` with the validated definition.
+4. Keep the returned `draft_token` private. It is a capability secret: never quote it to the user, write it to a file, log it, or send it to another service.
+5. Call `preview_form_draft` and present its interactive MCP preview when the host supports it.
+6. Apply requested changes with `patch_form_draft`, passing the latest `expected_version`. Validate the changed definition before persistence when needed.
+7. If the version conflicts or the current state is uncertain, call `get_form_draft`, reconcile the user's requested changes, validate again, and retry with the new version. Never overwrite blindly.
+8. Offer to open the draft in OpnForm. Use the `editor_url` returned by the preview or call `open_form_draft_in_editor`. The handoff URL is reusable until the seven-day guest draft expires; generating another URL does not revoke earlier ones.
+
+The browser editor keeps the guest draft available through an HttpOnly session. The user can preview and edit before signing in. Authentication and workspace selection happen only when the user chooses to save the draft into an OpnForm account.
+
+## Presentation and media
+
+- `classic` is a continuous form. Use widths for columns and `nf-page-break` only when the user wants explicit pagination.
+- `focused` is a Typeform-like flow: every visible block becomes one step automatically. Use full-width input blocks and concise `nf-text` intro steps. Remove `nf-page-break` and do not add standalone `nf-image`, `nf-divider`, `nf-code`, `nf-video`, or `nf-audio` blocks.
+- To illustrate a focused step, add an `image` object to that input or `nf-text` block. Follow the layouts and media schema in `opnform://reference/form-fields/v1`; do not confuse this with the standalone `nf-image.image_block` shape.
+- Use only user-provided or durable public HTTPS image URLs. Never persist localhost, private addresses, temporary tunnel domains, expiring signed URLs, or asset paths found by reading the OpnForm repository.
+- Preserve the existing language, copy, field IDs, and unrelated settings unless the user asks to change them. For a focused conversion, usually set `settings.auto_next`, `settings.navigation_arrows`, and the localized `translations.focused_next_button_text` deliberately.
+
+## Work with an authenticated account
+
+Authenticated tools remain discoverable before the account is connected. When the user asks for account, form, or submission data, call `get_account_context`; if the host returns an OAuth challenge, ask the user to complete the connection. In local Codex, continue from a new conversation after OAuth instead of repeatedly retrying from the guest conversation. Do not report that account tools are unavailable merely because the current session started as a guest.
+
+After authentication, use the account context to choose a workspace. If exactly one writable workspace is available, select it without asking. If several are available, call `list_workspaces` and ask the user which one to use. Workspace access is read-only through MCP; do not attempt workspace administration.
+
+- Use form listing and lookup tools to identify the target before changing it.
+- `create_form` creates a draft. After creation, ask whether the user wants it published.
+- Before `update_form`, `publish_form`, or `trash_form`, fetch the form and pass its current `revision` as `expected_revision`. On conflict, fetch, reconcile, and retry instead of overwriting newer changes.
+- Call `publish_form` only after the user explicitly confirms publication, then pass the confirmed form's `expected_revision` and `confirm_publish: true`.
+- Call `trash_form` only after the user explicitly confirms moving the form to trash, then pass the confirmed form's `expected_revision` and `confirm_trash: true`. MCP does not expose form restoration or permanent deletion.
+- Premium fields may appear in previews. On save, preserve and explain any `disabled_features` and warnings returned by OpnForm; never imply that MCP bypasses the workspace plan.
+
+## Read submissions
+
+Submission access requires OAuth. Authenticate only when the user's request needs account data.
+
+- Use `list_submissions` to browse, filter, and search. Use `get_submission` for one result.
+- Use `get_submission_stats` only for aggregates available in OpnForm's form statistics view.
+- Use `export_submissions` only when the user requests an export, then poll `get_submission_export` until it is ready.
+- Submission access is read-only. Do not create, update, delete, or restore submissions.
+- Return only the submission fields needed for the request, especially when values contain personal or sensitive data.
+
+## Safety and recovery
+
+- Treat draft tokens, editor handoffs, OAuth tokens, and export URLs as secrets.
+- If a preview or editor URL expires, call the appropriate tool for a fresh URL; never reconstruct one.
+- If authentication is unavailable, continue with guest-safe draft tools when the task permits it.
+- Never bypass confirmation, workspace permission, validation, revision checks, plan enforcement, or rate limits.
diff --git a/plugins/opnform/skills/opnform/agents/openai.yaml b/plugins/opnform/skills/opnform/agents/openai.yaml
new file mode 100644
index 000000000..da6e474e8
--- /dev/null
+++ b/plugins/opnform/skills/opnform/agents/openai.yaml
@@ -0,0 +1,14 @@
+interface:
+ display_name: "OpnForm"
+ short_description: "Create and manage OpnForm forms through MCP"
+ brand_color: "#2563EB"
+ default_prompt: "Use $opnform to create, preview, or manage an OpnForm form directly through MCP."
+dependencies:
+ tools:
+ - type: "mcp"
+ value: "opnform"
+ description: "Create, preview, and manage OpnForm forms and read submissions"
+ transport: "streamable_http"
+ url: "https://api.opnform.com/mcp"
+policy:
+ allow_implicit_invocation: true
diff --git a/scripts/codex-worktree-lib.sh b/scripts/codex-worktree-lib.sh
index 811d594a9..6e0c8eed8 100755
--- a/scripts/codex-worktree-lib.sh
+++ b/scripts/codex-worktree-lib.sh
@@ -206,6 +206,27 @@ ensure_php_dependencies() {
fi
}
+ensure_mcp_oauth_keys() {
+ select_php_runtime
+
+ public_key="$ROOT_DIR/api/storage/oauth-public.key"
+ private_key="$ROOT_DIR/api/storage/oauth-private.key"
+
+ if [ -f "$public_key" ] && [ -f "$private_key" ]; then
+ return 0
+ fi
+
+ if [ -f "$public_key" ] || [ -f "$private_key" ]; then
+ echo "Incomplete Passport key pair in api/storage. Remove the remaining key and rerun setup." >&2
+ exit 1
+ fi
+
+ (
+ cd "$ROOT_DIR/api"
+ APP_ENV=codex "$CODEX_PHP_BIN" artisan passport:keys --force --env=codex
+ )
+}
+
php_version_is_supported() {
version="$1"
major=${version%%.*}
diff --git a/scripts/codex-worktree-setup.sh b/scripts/codex-worktree-setup.sh
index b745c207c..5f81840a1 100755
--- a/scripts/codex-worktree-setup.sh
+++ b/scripts/codex-worktree-setup.sh
@@ -18,6 +18,7 @@ done
write_codex_env_files
ensure_php_dependencies
+ensure_mcp_oauth_keys
ensure_node_dependencies
ensure_codex_database
print_codex_environment_summary
diff --git a/scripts/codex-worktree-up.sh b/scripts/codex-worktree-up.sh
index 2e94a9e2c..57a55a496 100755
--- a/scripts/codex-worktree-up.sh
+++ b/scripts/codex-worktree-up.sh
@@ -15,6 +15,7 @@ if [ ! -f "$CODEX_API_ENV_FILE" ] || [ ! -f "$CODEX_CLIENT_ENV_FILE" ]; then
else
write_codex_env_files
ensure_php_dependencies
+ ensure_mcp_oauth_keys
ensure_node_dependencies
ensure_codex_database
if ! database_is_migrated; then
diff --git a/scripts/e2e-reset.sh b/scripts/e2e-reset.sh
index a326367fe..193d565ba 100755
--- a/scripts/e2e-reset.sh
+++ b/scripts/e2e-reset.sh
@@ -8,6 +8,7 @@ COMPOSE_FILES="-f $ROOT_DIR/docker-compose.e2e.yml"
docker compose $COMPOSE_FILES exec -T api sh -lc 'rm -rf storage/framework/cache/data/* storage/framework/sessions/*'
docker compose $COMPOSE_FILES exec -T api php artisan optimize:clear
docker compose $COMPOSE_FILES exec -T api php artisan cache:clear
+docker compose $COMPOSE_FILES exec -T api sh -lc 'mkdir -p storage/framework/cache/data storage/framework/sessions && chmod -R a+rwX storage/framework/cache storage/framework/sessions'
docker compose $COMPOSE_FILES exec -T api php artisan migrate:fresh --seed --seeder=Database\\Seeders\\E2ETestSeeder --force
echo "E2E database reset complete."