Skip to content

Beautiful Open-Source Form Builder

fix(mcp): harden ChatGPT widget contract

Julien Nahum145d2d375ce0
diff --git a/api/app/Mcp/Apps/FormDraftPreviewApp.php b/api/app/Mcp/Apps/FormDraftPreviewApp.php
index a7583edf8..e10fad009 100644
--- a/api/app/Mcp/Apps/FormDraftPreviewApp.php
+++ b/api/app/Mcp/Apps/FormDraftPreviewApp.php
@@ -30,7 +30,11 @@ class FormDraftPreviewApp extends AppResource
public function handle(Request $request): Response
{
- $response = Response::view('mcp.form-draft-preview-app');
+ $response = Response::view('mcp.form-draft-preview-app')
+ ->withMeta(
+ 'openai/widgetDescription',
+ 'Interactive private preview of the current OpnForm draft, with zoom controls and an Edit in OpnForm action.',
+ );
$origin = $this->frontOrigin();
if ($origin !== null) {
@@ -49,14 +53,14 @@ class FormDraftPreviewApp extends AppResource
{
$origin = $this->frontOrigin();
if ($origin === null) {
- return AppMeta::make();
+ return AppMeta::make()->prefersBorder(false);
}
return AppMeta::make()->csp(
Csp::make()
->resourceDomains([$origin])
->frameDomains([$origin]),
- )->domain($origin);
+ )->domain($origin)->prefersBorder(false);
}
private function frontOrigin(): ?string
diff --git a/api/app/Mcp/Apps/LegacyFormDraftPreviewApp.php b/api/app/Mcp/Apps/LegacyFormDraftPreviewApp.php
index ff5264d2c..ee336b254 100644
--- a/api/app/Mcp/Apps/LegacyFormDraftPreviewApp.php
+++ b/api/app/Mcp/Apps/LegacyFormDraftPreviewApp.php
@@ -4,15 +4,12 @@ namespace App\Mcp\Apps;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Attributes\Name;
-use Laravel\Mcp\Server\Contracts\HasUriTemplate;
-use Laravel\Mcp\Support\UriTemplate;
+use Laravel\Mcp\Server\Attributes\Uri;
-#[Name('legacy_form_draft_preview')]
-#[Description('Compatibility resource for OpnForm preview templates referenced by existing plugin versions and conversations.')]
-class LegacyFormDraftPreviewApp extends FormDraftPreviewApp implements HasUriTemplate
+#[Name('legacy_form_draft_preview_v8')]
+#[Description('Compatibility resource for the form preview URI published by the current OpenAI plugin snapshot.')]
+#[Uri(LegacyFormDraftPreviewApp::URI)]
+class LegacyFormDraftPreviewApp extends FormDraftPreviewApp
{
- public function uriTemplate(): UriTemplate
- {
- return new UriTemplate('ui://opnform/form-draft-preview-{version}');
- }
+ public const URI = 'ui://opnform/form-draft-preview-v8.html';
}
diff --git a/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php b/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
index a04925495..fd2b341f3 100644
--- a/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
+++ b/api/app/Mcp/Tools/OpenFormDraftInEditorTool.php
@@ -45,9 +45,9 @@ class OpenFormDraftInEditorTool extends GuestDraftMcpTool
$handoff = $drafts->issueEditorHandoff($validated['draft_handle']);
return Response::structured([
- 'editor_url' => $handoff['editor_url'],
+ 'editor_handoff_ready' => true,
'expires_at' => $handoff['expires_at'],
- ]);
+ ])->withMeta('editor_url', $handoff['editor_url']);
}
public function schema(JsonSchema $schema): array
@@ -64,7 +64,7 @@ class OpenFormDraftInEditorTool extends GuestDraftMcpTool
public function outputSchema(JsonSchema $schema): array
{
return [
- 'editor_url' => $schema->string()->format('uri')->required(),
+ 'editor_handoff_ready' => $schema->boolean()->required(),
'expires_at' => $schema->string()->format('date-time')->required(),
];
}
diff --git a/api/app/Mcp/Tools/PreviewFormDraftTool.php b/api/app/Mcp/Tools/PreviewFormDraftTool.php
index 737f1230d..70299c3f0 100644
--- a/api/app/Mcp/Tools/PreviewFormDraftTool.php
+++ b/api/app/Mcp/Tools/PreviewFormDraftTool.php
@@ -44,8 +44,7 @@ class PreviewFormDraftTool extends GuestDraftMcpTool
return Response::structured([
'draft_handle' => $validated['draft_handle'],
'draft' => $drafts->serialize($draft),
- 'preview_url' => $drafts->previewUrl($draft),
- ]);
+ ])->withMeta('preview_url', $drafts->previewUrl($draft));
}
public function schema(JsonSchema $schema): array
@@ -64,7 +63,6 @@ class PreviewFormDraftTool extends GuestDraftMcpTool
return [
'draft_handle' => $schema->string()->min(43)->max(43)->required(),
'draft' => McpOutputSchema::draft($schema)->required(),
- 'preview_url' => $schema->string()->format('uri')->required(),
];
}
}
diff --git a/api/resources/views/mcp/form-draft-preview-app.blade.php b/api/resources/views/mcp/form-draft-preview-app.blade.php
index 5675fd976..64a3bcb15 100644
--- a/api/resources/views/mcp/form-draft-preview-app.blade.php
+++ b/api/resources/views/mcp/form-draft-preview-app.blade.php
@@ -119,6 +119,10 @@
?? result
?? {};
+ const toolMeta = (result) => result?._meta
+ ?? result?.meta
+ ?? {};
+
const applyToolInput = (input) => {
const args = input?.arguments ?? input ?? {};
draftHandle = args.draft_handle ?? draftHandle;
@@ -127,10 +131,12 @@
const renderToolResult = (result) => {
const payload = toolPayload(result);
+ const resultMeta = toolMeta(result);
const draft = payload.draft ?? {};
const definition = draft.definition ?? {};
+ const previewUrlValue = resultMeta.preview_url;
- if (!payload.preview_url && !draft.version && !definition.title) {
+ if (!previewUrlValue && !draft.version && !definition.title) {
return false;
}
@@ -141,8 +147,8 @@
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);
+ if (previewUrlValue) {
+ const previewUrl = new URL(previewUrlValue);
previewUrl.searchParams.set('embedded', '1');
const nextPreviewUrl = previewUrl.toString();
if (currentPreviewUrl !== nextPreviewUrl) {
@@ -205,13 +211,14 @@
const result = await app.callServerTool('open_form_draft_in_editor', {
draft_handle: draftHandle,
});
- const payload = toolPayload(result);
+ const resultMeta = toolMeta(result);
+ const editorUrl = resultMeta.editor_url;
- if (result?.isError || !payload.editor_url) {
+ if (result?.isError || !editorUrl) {
throw new Error('Editor link unavailable');
}
- await app.openLink({ url: payload.editor_url });
+ await app.openLink({ url: editorUrl });
} catch (error) {
actionStatus.textContent = 'Could not open the OpnForm editor. Please try again.';
actionStatus.hidden = false;
diff --git a/api/tests/Feature/Mcp/AgentDraftEditorTest.php b/api/tests/Feature/Mcp/AgentDraftEditorTest.php
index ae1e88887..9d9c8f367 100644
--- a/api/tests/Feature/Mcp/AgentDraftEditorTest.php
+++ b/api/tests/Feature/Mcp/AgentDraftEditorTest.php
@@ -1,6 +1,8 @@
<?php
use App\Http\Controllers\AgentFormDraftController;
+use App\Mcp\Apps\FormDraftPreviewApp;
+use App\Mcp\Apps\LegacyFormDraftPreviewApp;
use App\Mcp\Servers\OpnFormServer;
use App\Mcp\Tools\OpenFormDraftInEditorTool;
use App\Mcp\Tools\PreviewFormDraftTool;
@@ -34,7 +36,7 @@ it('renders a read-only MCP App preview and creates an editor link only on deman
OpnFormServer::tool(PreviewFormDraftTool::class, [
'draft_handle' => $created['token'],
])->assertOk()
- ->assertSee('preview_url')
+ ->assertDontSee('preview_url')
->assertSee('draft_handle')
->assertDontSee('editor_url')
->assertSee('Agent customer intake');
@@ -53,7 +55,8 @@ it('renders a read-only MCP App preview and creates an editor link only on deman
OpnFormServer::tool(OpenFormDraftInEditorTool::class, [
'draft_handle' => $created['token'],
])->assertOk()
- ->assertSee('editor_url')
+ ->assertSee('editor_handoff_ready')
+ ->assertDontSee('editor_url')
->assertDontSee('handoff_token');
$draft = $created['draft']->refresh();
@@ -62,13 +65,13 @@ it('renders a read-only MCP App preview and creates an editor link only on deman
->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'])
+ ->and(app(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);
+ $previewApp = app(FormDraftPreviewApp::class);
$resource = $previewApp->handle(new \Laravel\Mcp\Request())
->content()
->toResource($previewApp);
@@ -80,7 +83,11 @@ it('publishes standard and ChatGPT-compatible CSP metadata with the full fronten
->toBe(['http://127.0.0.1:33676'])
->and($previewApp->resolvedAppMeta()['csp']['frameDomains'])
->toBe(['http://127.0.0.1:33676'])
+ ->and($previewApp->resolvedAppMeta()['prefersBorder'])
+ ->toBeFalse()
->and($resource['text'])->not->toContain('native-preview')
+ ->and($resource['_meta']['openai/widgetDescription'])
+ ->toBe('Interactive private preview of the current OpnForm draft, with zoom controls and an Edit in OpnForm action.')
->and($resource['_meta']['openai/widgetCSP'])
->toBe([
'connect_domains' => [],
@@ -90,7 +97,7 @@ it('publishes standard and ChatGPT-compatible CSP metadata with the full fronten
]);
config()->set('app.front_url', 'https://opnform.test');
- $secureApp = app(\App\Mcp\Apps\FormDraftPreviewApp::class);
+ $secureApp = app(FormDraftPreviewApp::class);
$secureResource = $secureApp->handle(new \Laravel\Mcp\Request())
->content()
->toResource($secureApp);
@@ -105,17 +112,32 @@ it('publishes standard and ChatGPT-compatible CSP metadata with the full fronten
->toBe(['https://opnform.test']);
});
-it('keeps preview template URIs used by existing plugin versions readable', function () {
- $headers = ['Accept' => 'application/json, text/event-stream'];
+it('keeps signed editor URLs private to the widget result metadata', function () {
+ $created = app(AgentFormDraftService::class)->create(editorDraftDefinition());
- $historicalUris = array_map(
- fn (int $version) => "ui://opnform/form-draft-preview-v{$version}",
- range(3, 7),
- );
- $historicalUris[] = 'ui://opnform/form-draft-preview-v8.html';
+ $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 1,
+ 'method' => 'tools/call',
+ 'params' => [
+ 'name' => 'open_form_draft_in_editor',
+ 'arguments' => ['draft_handle' => $created['token']],
+ ],
+ ], ['Accept' => 'application/json, text/event-stream'])->assertOk()
+ ->assertJsonPath('result.isError', false)
+ ->assertJsonPath('result.structuredContent.editor_handoff_ready', true)
+ ->assertJsonPath('result.structuredContent.expires_at', fn (string $expiresAt): bool => $expiresAt !== '')
+ ->assertJsonMissingPath('result.structuredContent.editor_url')
+ ->assertJsonPath('result._meta.editor_url', fn (string $url): bool => str_starts_with(
+ $url,
+ 'https://opnform.test/agent-drafts/edit#handoff=',
+ ));
+});
- foreach ($historicalUris as $index => $uri) {
+it('keeps the current OpenAI snapshot preview URI readable without a catch-all template', function () {
+ $headers = ['Accept' => 'application/json, text/event-stream'];
+ foreach ([FormDraftPreviewApp::URI, LegacyFormDraftPreviewApp::URI] as $index => $uri) {
$this->postJson('/mcp', [
'jsonrpc' => '2.0',
'id' => $index + 1,
@@ -128,6 +150,16 @@ it('keeps preview template URIs used by existing plugin versions readable', func
->assertSee('Edit in OpnForm');
}
+ $resourcesResponse = $this->postJson('/mcp', [
+ 'jsonrpc' => '2.0',
+ 'id' => 7,
+ 'method' => 'resources/list',
+ 'params' => [],
+ ], $headers)->assertOk();
+
+ expect(collect($resourcesResponse->json('result.resources'))->pluck('uri'))
+ ->toContain(FormDraftPreviewApp::URI, LegacyFormDraftPreviewApp::URI);
+
$resourceTemplatesResponse = $this->postJson('/mcp', [
'jsonrpc' => '2.0',
'id' => 8,
@@ -136,7 +168,7 @@ it('keeps preview template URIs used by existing plugin versions readable', func
], $headers)->assertOk();
expect(collect($resourceTemplatesResponse->json('result.resourceTemplates'))->pluck('uriTemplate'))
- ->toContain('ui://opnform/form-draft-preview-{version}');
+ ->not->toContain('ui://opnform/form-draft-preview-{version}');
});
it('serves preview data only through a valid signed URL without exposing capabilities', function () {
diff --git a/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php b/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php
index 63c378d56..655dcf9c9 100644
--- a/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php
+++ b/api/tests/Feature/Mcp/AuthenticatedFormToolsTest.php
@@ -168,7 +168,10 @@ it('hides guest draft capabilities but keeps validation and OAuth tools on self-
expect($resourceUris)
->toContain('opnform://schemas/agent-form-definition/v1', 'opnform://reference/form-fields/v1')
- ->not->toContain('ui://opnform/form-draft-preview.html');
+ ->not->toContain(
+ 'ui://opnform/form-draft-preview.html',
+ 'ui://opnform/form-draft-preview-v8.html',
+ );
$resourceTemplatesResponse = $this->postJson('/mcp', [
'jsonrpc' => '2.0',
diff --git a/api/tests/Feature/Mcp/GuestDraftToolsTest.php b/api/tests/Feature/Mcp/GuestDraftToolsTest.php
index 3d01e9fca..d691ff84b 100644
--- a/api/tests/Feature/Mcp/GuestDraftToolsTest.php
+++ b/api/tests/Feature/Mcp/GuestDraftToolsTest.php
@@ -40,11 +40,14 @@ it('publishes a neutral draft handle contract and accurate preview annotations',
->and($preview['_meta']['openai/outputTemplate'])->toBe('ui://opnform/form-draft-preview.html')
->and($preview['inputSchema']['properties'])->toHaveKey('draft_handle')
->and($preview['outputSchema']['properties'])->not->toHaveKeys([
+ 'preview_url',
'editor_url',
'editor_link_expires_at',
])
->and($preview['annotations']['readOnlyHint'])->toBeTrue()
->and($open['_meta']['ui']['visibility'])->toBe(['model', 'app'])
+ ->and($open['outputSchema']['properties'])->toHaveKey('editor_handoff_ready')
+ ->and($open['outputSchema']['properties'])->not->toHaveKey('editor_url')
->and($open['outputSchema']['properties'])->not->toHaveKey('handoff_token');
});
diff --git a/api/tests/Feature/Mcp/McpOAuthTest.php b/api/tests/Feature/Mcp/McpOAuthTest.php
index bb2bb36cf..388ee32af 100644
--- a/api/tests/Feature/Mcp/McpOAuthTest.php
+++ b/api/tests/Feature/Mcp/McpOAuthTest.php
@@ -154,7 +154,8 @@ it('creates and previews a guest form over HTTP without an OAuth challenge', fun
], mcpHeaders())->assertOk()
->assertJsonPath('result.isError', false)
->assertJsonPath('result.structuredContent.draft.definition.title', 'Contact form')
- ->assertJsonPath('result.structuredContent.preview_url', fn (string $url): bool => str_starts_with($url, 'https://opnform.test/'))
+ ->assertJsonMissingPath('result.structuredContent.preview_url')
+ ->assertJsonPath('result._meta.preview_url', fn (string $url): bool => str_starts_with($url, 'https://opnform.test/'))
->assertJsonPath('result.structuredContent.draft_handle', $draftHandle)
->assertJsonMissingPath('result.structuredContent.editor_url')
->assertJsonMissingPath('result._meta.mcp/www_authenticate');