Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(mcp): add secure ChatGPT MSO Surface

Rahman5ac14bc96cd6
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 6ee75ba8..d16d523a 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -115,6 +115,22 @@ The shell uses the History API for focus/open URL synchronization instead of tre
window operation as a server navigation. Reserved framework paths are never allowed to fall
through the app catch-all.
+### 4.1 ChatGPT as an MSO presentation target
+
+The web catch-all remains the authenticated cockpit route. ChatGPT does **not** frame that cockpit.
+Instead `render_mso_surface` binds the versioned MCP App resource `ui://mso/surface-v1.html`, which
+implements a smaller presentation router for `/`, `/monitor`, `/project`, `/diff`, `/browser` and
+`/apps/<reviewed-id>`. Native Surface views call the same bounded MSO tools; reviewed app demos may
+use a nested iframe only when their exact HTTPS origin exists in the code-owned Surface catalog and
+the MCP resource CSP `frameDomains`. Anti-frame apps stay on the remote-browser seam.
+
+This trust catalog is deliberately separate from Store/runtime `AppManifest` data. A locally installed
+`runtime:"html"` app or HTML widget is user-controlled presentation data and cannot grant itself a
+ChatGPT nested-frame origin. `srcDoc` HTML remains opaque-origin sandboxed, the MCP widget stays on
+`mso-ui.rahmanef.com`, and the authenticated `mso.rahmanef.com` cockpit retains its deny-framing
+headers. The split prevents convenient HTML/runtime extensibility from becoming a CSP privilege
+escalation path.
+
## 5. Host API and filesystem model
`/api/v1/*` is the authenticated host API. Important families include:
diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.md
index 55ee22b6..7d0a909e 100644
--- a/docs/CHATGPT-PLUGIN.md
+++ b/docs/CHATGPT-PLUGIN.md
@@ -8,7 +8,7 @@ The exact current server/toolset identity plus the full MSO and compact ChatGPT
Browser-hosted MCP probes from ChatGPT are allowed only when they target the configured public `OS_PUBLIC_ORIGIN`; arbitrary origins and ChatGPT-origin requests aimed at loopback remain denied. Additional trusted browser hosts can be added explicitly with comma-separated `OS_MCP_BROWSER_ORIGINS`. Public OAuth discovery and DCR responses carry CORS metadata; authenticated `/mcp` echoes only an approved exact origin.
-The compact descriptor regression currently measures **64,180 JSON bytes** for the current generated ChatGPT profile (roughly 16.0k tokens at a 4-byte/token estimate), with the largest individual descriptor **2,615 bytes**. CI keeps the profile below 72 KiB and each descriptor below 8 KiB. Bytes are the deterministic contract; token estimates vary by tokenizer.
+The compact descriptor regression currently measures **67,496 JSON bytes** for the current generated ChatGPT profile (roughly 16.9k tokens at a 4-byte/token estimate), with the largest individual descriptor **2,615 bytes**. CI keeps the profile below 72 KiB and each descriptor below 8 KiB. Bytes are the deterministic contract; token estimates vary by tokenizer.
## Why ChatGPT gets a compact profile
@@ -28,6 +28,7 @@ ChatGPT
├─ project snapshot / diff / knowledge / project-agent tasks
├─ Convex status + dynamic Convex MCP schemas/calls
├─ MCP Apps UI for workflow, project, diff and VPS
+ ├─ universal MSO Surface + reviewed live app demos
└─ dynamic project MCP/function seams for project-owned tools
```
@@ -55,6 +56,8 @@ The restored Original MSO operator primitives (`sys_*`, `fs_usage` + full bounde
Project-owned MCP names and Convex's own dynamic schemas still load on demand through `project_mcp_tools` / `project_mcp_call` and `project_database_tools` / `project_database_call`. That is how MSO keeps a bounded static model profile instead of copying every downstream provider/project action into ChatGPT.
+`render_mso_surface` is the presentation bridge for ChatGPT-as-an-MSO-shell. It accepts only MSO-style routes and a server-reviewed app id; arbitrary HTML and external URL inputs are not part of its schema. `mso_surface_apps_list` exposes only the public reviewed catalog. Direct nested frames are exact-origin allowlisted in the MCP App resource CSP, while anti-frame applications remain remote-browser candidates. User-installed runtime HTML apps do not inherit this trust automatically.
+
### Structured-result contract
After the Fresh 3 rescan exposed `Output schema recommended` on non-UI actions, the ChatGPT profile now advertises an output schema on **all current ChatGPT transport actions** without duplicating dozens of provider/project result definitions. Tools with stable UI-critical shapes keep their explicit typed schemas. Every other ChatGPT action uses one exact outer `{ result: ... }` contract and returns the already-bounded JSON value inside `structuredContent.result`; its text `content` is a short acknowledgement so the same payload is not duplicated in the conversation transcript. Full/generic MCP clients keep the historical text-only contract unless a tool explicitly declares structured output. `screen_capture` keeps the image in MCP content and exposes only safe dimensions/URLs/expiry metadata in the structured envelope—never base64 image bytes.
@@ -146,7 +149,7 @@ MSO uses Streamable HTTP JSON-RPC over `POST /mcp`.
4. Choose OAuth and complete the MSO consent flow on an approved owner device.
5. Select the lowest useful MSO tier.
6. Run **Scan Tools / Refresh** in ChatGPT.
-7. Verify that the action snapshot corresponds to the 62-tool transport profile (61 model actions + app-only `workflow_status`) above.
+7. Verify that the action snapshot corresponds to the 64-tool transport profile (63 model actions + app-only `workflow_status`) in the generated catalog.
8. Start a new chat when testing a newly scanned draft/action snapshot.
After a schema/profile change, changing production code alone does not replace ChatGPT's frozen action snapshot. Refresh/re-scan (or recreate/republish where the workspace UI requires it) after deployment.
@@ -177,3 +180,5 @@ The live diagnostic `GET /mcp` returns both `toolset` (full MSO) and `chatgptToo
- Remote HTTP project MCP calls retain MSO's public-address / SSRF / DNS-rebinding guard.
- Tool hiding is not a substitute for scope checks; list-time and call-time scope enforcement both remain mandatory.
- Hidden ChatGPT transcript, private chain-of-thought and credentials are never copied into Local Agent/project MCP messages.
+- MSO Surface never accepts raw HTML/arbitrary URL input; nested iframe origins are code-reviewed, exact-origin CSP entries and revalidated in the widget.
+- The authenticated MSO cockpit stays non-frameable, and user-installed HTML/runtime manifests cannot promote themselves into the ChatGPT frame allowlist.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 5d0fb0c0..dbfa5c19 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,4 +1,5 @@
# mso — Progress Log
+- **MSO Surface v1 / ChatGPT presentation target (2026-09-04):** MCP server `1.9.0` / toolset `2026.09.04.1` adds `mso_surface_apps_list` and `render_mso_surface`, taking the ChatGPT profile to 64 transport tools (63 model actions + app-only `workflow_status`) and the full model catalog to 87. `ui://mso/surface-v1.html` is a universal responsive MCP App with native home/monitor/project/diff/browser routes, fullscreen/PiP controls, and reviewed app-demo routing. Security is default-deny: no raw HTML or arbitrary URL tool inputs, dynamic strings use DOM text nodes, iframe URLs are revalidated against a catalog bundled in the UI resource, nested `frameDomains` contains only exact reviewed origins, sandbox grants omit popups/top-navigation, authenticated MSO remains non-frameable, and user-installed `runtime:"html"`/HTML widgets cannot promote themselves into the ChatGPT frame allowlist. AntiNRML Builder is the first direct live-demo origin; Baton and AntiNRML Game remain remote because their production XFO/CSP currently deny third-party framing.
- **MCP App contextual landing hardening (2026-09-03):** `Open in MSO` no longer lands on an idle desktop. Workflow/VPS/project/diff cards target `/assistant/mcp`, `/monitor`, `/files`, and `/code`; the shell also recognizes ChatGPT's root `redirectUrl=https://chatgpt.com/c/...` handoff and redirects it to Alfa → MCP Activity so an already-cached v2 widget still produces a visible result. Assistant deep-link payloads now select their requested tab even when reusing an existing singleton window. MCP tool count, scopes, output schemas, and v2 resource URIs are unchanged.
- **Live-build chunk corruption eliminated (2026-09-03):** a production browser repro proved the shell/Settings crash was not a Settings logic regression: an in-place `next build` in the active service checkout replaced `.next` while the old Next process still served its boot-time manifest, making all 19 root-referenced chunks disappear and one observed JS request return `500 text/plain`. Production was recovered through `mso deploy`; shell + Settings then passed real authenticated Playwright on desktop/mobile with zero failed requests/console errors. `bun run build` is now a fail-closed wrapper that holds the checkout exclusion and refuses a same-checkout live runtime; `mso build` remains the out-of-tree proof and guarded deploy/update lifecycles invoke raw Next only after quiescence. Post-replacement validation now checks every root-referenced JS/CSS asset status+MIME, not one CSS/chunk. The Fresh 3 smoke scratch path moved out of protected `~/.mso`, and recursive `fs_mkdir` now securely supports missing parents while rejecting symlink escapes.
diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.md
index 5528625d..7df45692 100644
--- a/docs/TESTING-HANDOFF.md
+++ b/docs/TESTING-HANDOFF.md
@@ -5,10 +5,10 @@ Update this file at the end of every manual or automated test session. Keep it f
## Current status
-The current release target is **MSO CLI 1.12.0**, MCP server `1.8.2`, toolset `2026.09.03.7`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.
+The current release target is **MSO CLI 1.12.0**, MCP server `1.9.0`, toolset `2026.09.04.1`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.
Current verified behavior:
-- Fresh 3 current MCP contract: server `1.8.2` / toolset `2026.09.03.7`; ChatGPT receives **62 transport tools = 61 model/operator actions (32 read / 17 write / 12 exec) + app-only `workflow_status`**, while the full transport catalog is 86 tools / 85 model tools. Every ChatGPT action advertises `outputSchema`, the dedicated MCP Apps widget origin is `https://mso-ui.rahmanef.com`, and five official digest-verified Skills are exposed through the MCP Skills/resource extension. The four MCP Apps use v2 resource URIs and `Open in MSO` now has visible bridge status, `setOpenInAppUrl`, and a direct-link fallback for host navigation failures.
+- Fresh 3 current MCP contract: server `1.9.0` / toolset `2026.09.04.1`; ChatGPT receives **64 transport tools = 63 model/operator actions (34 read / 17 write / 12 exec) + app-only `workflow_status`**, while the full transport catalog is 88 tools / 87 model tools. Every ChatGPT action advertises `outputSchema`, the dedicated MCP Apps widget origin is `https://mso-ui.rahmanef.com`, and five official digest-verified Skills are exposed through the MCP Skills/resource extension. Five MCP Apps are now published: the four existing v2 operator cards plus `ui://mso/surface-v1.html`. The Surface accepts no raw HTML/arbitrary URL; its one direct demo origin is exact-origin allowlisted, while Baton/AntiNRML Game remain remote because their current headers deny third-party framing.
- MCP App navigation acceptance: a ChatGPT-opened root URL carrying `redirectUrl=https://chatgpt.com/c/...` must 307 to `/assistant/mcp`, then authenticated browser E2E must show the Alfa `MCP Activity` view. Contextual widget targets are workflow→`/assistant/mcp`, VPS→`/monitor`, project→`/files`, diff→`/code`. This changes no MCP tool/schema/resource URI, so existing Fresh 3 registrations remain compatible.
- P10 memory retention/lifecycle: isolated fixtures now archive only cold finished claims before the hard 2,000-record / 2 MiB live-ledger limits. Trigger/target are 1,400 -> <=1,000 live records (or ~1.4 MiB -> ~1 MiB); archive segments are content-addressed, owner-only and archive-before-ledger atomic. `bench:memory:lifecycle` is **8/8 deterministic** with a 1,400-correction seed ending at **1,000 live + 401 archived / two segments** and a 56-byte resolved projection. It verifies explicit archived-history retrieval, historical temporal resolution, aggregate-only no-content telemetry, `0700/0600` permissions, interrupted-commit live-wins semantics, backdated replacement over immutable archive, and frozen session A / fresh session B / resume-copy behavior. The P10 retrieval gate is **4/6 lexical** (synonym + Indonesian/English misses remain explicit); P10D also calibrates the existing local `mso-local-hybrid-v1` encoder on the same rows and gets **3/6** with zero network calls / zero persisted memory vectors, so production vector storage stays blocked by measured non-improvement rather than assumption. **3/3 two-hop relationship fixtures** keep graph storage blocked. The exact-history crowding bug (`Runtime-1` vs `Runtime-10...`) is fixed by exact phrase/token scoring; legacy `bench:memory` remains 100%.
- P9 memory calibration: isolated temporary-memory fixtures now cover repeated corrections, explicit-vs-observed authority, confidence/recency, future validity, forget, and history integrity. P9 fixed a real temporal privacy bug where `forget` could leave a future-scheduled claim that resurrected later; forget now closes all current/future-capable intervals while preserving already-ended history. Final 200-correction stress from source `d249da4`: **6/6 calibration scenarios**, existing memory benchmark **100%**, Cognitive Runtime memory gates **100%**; 200 ledger rows / 135,180 bytes resolve to 1 row / 58-byte compatibility projection (**99.96% smaller**) and history retrieval remains capped at 100. No calibrated case requires graph memory.
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 2103d995..5a6ff715 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,21 +4,21 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.8.2 version=2026.09.03.7 tools=85 read=41 write=25 exec=19 -->
+<!-- mcp-toolset: server=1.9.0 version=2026.09.04.1 tools=87 read=43 write=25 exec=19 -->
| Fact | Current source value |
|---|---:|
-| MCP server | `1.8.2` |
-| Toolset | `2026.09.03.7` |
-| Toolset changed at | `2026-09-03T14:51:00Z` |
-| Transport tools | **86** |
-| Model/operator tools | **85** |
-| Read | **41** |
+| MCP server | `1.9.0` |
+| Toolset | `2026.09.04.1` |
+| Toolset changed at | `2026-09-03T17:55:43Z` |
+| Transport tools | **88** |
+| Model/operator tools | **87** |
+| Read | **43** |
| Write | **25** |
| Exec | **19** |
| App-only bridges | **1** |
-### Read (41)
+### Read (43)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -44,6 +44,7 @@
- `local_agent_inbox`
- `local_agent_request_wait`
- `local_agents_list`
+- `mso_surface_apps_list`
- `project_agent_status`
- `project_capabilities`
- `project_changes_list`
@@ -53,6 +54,7 @@
- `project_memory_search`
- `projects_list`
- `read_pipeline`
+- `render_mso_surface`
- `screen_capture`
- `skills_list`
- `skills_read`
@@ -118,20 +120,20 @@
## ChatGPT static profile
-<!-- mcp-chatgpt-profile: server=1.8.2 version=2026.09.03.7 tools=61 read=32 write=17 exec=12 app-only=1 total=62 -->
+<!-- mcp-chatgpt-profile: server=1.9.0 version=2026.09.04.1 tools=63 read=34 write=17 exec=12 app-only=1 total=64 -->
The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_NAMES`. OAuth scope is still enforced independently; project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **62** |
-| ChatGPT model/operator tools | **61** |
-| Read | **32** |
+| ChatGPT transport tools | **64** |
+| ChatGPT model/operator tools | **63** |
+| Read | **34** |
| Write | **17** |
| Exec | **12** |
| App-only bridges | **1** |
-### ChatGPT read (32)
+### ChatGPT read (34)
- `agent_session_current`
- `apps_list`
@@ -150,6 +152,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `local_agent_inbox`
- `local_agent_request_wait`
- `local_agents_list`
+- `mso_surface_apps_list`
- `project_agent_status`
- `project_capabilities`
- `project_changes_list`
@@ -158,6 +161,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `project_knowledge_get`
- `projects_list`
- `read_pipeline`
+- `render_mso_surface`
- `screen_capture`
- `skills_list`
- `skills_read`
diff --git a/docs/integrations/CHATGPT-UI.md b/docs/integrations/CHATGPT-UI.md
index 2ee047db..31052be4 100644
--- a/docs/integrations/CHATGPT-UI.md
+++ b/docs/integrations/CHATGPT-UI.md
@@ -24,6 +24,7 @@ Official references:
| Project status | `project_get` | `ui://mso/project-status-v2.html` | widget calls `project_get` again |
| Git diff summary | `project_diff` | `ui://mso/project-diff-v2.html` | static result; request a new diff for changed state |
| VPS/operator status | `vps_status` | `ui://mso/vps-status-v2.html` | widget calls `vps_status` again |
+| Universal MSO Surface | `render_mso_surface` | `ui://mso/surface-v1.html` | native views call bounded read tools; reviewed apps may use exact-origin nested frames |
Source boundaries:
@@ -31,6 +32,8 @@ Source boundaries:
| --- | --- |
| Resource registry / workflow UI | `lib/mcp/ui-resources.ts` |
| Project/diff/VPS resources | `lib/mcp/ui-operator-resources.ts` |
+| Universal Surface resource/runtime | `lib/mcp/ui-surface.ts`, `lib/mcp/ui-surface-script.ts`, `lib/mcp/ui-surface-style.ts` |
+| Surface security catalog/router | `lib/mcp/surface-catalog.ts`, `lib/mcp/tools-surface.ts` |
| Resource capability / RPC | `lib/mcp/dispatch.ts` |
| Workflow structured schema | `lib/mcp/tools-workflow-start.ts`, `lib/mcp/tools-workflow-lifecycle.ts` |
| Project/diff structured schemas | `lib/mcp/tools-project-experience.ts` |
@@ -50,7 +53,11 @@ The diff component receives only project/mode/SHA metadata, changed file names a
The VPS component receives bounded health/process/app/browser state and **masked** infrastructure readiness. Provider values are those already sanitized by the infrastructure summary layer; raw credentials are never added for UI rendering.
-All four resources are self-contained: no external JavaScript, CSS, images, or direct `fetch()` calls. `Open in MSO` feature-detects the official ChatGPT `window.openai.openExternal` bridge, registers a contextual MSO deep-link with `window.openai.setOpenInAppUrl`, and shows a user-clickable `Open directly` fallback plus visible status when automatic navigation is unavailable. Workflow cards target `/assistant/mcp`, VPS cards `/monitor`, project cards `/files`, and diff cards `/code`. As a cache-safe fallback, a root MSO landing carrying ChatGPT's `redirectUrl=https://chatgpt.com/c/...` is server-redirected to `/assistant/mcp` while preserving the callback query; MSO never follows that callback itself. The widget CSP has no connect/resource domains and allowlists only `https://mso.rahmanef.com` as the dashboard redirect.
+All five resources are self-contained: no external JavaScript, CSS, images, or direct `fetch()` calls. `Open in MSO` feature-detects the official ChatGPT `window.openai.openExternal` bridge, registers a contextual MSO deep-link with `window.openai.setOpenInAppUrl`, and shows a user-clickable `Open directly` fallback plus visible status when automatic navigation is unavailable. Workflow cards target `/assistant/mcp`, VPS cards `/monitor`, project cards `/files`, and diff cards `/code`. As a cache-safe fallback, a root MSO landing carrying ChatGPT's `redirectUrl=https://chatgpt.com/c/...` is server-redirected to `/assistant/mcp` while preserving the callback query; MSO never follows that callback itself.
+
+The universal **MSO Surface** is intentionally stricter than the ordinary runtime-app/HTML widgets. `render_mso_surface` accepts only an MSO-style route plus optional project/SHA context — never raw HTML and never an arbitrary URL. Nested frames come from the code-owned `SURFACE_APPS` registry and are permitted only when the exact origin is also present in the resource's `ui.csp.frameDomains`. The browser-side renderer validates the returned app id and URL origin against the catalog bundled into the signed resource before setting `iframe.src`; dynamic labels use DOM `textContent`, not HTML interpolation. The iframe sandbox omits popup/top-navigation privileges. Apps that send `X-Frame-Options` or restrictive `frame-ancestors` remain `remote` and MSO does not strip those protections.
+
+Installed `runtime:"html"` apps and user-authored HTML widgets are **not** trusted inputs to the ChatGPT frame allowlist. They remain useful inside the authenticated MSO shell, but promoting one into `SURFACE_APPS` requires an explicit code review/release. This separation prevents a user-installed manifest or HTML snippet from escalating into a ChatGPT nested-frame CSP capability. Raw HTML snippets continue to run only in opaque-origin `srcDoc` sandboxes. The authenticated cockpit itself remains non-frameable; no change is made to its `frame-ancestors` or `X-Frame-Options` policy.
## Flow
@@ -60,14 +67,18 @@ ChatGPT model
├─ workflow_start ──→ workflow card ──→ workflow_status (app-only)
├─ project_get ──→ project card ──→ project_get refresh
├─ project_diff ──→ diff card
- └─ vps_status ──→ VPS card ──→ vps_status refresh
+ ├─ vps_status ──→ VPS card ──→ vps_status refresh
+ └─ render_mso_surface ─→ MSO Surface
+ ├─ native monitor/project/diff views
+ ├─ reviewed exact-origin live iframe app
+ └─ remote-browser fallback for anti-frame apps
Every entry tool also returns portable text/JSON for non-MCP-Apps clients.
```
## Dedicated UI origin
-All four templates declare `_meta.ui.domain = https://mso-ui.rahmanef.com` and the ChatGPT compatibility alias `_meta["openai/widgetDomain"]` with the same origin. The sibling hostname is intentional: the cockpit may scope its session cookie to `mso.rahmanef.com`, while `mso-ui.rahmanef.com` is outside that cookie domain. The dedicated origin therefore satisfies the plugin UI identity requirement without reusing the authenticated dashboard origin.
+All five templates declare `_meta.ui.domain = https://mso-ui.rahmanef.com` and the ChatGPT compatibility alias `_meta["openai/widgetDomain"]` with the same origin. The sibling hostname is intentional: the cockpit may scope its session cookie to `mso.rahmanef.com`, while `mso-ui.rahmanef.com` is outside that cookie domain. The dedicated origin therefore satisfies the plugin UI identity requirement without reusing the authenticated dashboard origin.
The reproducible Traefik route is stored in `ops/traefik/mso-ui.yml` and forwards only to the same local MSO service through the existing HTTPS/Let's Encrypt ingress. Widget CSP still allows no network/static-resource domains and only permits `Open in MSO` to redirect to `https://mso.rahmanef.com`.
@@ -78,6 +89,7 @@ Do not manually click through every model action. Cover the public contract with
| Journey | Suggested prompt/action | Pass condition |
| --- | --- | --- |
| Workflow/UI bridge | Start a read-only workflow for `mso`, press `Refresh`, then `Open in MSO` | progress updates; MSO opens visibly at Alfa → MCP Activity (`/assistant/mcp`), including when ChatGPT still uses a cached root-targeting widget; the explicit `Open directly` fallback targets the same view |
+| MSO Surface | Ask to render `/`, `/monitor`, then `/apps/antinrml-builder` | home/native view renders inline; reviewed builder appears as a nested live frame; fullscreen control is available; Baton/game remain remote and never enter `frameDomains` |
| VPS card | Ask for the current VPS status | `vps_status` renders CPU/memory/disk/apps/browser/infra and its refresh works |
| Project/Git | Ask to inspect project `mso`, then show its current diff/history | `project_get` and `project_diff` render the correct project/branch/changes without secrets |
| Safe filesystem CRUD | Create/read/copy/move/delete a disposable file under `~/mso-smoke-tests/` | content/hash round-trip succeeds and cleanup leaves no test file |
@@ -94,9 +106,9 @@ After a UI/schema release:
1. run `bun run verify` and a production build;
2. deploy through the normal MSO release path;
3. refresh/re-scan the ChatGPT development app so `initialize`, `tools/list`, and `resources/list` are read again;
-4. verify all 62 ChatGPT actions expose `outputSchema`; verify each UI entry tool also exposes `_meta.ui.resourceUri`;
+4. verify all 64 ChatGPT transport tools expose `outputSchema` (63 model actions + app-only `workflow_status`); verify each UI entry tool also exposes `_meta.ui.resourceUri`;
5. verify each `resources/read` returns `text/html;profile=mcp-app`;
-6. verify every UI resource reports `ui.domain=https://mso-ui.rahmanef.com`, refresh buttons work, and `workflow_status` polling does not enter learned workflow steps;
+6. verify every UI resource reports `ui.domain=https://mso-ui.rahmanef.com`; for the universal Surface verify `ui.csp.frameDomains` contains only reviewed iframe origins, refresh buttons work, and `workflow_status` polling does not enter learned workflow steps;
7. verify `skills/list`, `skills/get`, and each declared `skill://` resource/digest before the final Scan Tools refresh.
If ChatGPT still renders text only after a verified deployment, treat a stale app/action snapshot as the first suspect before changing the server again.
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 26c42967..e9683aa1 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -99,6 +99,8 @@ const MCP_ONLY: Record<string, string> = {
"project.agent.run": "project-agent execution wraps the durable MCP/terminal AgentSession subagent runtime; Alfa browser threads have a separate lifecycle and approval identity",
"project.agent.status": "status belongs to project-agent message ids owned by the external MCP principal/session; Alfa has no compatible project-agent task ledger",
"vps.status": "this is an aggregate MCP Apps operator card over existing bounded host/app/browser/infra primitives; Alfa already renders equivalent in-shell operational surfaces",
+ "mso.surface.apps.list": "the reviewed ChatGPT Surface demo catalog is MCP-App presentation metadata; Alfa already owns its in-shell app registry and must not inherit ChatGPT frame allowlists",
+ "render.mso.surface": "the universal MSO Surface is a ChatGPT MCP Apps presentation target; Alfa already is an MSO presentation target and does not render another copy of itself",
};
describe("Alfa ↔ MCP capability parity", () => {
diff --git a/lib/mcp/surface-catalog.test.ts b/lib/mcp/surface-catalog.test.ts
new file mode 100644
index 00000000..4c372102
--- /dev/null
+++ b/lib/mcp/surface-catalog.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+import { publicSurfaceApps, resolveSurfaceRoute, surfaceFrameDomains } from "./surface-catalog";
+import { MSO_SURFACE_SCRIPT } from "./ui-surface-script";
+import { OPEN_IN_MSO_SCRIPT } from "./ui-navigation";
+
+describe("MSO Surface trusted app catalog", () => {
+ it("allowlists only reviewed direct-frame origins", () => {
+ expect(surfaceFrameDomains()).toEqual(["https://builder-game.antinrml.com"]);
+ const apps = publicSurfaceApps();
+ expect(apps.find((app) => app.id === "antinrml-builder")?.renderer).toBe("iframe");
+ expect(apps.find((app) => app.id === "baton")?.renderer).toBe("remote");
+ expect(apps.find((app) => app.id === "antinrml-game")?.renderer).toBe("remote");
+ expect(JSON.stringify(apps)).not.toContain("sandbox");
+ });
+
+ it("rejects arbitrary URLs, protocol-relative routes and traversal", () => {
+ for (const route of [
+ "https://evil.example/app",
+ "//evil.example/app",
+ "/apps/unknown",
+ "/apps/antinrml-builder/../admin",
+ "/apps/antinrml-builder/%2e%2e/admin",
+ "/apps/antinrml-builder\\evil",
+ ]) {
+ expect(() => resolveSurfaceRoute(route), route).toThrow();
+ }
+ });
+
+ it("keeps direct demo paths on the exact reviewed origin", () => {
+ const surface = resolveSurfaceRoute("/apps/antinrml-builder/rooms/demo?mode=guest");
+ expect(surface).toMatchObject({ kind: "app", title: "AntiNRML Builder" });
+ expect(surface.app?.renderer).toBe("iframe");
+ const url = new URL(surface.app!.url);
+ expect(url.origin).toBe("https://builder-game.antinrml.com");
+ expect(url.pathname).toBe("/rooms/demo");
+ expect(url.searchParams.get("mode")).toBe("guest");
+ });
+
+ it("ships syntactically valid browser code with no dynamic HTML sink", () => {
+ expect(() => new Function(`${OPEN_IN_MSO_SCRIPT}\n${MSO_SURFACE_SCRIPT}`)).not.toThrow();
+ expect(MSO_SURFACE_SCRIPT).not.toContain("innerHTML");
+ expect(MSO_SURFACE_SCRIPT).not.toContain("insertAdjacentHTML");
+ expect(MSO_SURFACE_SCRIPT).not.toContain("document.write");
+ expect(MSO_SURFACE_SCRIPT).toContain("url.origin!==safe.origin");
+ });
+
+ it("preserves anti-framing apps as remote surfaces", () => {
+ const baton = resolveSurfaceRoute("/apps/baton");
+ expect(baton.app).toMatchObject({ id: "baton", renderer: "remote", origin: "https://baton.rahmanef.com" });
+ expect(baton.openPath).toBe("/browser");
+ });
+});
diff --git a/lib/mcp/surface-catalog.ts b/lib/mcp/surface-catalog.ts
new file mode 100644
index 00000000..23ec2241
--- /dev/null
+++ b/lib/mcp/surface-catalog.ts
@@ -0,0 +1,122 @@
+export type SurfaceRenderer = "iframe" | "remote";
+export type SurfacePresentation = "inline" | "fullscreen" | "pip";
+
+export type SurfaceApp = {
+ id: string;
+ title: string;
+ description: string;
+ origin: string;
+ startPath: string;
+ renderer: SurfaceRenderer;
+ presentation: SurfacePresentation;
+ sandbox?: string;
+ reason?: string;
+};
+
+// This is deliberately code-owned rather than model/user-provided. Every nested
+// frame origin becomes part of the MCP Apps CSP and therefore deserves review.
+// Apps that deny framing remain useful through the remote-browser seam instead of
+// having their X-Frame-Options/frame-ancestors stripped by MSO.
+export const SURFACE_APPS: readonly SurfaceApp[] = [
+ {
+ id: "antinrml-builder",
+ title: "AntiNRML Builder",
+ description: "Live AntiNRML builder demo rendered directly inside the ChatGPT MSO Surface.",
+ origin: "https://builder-game.antinrml.com",
+ startPath: "/",
+ renderer: "iframe",
+ presentation: "fullscreen",
+ sandbox: "allow-scripts allow-same-origin allow-forms allow-pointer-lock",
+ },
+ {
+ id: "baton",
+ title: "Baton",
+ description: "Baton app demo. Its production origin currently denies framing, so MSO keeps it on the remote-browser path.",
+ origin: "https://baton.rahmanef.com",
+ startPath: "/os?view=home",
+ renderer: "remote",
+ presentation: "fullscreen",
+ reason: "The app sends X-Frame-Options: DENY; MSO does not strip application frame protections.",
+ },
+ {
+ id: "antinrml-game",
+ title: "AntiNRML Game",
+ description: "AntiNRML game surface. The current deployment permits only same-origin framing, so it uses the remote-browser seam.",
+ origin: "https://game.rahmanef.com",
+ startPath: "/",
+ renderer: "remote",
+ presentation: "pip",
+ reason: "The app CSP currently declares frame-ancestors 'self'.",
+ },
+] as const;
+
+const ROUTE_MAX = 1024;
+const BASE = "https://mso-surface.invalid";
+
+export type ResolvedSurface = {
+ route: string;
+ kind: "home" | "monitor" | "project" | "diff" | "browser" | "app";
+ title: string;
+ openPath: string;
+ project?: string;
+ sha?: string;
+ app?: SurfaceApp & { url: string };
+};
+
+export function publicSurfaceApps(): Array<Omit<SurfaceApp, "sandbox">> {
+ return SURFACE_APPS.map(({ sandbox: _sandbox, ...app }) => ({ ...app }));
+}
+
+export function surfaceFrameDomains(): string[] {
+ return [...new Set(SURFACE_APPS.filter((app) => app.renderer === "iframe").map((app) => app.origin))];
+}
+
+export function surfaceAppById(id: string): SurfaceApp | undefined {
+ return SURFACE_APPS.find((app) => app.id === id);
+}
+
+function cleanRoute(raw: string): URL {
+ if (!raw || raw.length > ROUTE_MAX || !raw.startsWith("/") || raw.startsWith("//") || /[\\\u0000-\u001f]/.test(raw)) {
+ throw new Error("surface route must be a bounded absolute MSO-style path");
+ }
+ const url = new URL(raw, BASE);
+ if (url.origin !== BASE) throw new Error("surface route cannot change origin");
+ return url;
+}
+
+function safeDemoUrl(app: SurfaceApp, suffix: string, search: string): string {
+ const path = suffix ? `/${suffix}` : app.startPath;
+ if (path.length > 768 || /[\\\u0000-\u001f]/.test(path) || path.split("/").some((part) => part === "." || part === "..")) {
+ throw new Error("invalid demo path");
+ }
+ const url = new URL(suffix ? `${path}${search}` : app.startPath, app.origin);
+ if (url.origin !== app.origin || url.username || url.password || url.protocol !== "https:") throw new Error("demo URL escaped its trusted origin");
+ return url.href;
+}
+
+export function resolveSurfaceRoute(rawRoute: string, context?: { project?: string; sha?: string }): ResolvedSurface {
+ const url = cleanRoute(rawRoute);
+ const decoded = decodeURIComponent(url.pathname);
+ const parts = decoded.split("/").filter(Boolean);
+ const route = `${url.pathname}${url.search}`;
+
+ if (parts.length === 0) return { route, kind: "home", title: "MSO", openPath: "/assistant/mcp" };
+ if (parts[0] === "monitor" && parts.length === 1) return { route, kind: "monitor", title: "System Monitor", openPath: "/monitor" };
+ if (parts[0] === "browser" && parts.length === 1) return { route, kind: "browser", title: "Remote Browser", openPath: "/browser" };
+ if (parts[0] === "project" && parts.length === 1) return { route, kind: "project", title: "Project", openPath: "/files", ...(context?.project ? { project: context.project } : {}) };
+ if (parts[0] === "diff" && parts.length === 1) return { route, kind: "diff", title: "Project Diff", openPath: "/code", ...(context?.project ? { project: context.project } : {}), ...(context?.sha ? { sha: context.sha } : {}) };
+
+ if (parts[0] === "apps" && parts[1]) {
+ const app = surfaceAppById(parts[1]);
+ if (!app) throw new Error(`unknown MSO Surface app: ${parts[1]}`);
+ const suffix = parts.slice(2).join("/");
+ return {
+ route,
+ kind: "app",
+ title: app.title,
+ openPath: app.renderer === "remote" ? "/browser" : "/assistant/mcp",
+ app: { ...app, url: safeDemoUrl(app, suffix, url.search) },
+ };
+ }
+ throw new Error(`unsupported MSO Surface route: ${url.pathname}`);
+}
diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.ts
index fe5c9197..1dc90fc8 100644
--- a/lib/mcp/tool-contract.ts
+++ b/lib/mcp/tool-contract.ts
@@ -48,7 +48,7 @@ export const CHATGPT_TOOL_NAMES = new Set([
"project_database_status", "project_database_tools", "project_database_call", "project_database_query",
// Original MSO bounded VPS/file/application/browser power restored to ChatGPT.
- "vps_status", "screen_capture", "fs_list", "fs_read", "fs_search", "fs_usage",
+ "vps_status", "mso_surface_apps_list", "render_mso_surface", "screen_capture", "fs_list", "fs_read", "fs_search", "fs_usage",
"fs_write", "fs_upload_file", "fs_mkdir", "fs_move", "fs_copy", "fs_delete",
"sys_stats", "sys_processes", "apps_list", "apps_logs", "apps_power", "browser_status", "browser_power",
diff --git a/lib/mcp/tools-surface.test.ts b/lib/mcp/tools-surface.test.ts
new file mode 100644
index 00000000..afed429a
--- /dev/null
+++ b/lib/mcp/tools-surface.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { SURFACE_TOOLS } from "./tools-surface";
+
+const tool = (name: string) => {
+ const value = SURFACE_TOOLS.find((row) => row.name === name);
+ if (!value) throw new Error(`missing ${name}`);
+ return value;
+};
+
+describe("MSO Surface MCP tools", () => {
+ it("returns only the server-reviewed public app catalog", async () => {
+ const result = await tool("mso_surface_apps_list").run({}, { scope: "read" }) as { apps: Array<Record<string, unknown>> };
+ expect(result.apps.map((app) => app.id)).toEqual(["antinrml-builder", "baton", "antinrml-game"]);
+ expect(JSON.stringify(result)).not.toContain("sandbox");
+ expect(JSON.stringify(result)).not.toContain("<script");
+ });
+
+ it("renders a direct app without accepting a URL argument", async () => {
+ const render = tool("render_mso_surface");
+ expect(render.inputSchema.properties).not.toHaveProperty("url");
+ expect(render.inputSchema.properties).not.toHaveProperty("html");
+ const result = await render.run({ route: "/apps/antinrml-builder" }, { scope: "read" }) as { app?: Record<string, unknown> };
+ expect(result.app).toMatchObject({ id: "antinrml-builder", renderer: "iframe", origin: "https://builder-game.antinrml.com" });
+ expect(result.app).not.toHaveProperty("sandbox");
+ });
+
+ it("keeps project identity separate from the route string", async () => {
+ const result = await tool("render_mso_surface").run({ route: "/project", project: "mso" }, { scope: "read" });
+ expect(result).toMatchObject({ route: "/project", kind: "project", project: "mso", openPath: "/files" });
+ });
+});
diff --git a/lib/mcp/tools-surface.ts b/lib/mcp/tools-surface.ts
new file mode 100644
index 00000000..0cb714ad
--- /dev/null
+++ b/lib/mcp/tools-surface.ts
@@ -0,0 +1,69 @@
+import { type McpTool, S, str, opt, READ_ONLY } from "./tool-kit";
+import { MSO_SURFACE_URI } from "./ui-surface";
+import { publicSurfaceApps, resolveSurfaceRoute, type ResolvedSurface } from "./surface-catalog";
+
+const APP_SCHEMA = {
+ type: "object",
+ properties: {
+ id: { type: "string" }, title: { type: "string" }, description: { type: "string" }, origin: { type: "string" },
+ startPath: { type: "string" }, renderer: { type: "string", enum: ["iframe", "remote"] },
+ presentation: { type: "string", enum: ["inline", "fullscreen", "pip"] }, reason: { type: "string" },
+ },
+ required: ["id", "title", "description", "origin", "startPath", "renderer", "presentation"],
+ additionalProperties: false,
+} as const;
+
+const SURFACE_OUTPUT = {
+ type: "object",
+ properties: {
+ route: { type: "string" }, kind: { type: "string", enum: ["home", "monitor", "project", "diff", "browser", "app"] },
+ title: { type: "string" }, openPath: { type: "string" }, project: { type: "string" }, sha: { type: "string" },
+ app: { type: "object" }, catalog: { type: "array", items: APP_SCHEMA },
+ },
+ required: ["route", "kind", "title", "openPath", "catalog"],
+ additionalProperties: false,
+} as const;
+
+function publicResolved(resolved: ResolvedSurface): Record<string, unknown> {
+ const { app, ...rest } = resolved;
+ if (!app) return rest;
+ const { sandbox: _sandbox, ...safeApp } = app;
+ return { ...rest, app: safeApp };
+}
+
+export const SURFACE_TOOLS: McpTool[] = [
+ {
+ name: "mso_surface_apps_list",
+ title: "List MSO Surface Apps",
+ description: "List the small server-owned catalog of apps that MSO may present inside the ChatGPT MSO Surface. The model cannot add URLs or HTML to this catalog. Apps marked iframe have a reviewed exact frame origin; remote means the app keeps its own anti-framing policy and MSO will not strip it.",
+ chatgptDescription: "List reviewed apps available to the ChatGPT MSO Surface, including whether each can be framed directly or must use the remote-browser seam.",
+ scope: "read", annotations: READ_ONLY,
+ inputSchema: S({}),
+ outputSchema: { type: "object", properties: { apps: { type: "array", items: APP_SCHEMA } }, required: ["apps"], additionalProperties: false },
+ run: async () => ({ apps: publicSurfaceApps() }),
+ },
+ {
+ name: "render_mso_surface",
+ title: "Render MSO Surface",
+ description: "Render the universal MSO Surface MCP App. Use an MSO-style route such as /, /monitor, /project, /diff, /browser, or /apps/<reviewed-app-id>. For project/diff views pass project separately. This tool never accepts raw HTML or arbitrary external URLs; demo origins are resolved only from the server-owned allowlist.",
+ chatgptDescription: "Render a secure interactive MSO Surface in ChatGPT. Route examples: /, /monitor, /project, /diff, /browser, /apps/antinrml-builder. No arbitrary HTML/URL input is accepted.",
+ scope: "read", annotations: READ_ONLY,
+ inputSchema: S({
+ route: { type: "string", minLength: 1, maxLength: 1024, description: "MSO Surface route. External URLs are rejected." },
+ project: { type: "string", description: "Project id/path/name for /project or /diff." },
+ sha: { type: "string", description: "Optional commit SHA for /diff." },
+ }, ["route"]),
+ outputSchema: SURFACE_OUTPUT,
+ meta: {
+ ui: { resourceUri: MSO_SURFACE_URI, visibility: ["model", "app"] },
+ "openai/outputTemplate": MSO_SURFACE_URI,
+ "openai/toolInvocation/invoking": "Opening MSO Surface…",
+ "openai/toolInvocation/invoked": "MSO Surface opened",
+ "openai/widgetAccessible": true,
+ },
+ run: async (a) => ({
+ ...publicResolved(resolveSurfaceRoute(str(a, "route"), { project: opt(a, "project"), sha: opt(a, "sha") })),
+ catalog: publicSurfaceApps(),
+ }),
+ },
+];
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 96fd6c8a..643c8ac4 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -17,6 +17,7 @@ import { READ_PIPELINE_TOOLS } from "./tools-read-pipeline";
import { PROJECT_MCP_TOOLS } from "./tools-project-mcp";
import { PROJECT_EXPERIENCE_TOOLS } from "./tools-project-experience";
import { OPERATOR_DASHBOARD_TOOLS } from "./tools-operator-dashboard";
+import { SURFACE_TOOLS } from "./tools-surface";
import { withWorkflowContext } from "./tool-context";
// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,
@@ -226,4 +227,4 @@ const MUTATE_TOOLS: McpTool[] = [
},
];
-export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
+export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 8937e71f..bf9d0a06 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -3,9 +3,9 @@ import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
import { toolDescriptor, type McpToolProfile } from "./tool-contract";
-export const MCP_SERVER_VERSION = "1.8.2";
-export const MCP_TOOLSET_VERSION = "2026.09.03.7";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-03T14:51:00Z";
+export const MCP_SERVER_VERSION = "1.9.0";
+export const MCP_TOOLSET_VERSION = "2026.09.04.1";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-03T17:55:43Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/mcp/ui-config.ts b/lib/mcp/ui-config.ts
index 2c3ee972..8e07f130 100644
--- a/lib/mcp/ui-config.ts
+++ b/lib/mcp/ui-config.ts
@@ -3,12 +3,19 @@ export const MSO_ORIGIN = "https://mso.rahmanef.com";
// below mso.rahmanef.com, whose session cookie may be scoped to that hostname.
export const MCP_UI_DOMAIN = "https://mso-ui.rahmanef.com";
-export function widgetResourceMeta(description: string): Record<string, unknown> {
+export function widgetResourceMeta(description: string, options?: { frameDomains?: readonly string[]; connectDomains?: readonly string[]; resourceDomains?: readonly string[] }): Record<string, unknown> {
+ const frameDomains = [...(options?.frameDomains ?? [])];
+ const connectDomains = [...(options?.connectDomains ?? [])];
+ const resourceDomains = [...(options?.resourceDomains ?? [])];
return {
- ui: { domain: MCP_UI_DOMAIN, prefersBorder: true, csp: { connectDomains: [], resourceDomains: [] } },
+ ui: {
+ domain: MCP_UI_DOMAIN,
+ prefersBorder: true,
+ csp: { connectDomains, resourceDomains, ...(frameDomains.length ? { frameDomains } : {}) },
+ },
"openai/widgetDescription": description,
"openai/widgetPrefersBorder": true,
"openai/widgetDomain": MCP_UI_DOMAIN,
- "openai/widgetCSP": { connect_domains: [], resource_domains: [], redirect_domains: [MSO_ORIGIN] },
+ "openai/widgetCSP": { connect_domains: connectDomains, resource_domains: resourceDomains, ...(frameDomains.length ? { frame_domains: frameDomains } : {}), redirect_domains: [MSO_ORIGIN] },
};
}
diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.ts
index 9e95ee4c..8f495755 100644
--- a/lib/mcp/ui-resources.test.ts
+++ b/lib/mcp/ui-resources.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
const { dispatch } = await import("./dispatch");
-const { MCP_APP_MIME_TYPE, WORKFLOW_PROGRESS_URI, PROJECT_STATUS_URI, DIFF_VIEW_URI, VPS_STATUS_URI, readUiResource } = await import("./ui-resources");
+const { MCP_APP_MIME_TYPE, WORKFLOW_PROGRESS_URI, PROJECT_STATUS_URI, DIFF_VIEW_URI, VPS_STATUS_URI, MSO_SURFACE_URI, readUiResource } = await import("./ui-resources");
const { MCP_UI_DOMAIN } = await import("./ui-config");
const { activeWorkflowForActor } = await import("@/lib/workflow");
@@ -40,17 +40,26 @@ describe("MCP Apps workflow progress UI", () => {
expect(tool?.outputSchema, name).toBeDefined();
expect(tool?._meta, name).toMatchObject({ ui: { resourceUri: uri, visibility: ["model", "app"] }, "openai/outputTemplate": uri });
}
+
+ const surface = tools.find((row) => row.name === "render_mso_surface");
+ expect(surface?.outputSchema).toBeDefined();
+ expect(surface?._meta).toMatchObject({
+ ui: { resourceUri: MSO_SURFACE_URI, visibility: ["model", "app"] },
+ "openai/outputTemplate": MSO_SURFACE_URI,
+ "openai/widgetAccessible": true,
+ });
});
it("serves one self-contained mcp-app resource", async () => {
const listed = await dispatch({ id: 1, method: "resources/list" }, "read", "mcp:ui-resource");
const resources = (listed.result as { resources: Array<{ uri: string; mimeType: string }> }).resources;
- expect(resources).toHaveLength(4);
+ expect(resources).toHaveLength(5);
expect(resources).toEqual(expect.arrayContaining([
expect.objectContaining({ uri: WORKFLOW_PROGRESS_URI, mimeType: MCP_APP_MIME_TYPE }),
expect.objectContaining({ uri: PROJECT_STATUS_URI, mimeType: MCP_APP_MIME_TYPE }),
expect.objectContaining({ uri: DIFF_VIEW_URI, mimeType: MCP_APP_MIME_TYPE }),
expect.objectContaining({ uri: VPS_STATUS_URI, mimeType: MCP_APP_MIME_TYPE }),
+ expect.objectContaining({ uri: MSO_SURFACE_URI, mimeType: MCP_APP_MIME_TYPE }),
]));
const read = await dispatch({ id: 2, method: "resources/read", params: { uri: WORKFLOW_PROGRESS_URI } }, "read", "mcp:ui-resource");
@@ -140,6 +149,33 @@ describe("MCP Apps workflow progress UI", () => {
expect(content._meta).toMatchObject({ ui: { domain: MCP_UI_DOMAIN, prefersBorder: true }, "openai/widgetDomain": MCP_UI_DOMAIN, "openai/widgetPrefersBorder": true });
}
});
+ it("serves the universal MSO Surface with a minimal nested-frame allowlist", async () => {
+ const read = await dispatch({ id: 30, method: "resources/read", params: { uri: MSO_SURFACE_URI } }, "read", "mcp:ui-surface");
+ const content = (read.result as { contents: Array<{ mimeType: string; text: string; _meta: Record<string, any> }> }).contents[0];
+ expect(content.mimeType).toBe(MCP_APP_MIME_TYPE);
+ expect(content.text).toContain("requestDisplayMode");
+ expect(content.text).toContain("setWidgetState");
+ expect(content.text).toContain("render_mso_surface");
+ expect(content.text).toContain("https://builder-game.antinrml.com");
+ expect(content.text).toContain("https://baton.rahmanef.com");
+ expect(content.text).not.toContain("fetch(");
+ expect(content.text).not.toContain("allow-popups");
+ expect(content.text).not.toContain("allow-top-navigation");
+ expect(content.text).not.toContain("dangerouslySetInnerHTML");
+ expect(content._meta.ui.csp).toMatchObject({
+ connectDomains: [],
+ resourceDomains: [],
+ frameDomains: ["https://builder-game.antinrml.com"],
+ });
+ expect(content._meta["openai/widgetCSP"]).toMatchObject({
+ connect_domains: [],
+ resource_domains: [],
+ frame_domains: ["https://builder-game.antinrml.com"],
+ });
+ expect(content._meta.ui.csp.frameDomains).not.toContain("https://baton.rahmanef.com");
+ expect(MSO_SURFACE_URI).toContain("surface-v1.html");
+ });
+
it("gives every MCP App a visible contextual MSO destination", () => {
expect(readUiResource(WORKFLOW_PROGRESS_URI)?.text).toContain('data-mso-path="/assistant/mcp"');
expect(readUiResource(PROJECT_STATUS_URI)?.text).toContain('data-mso-path="/files"');
diff --git a/lib/mcp/ui-resources.ts b/lib/mcp/ui-resources.ts
index 88e4ae89..edb7968e 100644
--- a/lib/mcp/ui-resources.ts
+++ b/lib/mcp/ui-resources.ts
@@ -1,7 +1,9 @@
+import { MSO_SURFACE_RESOURCE } from "./ui-surface";
import { OPERATOR_UI_RESOURCES } from "./ui-operator-resources";
import { widgetResourceMeta } from "./ui-config";
import { OPEN_IN_MSO_SCRIPT, openInMsoControls } from "./ui-navigation";
export { PROJECT_STATUS_URI, DIFF_VIEW_URI, VPS_STATUS_URI } from "./ui-operator-resources";
+export { MSO_SURFACE_URI } from "./ui-surface";
export const WORKFLOW_PROGRESS_URI = "ui://mso/workflow-progress-v2.html";
export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
@@ -224,6 +226,7 @@ const RESOURCES: readonly McpUiResource[] = [
_meta: workflowResourceMeta(),
},
...OPERATOR_UI_RESOURCES,
+ MSO_SURFACE_RESOURCE,
];
export function listUiResources() {
diff --git a/lib/mcp/ui-surface-script.ts b/lib/mcp/ui-surface-script.ts
new file mode 100644
index 00000000..c9964d2b
--- /dev/null
+++ b/lib/mcp/ui-surface-script.ts
@@ -0,0 +1,96 @@
+import { SURFACE_APPS } from "./surface-catalog";
+
+function safeJson(value: unknown): string {
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
+}
+
+const BROWSER_CATALOG = SURFACE_APPS.map((app) => ({
+ id: app.id,
+ title: app.title,
+ description: app.description,
+ origin: app.origin,
+ startPath: app.startPath,
+ renderer: app.renderer,
+ presentation: app.presentation,
+ sandbox: app.sandbox ?? "",
+ reason: app.reason ?? "",
+}));
+
+export const MSO_SURFACE_SCRIPT = String.raw`
+const SAFE_APPS=${safeJson(BROWSER_CATALOG)};
+const SAFE_BY_ID=new Map(SAFE_APPS.map(app=>[app.id,app]));
+const $=id=>document.getElementById(id);
+const body=$("surface-body"), titleEl=$("surface-title"), routeEl=$("surface-route"), modeEl=$("surface-mode");
+const fsBtn=$("surface-fullscreen"), pipBtn=$("surface-pip"), homeBtn=$("surface-home");
+let current={route:"/",kind:"home",title:"MSO",openPath:"/assistant/mcp",catalog:[]};
+const pending=new Map();let nextRpcId=5000;
+
+function text(value,fallback="—"){return typeof value==="string"&&value.trim()?value.trim():fallback}
+function clear(node){while(node.firstChild)node.removeChild(node.firstChild)}
+function el(tag,className,value){const node=document.createElement(tag);if(className)node.className=className;if(value!==undefined)node.textContent=String(value);return node}
+function button(label,onClick,className=""){const node=el("button",className,label);node.type="button";node.addEventListener("click",onClick);return node}
+function validRoute(route){return typeof route==="string"&&route.startsWith("/")&&!route.startsWith("//")&&route.length<=1024&&!/[\\\u0000-\u001f]/.test(route)}
+function safeAppResult(raw){
+ if(!raw||typeof raw!=="object")return null;
+ const id=text(raw.id,"");const safe=SAFE_BY_ID.get(id);if(!safe)return null;
+ let url;try{url=new URL(text(raw.url,""))}catch{return null}
+ if(url.protocol!=="https:"||url.origin!==safe.origin||url.username||url.password)return null;
+ return {...safe,url:url.href};
+}
+function openPath(path){setMsoTarget(validRoute(path)?path:"/assistant/mcp")}
+function applyHostGlobals(){
+ const api=window.openai||{};
+ const max=Number(api.maxHeight);document.documentElement.style.setProperty("--host-max-h",Number.isFinite(max)&&max>180?Math.floor(max)+"px":"680px");
+ const safe=api.safeArea||{};for(const [key,value] of [["top",safe.top],["right",safe.right],["bottom",safe.bottom],["left",safe.left]]){const n=Number(value);document.documentElement.style.setProperty("--safe-"+key,Number.isFinite(n)?Math.max(0,n)+"px":"0px")}
+ modeEl.textContent=text(api.displayMode,"inline");
+}
+async function displayMode(mode){
+ try{if(!window.openai||typeof window.openai.requestDisplayMode!=="function")throw new Error("unsupported");await window.openai.requestDisplayMode({mode})}catch(_){modeEl.textContent=mode+" unavailable"}
+}
+function persistRoute(){
+ try{if(window.openai&&typeof window.openai.setWidgetState==="function")window.openai.setWidgetState({modelContent:"MSO Surface: "+current.route,privateContent:{route:current.route},imageIds:[]})}catch(_){}
+}
+function rpcCall(name,args){
+ if(window.openai&&typeof window.openai.callTool==="function")return window.openai.callTool(name,args);
+ const id=nextRpcId++;window.parent.postMessage({jsonrpc:"2.0",id,method:"tools/call",params:{name,arguments:args}},"*");
+ return new Promise((resolve,reject)=>{pending.set(id,{resolve,reject});setTimeout(()=>{if(pending.has(id)){pending.delete(id);reject(new Error("tool timeout"))}},10000)})
+}
+function unbox(result){return result&&result.structuredContent?result.structuredContent:result}
+function nav(route,extra={}){
+ if(!validRoute(route))return;
+ current={route,kind:route==="/"?"home":"loading",title:"MSO",openPath:"/assistant/mcp",catalog:current.catalog,...extra};render();
+ if(route==="/")return;
+ rpcCall("render_mso_surface",{route,...(extra.project?{project:extra.project}:{}),...(extra.sha?{sha:extra.sha}:{})}).then(result=>{const value=unbox(result);if(value&&typeof value==="object"){current=value;render()}}).catch(showError)
+}
+function showError(error){clear(body);const box=el("div","notice");const inner=el("div");inner.append(el("h3","","Surface unavailable"),el("p","error",error&&error.message?error.message:"The requested surface could not be loaded."));box.append(inner);body.append(box)}
+function renderHome(){
+ const root=el("div","home");const hero=el("section","hero");hero.append(el("h2","","MSO Surface"),el("p","","ChatGPT is another MSO presentation target. Open a native operator view or a reviewed live demo without leaving the conversation."));root.append(hero);
+ root.append(el("div","section-title","Native surfaces"));const native=el("div","grid");
+ for(const item of [{route:"/monitor",title:"System Monitor",desc:"Live bounded host status."},{route:"/project",title:"Project",desc:"Project snapshot and Git state."},{route:"/diff",title:"Diff",desc:"Review project changes."},{route:"/browser",title:"Remote Browser",desc:"Fallback seam for sites that deny framing."}]){const card=button("",()=>nav(item.route),"card");card.append(el("strong","",item.title),el("span","",item.desc));native.append(card)}root.append(native);
+ root.append(el("div","section-title","Reviewed app demos"));const apps=el("div","grid");
+ for(const app of SAFE_APPS){const card=button("",()=>nav("/apps/"+encodeURIComponent(app.id)),"card");card.append(el("strong","",app.title),el("span","",app.description),el("span","tag",app.renderer));apps.append(card)}root.append(apps);body.append(root)
+}
+function renderMonitor(){
+ const stage=stageBase("Live bounded VPS status");const metrics=el("div","metrics");for(const name of ["CPU","Memory","Disk"]){const m=el("div","metric");m.append(el("span","",name),el("strong","","…"));metrics.append(m)}stage.content.append(metrics);const list=el("div","list");stage.content.append(list);body.append(stage.root);
+ rpcCall("vps_status",{}).then(raw=>{const v=unbox(raw)||{},h=v.health||{},apps=Array.isArray(v.apps)?v.apps:[],browser=v.browser||{};const nodes=metrics.querySelectorAll("strong");nodes[0].textContent=String(h.cpuPercent??h.cpu??"—");nodes[1].textContent=String(h.memory?.percentUsed??h.memoryPercent??"—");nodes[2].textContent=String(h.disk?.percentUsed??h.diskPercent??"—");for(const [label,value] of [["Managed apps",apps.length],["Browser",browser.running?"running":"stopped"],["Infrastructure",Array.isArray(v.infrastructure)?v.infrastructure.filter(x=>x&&x.configured).length+" configured":"—"]]){const row=el("div","line");row.append(el("span","",label),el("strong","",value));list.append(row)}}).catch(showError)
+}
+function renderProject(kind){
+ const project=text(current.project,"");if(!project){renderProjectPrompt(kind);return}const stage=stageBase(kind==="diff"?"Project diff":"Project status");const list=el("div","list");stage.content.append(list);body.append(stage.root);
+ const tool=kind==="diff"?"project_diff":"project_get";const args={project,...(kind==="diff"&&current.sha?{sha:current.sha}:{})};rpcCall(tool,args).then(raw=>{const v=unbox(raw)||{};if(kind==="project"){const p=v.project||{},g=v.git||{},pkg=v.package||{};for(const [label,value] of [["Project",p.name||project],["Branch",g.branch],["HEAD",g.head?.sha?String(g.head.sha).slice(0,12):"—"],["Package",[pkg.name,pkg.version].filter(Boolean).join(" · ")||"—"],["Working tree",g.clean===true?"clean":g.clean===false?"changed":"—"]])appendLine(list,label,value)}else{const s=v.summary||{};for(const [label,value] of [["Project",v.project?.name||project],["Files",s.files??"—"],["Additions",s.additions??"—"],["Deletions",s.deletions??"—"],["Mode",v.mode??"—"]])appendLine(list,label,value)}}).catch(showError)
+}
+function renderProjectPrompt(kind){const box=el("div","notice");const inner=el("div");inner.append(el("h3","",kind==="diff"?"Choose a project in chat":"Project context needed"),el("p","","Ask ChatGPT to render this surface with a project id/name. The widget does not guess filesystem paths or enumerate private projects on its own."));box.append(inner);body.append(box)}
+function appendLine(list,label,value){const row=el("div","line");row.append(el("span","",label),el("strong","mono",value==null?"—":value));list.append(row)}
+function stageBase(subtitle){const root=el("div","stage"),head=el("div","stage-head"),content=el("div");head.append(button("←",()=>nav("/"),"back"));const t=el("div","stage-title");t.append(el("strong","",current.title),el("span","",subtitle));head.append(t);root.append(head,content);return{root,content}}
+function renderApp(){
+ const raw=current.app,safe=safeAppResult(raw);if(!safe){showError(new Error("The app result is not in the reviewed MSO Surface registry."));return}const stage=stageBase(safe.renderer==="iframe"?"Live app demo":"Remote-browser fallback");body.append(stage.root);openPath(safe.renderer==="remote"?"/browser":"/assistant/mcp");
+ if(safe.renderer==="iframe"){const wrap=el("div","frame-wrap"),frame=document.createElement("iframe");frame.title=safe.title+" live demo";frame.src=safe.url;frame.setAttribute("sandbox",safe.sandbox);frame.referrerPolicy="no-referrer";frame.allow="fullscreen";wrap.append(frame);stage.content.append(wrap);return}
+ const box=el("div","notice"),inner=el("div");inner.append(el("h3","",safe.title+" protects itself from framing"),el("p","",safe.reason||"This app is not allowlisted for nested framing. MSO preserves the app's own frame policy instead of stripping it."));const row=el("div","row");row.append(button("Open Remote Browser",()=>openMso(),"primary"));if(window.openai&&typeof window.openai.sendFollowUpMessage==="function")row.append(button("Ask ChatGPT to continue",()=>window.openai.sendFollowUpMessage({prompt:"Continue this demo using the MSO remote-browser fallback for "+safe.title+"."})));inner.append(row);box.append(inner);stage.content.append(box);if(safe.presentation==="pip")pipBtn.hidden=false
+}
+function renderBrowser(){const box=el("div","notice"),inner=el("div");inner.append(el("h3","","Remote Browser seam"),el("p","","Sites that deny iframe embedding stay isolated. MSO can continue them through Camoufox without exposing its VNC password or authenticated viewer URL to this widget."));const row=el("div","row");row.append(button("Open MSO Browser",()=>openMso(),"primary"));inner.append(row);box.append(inner);body.append(box);openPath("/browser")}
+function render(){clear(body);titleEl.textContent=text(current.title,"MSO Surface");routeEl.textContent=text(current.route,"/");openPath(text(current.openPath,"/assistant/mcp"));persistRoute();if(current.kind==="home")renderHome();else if(current.kind==="monitor")renderMonitor();else if(current.kind==="project")renderProject("project");else if(current.kind==="diff")renderProject("diff");else if(current.kind==="app")renderApp();else if(current.kind==="browser")renderBrowser();else body.append(el("div","loading","Loading MSO Surface…"))}
+function readOutput(){const value=window.openai&&window.openai.toolOutput;if(value&&typeof value==="object"){current=value;render()}}
+window.addEventListener("message",event=>{if(event.source!==window.parent)return;const msg=event.data;if(!msg||msg.jsonrpc!=="2.0")return;if(msg.id!==undefined&&pending.has(msg.id)){const req=pending.get(msg.id);pending.delete(msg.id);msg.error?req.reject(msg.error):req.resolve(msg.result);return}if(msg.method==="ui/notifications/tool-result"&&msg.params&&msg.params.structuredContent){current=msg.params.structuredContent;render()}},{passive:true});
+window.addEventListener("openai:set_globals",()=>{applyHostGlobals();readOutput()},{passive:true});
+fsBtn.addEventListener("click",()=>displayMode("fullscreen"));pipBtn.addEventListener("click",()=>displayMode("pip"));homeBtn.addEventListener("click",()=>nav("/"));
+applyHostGlobals();readOutput();render();
+`;
diff --git a/lib/mcp/ui-surface-style.ts b/lib/mcp/ui-surface-style.ts
new file mode 100644
index 00000000..e2ccb0c2
--- /dev/null
+++ b/lib/mcp/ui-surface-style.ts
@@ -0,0 +1,5 @@
+export const MSO_SURFACE_STYLE = String.raw`
+:root{color-scheme:light dark;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;--line:color-mix(in srgb,CanvasText 13%,transparent);--muted:color-mix(in srgb,CanvasText 58%,transparent);--soft:color-mix(in srgb,CanvasText 5%,Canvas);--accent:#7c3aed;--safe-top:0px;--safe-right:0px;--safe-bottom:0px;--safe-left:0px;--host-max-h:680px}*{box-sizing:border-box}html,body{margin:0;min-width:0;background:transparent;color:CanvasText}body{padding:8px}.surface{display:flex;min-height:260px;max-height:min(var(--host-max-h),78vh);overflow:hidden;flex-direction:column;border:1px solid var(--line);border-radius:18px;background:color-mix(in srgb,Canvas 96%,transparent);box-shadow:0 8px 36px color-mix(in srgb,#000 12%,transparent)}.bar{display:flex;min-height:48px;align-items:center;gap:8px;padding:8px 10px;border-bottom:1px solid var(--line);padding-left:max(10px,var(--safe-left));padding-right:max(10px,var(--safe-right))}.brand{display:grid;place-items:center;width:30px;height:30px;flex:0 0 30px;border-radius:9px;background:color-mix(in srgb,var(--accent) 18%,Canvas);font-weight:850}.heading{min-width:0;flex:1}.heading strong{display:block;font-size:12px;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.heading span{display:block;margin-top:2px;font-size:9px;color:var(--muted);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tools{display:flex;align-items:center;gap:5px;flex-wrap:wrap;justify-content:flex-end}button,.button{appearance:none;border:1px solid var(--line);background:var(--soft);color:CanvasText;border-radius:9px;padding:6px 8px;min-height:30px;font:inherit;font-size:10px;font-weight:650;cursor:pointer;text-decoration:none}button:hover,.button:hover{background:color-mix(in srgb,CanvasText 9%,Canvas)}button:focus-visible,.button:focus-visible{outline:2px solid Highlight;outline-offset:2px}.primary{background:color-mix(in srgb,var(--accent) 17%,Canvas)}.open-direct{font-size:9px;color:CanvasText}.open-feedback{display:none}.body{min-height:0;flex:1;overflow:auto;padding:12px;padding-bottom:max(12px,var(--safe-bottom));scrollbar-gutter:stable}.home{display:grid;gap:12px}.hero{padding:14px;border:1px solid var(--line);border-radius:15px;background:linear-gradient(135deg,color-mix(in srgb,var(--accent) 12%,Canvas),Canvas)}.hero h2{margin:0;font-size:17px}.hero p{max-width:680px;margin:5px 0 0;font-size:11px;line-height:1.5;color:var(--muted)}.section-title{margin:2px 0 7px;font-size:10px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px}.card{min-width:0;text-align:left;padding:11px;border:1px solid var(--line);border-radius:13px;background:var(--soft)}.card strong{display:block;font-size:11px}.card span{display:block;margin-top:4px;font-size:9px;line-height:1.4;color:var(--muted)}.tag{display:inline-flex!important;width:auto!important;margin-top:8px!important;padding:2px 6px;border-radius:999px;border:1px solid var(--line);font-size:8px!important;text-transform:uppercase;letter-spacing:.06em}.stage{display:flex;min-height:330px;height:100%;flex-direction:column}.stage-head{display:flex;align-items:center;gap:8px;margin-bottom:8px}.back{flex:0 0 auto}.stage-title{min-width:0;flex:1}.stage-title strong{display:block;font-size:12px}.stage-title span{display:block;margin-top:2px;font-size:9px;color:var(--muted)}.frame-wrap{position:relative;min-height:280px;flex:1;overflow:hidden;border:1px solid var(--line);border-radius:13px;background:#111}.frame-wrap iframe{display:block;width:100%;height:100%;min-height:360px;border:0;background:#fff}.notice{display:grid;min-height:280px;place-items:center;border:1px solid var(--line);border-radius:13px;background:var(--soft);padding:24px;text-align:center}.notice>div{max-width:520px}.notice h3{margin:0;font-size:14px}.notice p{margin:7px 0 0;color:var(--muted);font-size:10px;line-height:1.5}.notice .row{justify-content:center;margin-top:12px}.metrics{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:7px}.metric{padding:12px;border:1px solid var(--line);border-radius:12px;background:var(--soft)}.metric span{display:block;font-size:8px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.metric strong{display:block;margin-top:4px;font-size:13px}.list{margin-top:8px;border:1px solid var(--line);border-radius:12px;overflow:hidden}.line{display:flex;align-items:center;gap:10px;min-height:34px;padding:7px 9px;border-top:1px solid var(--line);font-size:10px}.line:first-child{border-top:0}.line span{color:var(--muted)}.line strong{margin-left:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.loading{display:grid;min-height:240px;place-items:center;color:var(--muted);font-size:11px}.error{color:#dc2626}.mode-badge{padding:3px 6px;border-radius:999px;background:var(--soft);font-size:8px;color:var(--muted)}
+@media(max-width:660px){body{padding:5px}.surface{max-height:min(var(--host-max-h),82vh);border-radius:14px}.bar{align-items:flex-start;min-height:46px}.tools{max-width:50%}.tools button,.tools .button{padding:5px 7px}.grid{grid-template-columns:1fr 1fr}.frame-wrap iframe{min-height:430px}.metrics{grid-template-columns:1fr 1fr}.body{padding:9px}}
+@media(max-width:420px){.grid{grid-template-columns:1fr}.heading span{max-width:150px}.tools .optional{display:none}.metrics{grid-template-columns:1fr}.frame-wrap iframe{min-height:480px}}
+`;
diff --git a/lib/mcp/ui-surface.ts b/lib/mcp/ui-surface.ts
new file mode 100644
index 00000000..786b9a2e
--- /dev/null
+++ b/lib/mcp/ui-surface.ts
@@ -0,0 +1,37 @@
+import { widgetResourceMeta } from "./ui-config";
+import { OPEN_IN_MSO_SCRIPT, openInMsoControls } from "./ui-navigation";
+import { surfaceFrameDomains } from "./surface-catalog";
+import { MSO_SURFACE_SCRIPT } from "./ui-surface-script";
+import { MSO_SURFACE_STYLE } from "./ui-surface-style";
+
+export const MSO_SURFACE_URI = "ui://mso/surface-v1.html";
+const MIME = "text/html;profile=mcp-app";
+
+const html = String.raw`<main class="surface" aria-label="MSO Surface">
+<style>${MSO_SURFACE_STYLE}</style>
+<header class="bar">
+ <div class="brand" aria-hidden="true">M</div>
+ <div class="heading"><strong id="surface-title">MSO Surface</strong><span id="surface-route">/</span></div>
+ <span class="mode-badge" id="surface-mode">inline</span>
+ <div class="tools">
+ <button type="button" id="surface-home" class="optional">Home</button>
+ <button type="button" id="surface-pip" class="optional">PiP</button>
+ <button type="button" id="surface-fullscreen">Fullscreen</button>
+ ${openInMsoControls("primary", "/assistant/mcp")}
+ </div>
+</header>
+<section class="body" id="surface-body"><div class="loading">Loading MSO Surface…</div></section>
+<script>(()=>{${OPEN_IN_MSO_SCRIPT}${MSO_SURFACE_SCRIPT}})();</script>
+</main>`;
+
+export const MSO_SURFACE_RESOURCE = {
+ uri: MSO_SURFACE_URI,
+ name: "MSO Surface",
+ description: "Universal secure MSO presentation target for native operator views and reviewed live app demos inside ChatGPT.",
+ mimeType: MIME,
+ text: html,
+ _meta: widgetResourceMeta(
+ "Interactive MSO Surface. It renders native MSO views and reviewed app demos. Nested frames are exact-origin allowlisted; arbitrary HTML and URLs are never accepted from the model.",
+ { frameDomains: surfaceFrameDomains() },
+ ),
+} as const;