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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(mcp): maximize Fresh 3 operator capabilities
Rahmanf86557faa112
diff --git a/.env.example b/.env.exampleindex cc39a04e..7db1d343 100644--- a/.env.example+++ b/.env.example@@ -207,6 +207,7 @@ OS_SESSION_SECRET=# OS_THREADS_DIR=~/.mso/threads # Alfa assistant chat threads (one file each)# OS_AGENT_MEMORY_DIR=~/.mso/agent-memory # isolated MSO Agent USER.md/MEMORY.md stores# OS_AGENT_SESSIONS_DIR=~/.mso/agent-sessions # durable CLI/MCP agent session records+# OS_PROJECT_AGENT_TASKS_DIR=~/.mso/project-agent-tasks # private project-agent message/status records# OS_SUBAGENT_MAX_TURNS=12 # server policy cap for one foreground subagent; default 12, absolute max 48 (each child still defaults to 6)# Native Local Agents use private defaults; overrides are normally unnecessary.# OS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.json # live receive leases/aliases (0600)diff --git a/CLAUDE.md b/CLAUDE.mdindex 059c51e7..1a2d275d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -348,7 +348,7 @@ the real runtime and working analogue before changing a tool or skill contract.it AND `tools/call` re-checks it — a client can call a name it was never shown.- **Tool names are an MSO public API contract.** Keep global names MSO-owned and generic.Project-owned MCP names are data behind `project_mcp_tools` / `project_mcp_call`; never copy them into the global catalog.- <!-- mcp-toolset: server=1.7.3 version=2026.09.03.4 tools=72 read=34 write=24 exec=14 -->+ <!-- mcp-toolset: server=1.8.0 version=2026.09.03.5 tools=85 read=41 write=25 exec=19 -->The full MSO transport exposes **73 tools**: **72 model/operator tools** (34 read, 24 write, 14 exec) plus app-only `workflow_status`.ChatGPT receives a deliberately smaller static profile; hidden full-catalog names are rejected at call time, not merely omitted from `tools/list`.- Store is `~/.mso/mcp.json`, **sha256 only**, same atomic-write + fail-loud-on-corruptdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 2ba08192..e8cdd023 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -160,7 +160,7 @@ park a visible Approve/Deny card. The complete semantic contract is**MCP** is for external clients such as ChatGPT, Claude.ai and Cursor. Its catalog lives in`lib/mcp/`; access is controlled by the OAuth token scope rather than Alfa approval cards.-<!-- mcp-toolset: server=1.7.3 version=2026.09.03.4 tools=72 read=34 write=24 exec=14 -->+<!-- mcp-toolset: server=1.8.0 version=2026.09.03.5 tools=85 read=41 write=25 exec=19 -->The full transport exposes **73 tools**: **72 model/operator tools** (34 read, 24 write, 14 exec) plus app-only `workflow_status`. ChatGPT gets a compact client profile rather than the full set. Project function/MCP names remain data behind `project_capabilities`, `project_function_call`, `project_mcp_tools`, and `project_mcp_call`; they never rewrite the global tool prefix. `GET /mcp` reports both full and ChatGPT signatures.See `docs/MCP.md` for protocol/security internals, `docs/A2A.md` for peer-agent delegation, and `docs/CHATGPT-PLUGIN.md` for thediff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex ab6b5481..bd362190 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Added**+- `mcp` maximize Fresh 3 operator capabilities- `mcp` harden ChatGPT profile and project bridge**Fixed**diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.mdindex 378d8df5..e688d4b1 100644--- a/docs/CHATGPT-PLUGIN.md+++ b/docs/CHATGPT-PLUGIN.md@@ -4,13 +4,13 @@>> ChatGPT's Developer Mode/App UI can change independently of MSO. Use the current OpenAI MCP/App documentation for exact menu labels, and use MSO Settings → MCP / `GET /mcp` for the live server/profile signatures.-<!-- mcp-chatgpt-profile: server=1.7.3 version=2026.09.03.4 tools=28 read=14 write=8 exec=6 app-only=1 total=29 -->+<!-- mcp-chatgpt-profile: server=1.8.0 version=2026.09.03.5 tools=61 read=32 write=17 exec=12 app-only=1 total=62 -->-MSO server **1.7.3**, toolset **2026.09.03.4** exposes a full generic catalog for MCP clients, but a registered ChatGPT client receives only **29 transport tools**: **28 model/operator tools** (14 read, 8 write, 6 exec) plus app-only `workflow_status`.+MSO server **1.8.0**, toolset **2026.09.03.5** exposes the full generic catalog for MCP clients, while a registered ChatGPT client receives **62 transport tools**: **61 model/operator tools** (32 read, 17 write, 12 exec) plus app-only `workflow_status`.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 **31,908 JSON bytes** for all 29 ChatGPT tool definitions (roughly 8k tokens at a 4-byte/token estimate), with the largest individual descriptor **2,507 bytes**. CI keeps the profile below 40 KiB and each descriptor below 8 KiB. Bytes are the deterministic contract; token estimates vary by tokenizer.+The compact descriptor regression currently measures **57,853 JSON bytes** for all 62 ChatGPT transport tool definitions (roughly 14.5k tokens at a 4-byte/token estimate), with the largest individual descriptor **2,504 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@@ -23,12 +23,14 @@ full MCP client└─ full MSO catalogChatGPT- └─ compact MSO catalog- ├─ workflow / skill discovery- ├─ files / visual proof- ├─ bounded shell lifecycle- ├─ durable session + Local Agents- └─ generic dynamic project seams+ └─ compact capability-complete MSO operator catalog+ ├─ workflow / skills / durable sessions / Local Agents+ ├─ bounded VPS + filesystem CRUD + managed apps + browser+ ├─ explicit bounded infrastructure operations+ ├─ project snapshot / diff / knowledge / project-agent tasks+ ├─ Convex status + dynamic Convex MCP schemas/calls+ ├─ MCP Apps UI for workflow, project, diff and VPS+ └─ dynamic project MCP/function seams for project-owned tools```The profile is fail-closed at both `tools/list` and `tools/call`: guessing a hidden full-catalog name returns `unknown tool`. This profile is a compatibility/context boundary, not a privilege escalation mechanism; the OAuth `read < write < exec` scope is still enforced independently.@@ -49,39 +51,72 @@ The ChatGPT projection compacts verbose descriptions/schema descriptions without## Exact ChatGPT model tool profile-### `read` — 14 ChatGPT model tools+### `read` — 32 ChatGPT model tools- `agent_session_current`+- `apps_list`+- `apps_logs`+- `browser_status`+- `cloudflare_zones_list`+- `connections_list`+- `dokploy_projects_list`- `exec_job_status`- `fs_list`- `fs_read`- `fs_search`+- `fs_usage`+- `infra_provider_doctor`+- `infra_providers_list`- `local_agent_inbox`- `local_agent_request_wait`- `local_agents_list`+- `project_agent_status`- `project_capabilities`+- `project_changes_list`+- `project_diff`+- `project_get`+- `project_knowledge_get`- `projects_list`- `read_pipeline`- `screen_capture`+- `skills_list`- `skills_read`- `skills_search`+- `sys_processes`+- `sys_stats`+- `vps_status`-### `write` — + 8 ChatGPT model tools+### `write` — + 17 ChatGPT model tools- `agent_session_rename`+- `apps_power`+- `cloudflare_dns_upsert`+- `dokploy_project_ensure`+- `fs_copy`+- `fs_delete`+- `fs_mkdir`+- `fs_move`- `fs_upload_file`- `fs_write`+- `hostinger_dns_upsert`- `local_agent_message_send`- `local_agent_reply`+- `project_knowledge_set`- `workflow_cancel`- `workflow_finish`- `workflow_start`-### `exec` — + 6 ChatGPT model tools+### `exec` — + 12 ChatGPT model tools+- `browser_power`- `exec_job_cancel`- `exec_job_start`- `exec_run`+- `project_agent_run`+- `project_database_call`+- `project_database_query`+- `project_database_status`+- `project_database_tools`- `project_function_call`- `project_mcp_call`- `project_mcp_tools`@@ -90,6 +125,10 @@ The ChatGPT projection compacts verbose descriptions/schema descriptions without`workflow_status` is available to the MCP Apps progress UI but is not counted as a model/operator action.+The restored Original MSO operator primitives (`sys_*`, `fs_usage` + full bounded filesystem CRUD, `apps_*`, browser power/status, and Dokploy/Cloudflare/Hostinger operations) are again first-class ChatGPT actions. Fresh 3 adds `vps_status`, project snapshot/diff/history/knowledge, private project-agent message/status, connection inventory, and Convex database seams without removing the lower-level primitives. This is intentional: aggregate tools optimize common turns; bounded primitives preserve direct operator control.++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 61-action static model profile instead of copying every downstream provider/project action into ChatGPT.+For the complete non-ChatGPT MSO catalog, scopes, limits, A2A, providers, Tool Forge and other generic capabilities, see [`MCP.md`](./MCP.md).## Dynamic project capabilities without global project tools@@ -173,7 +212,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 29-tool compact profile above.+7. Verify that the action snapshot corresponds to the 62-tool transport profile (61 model actions + app-only `workflow_status`) above.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.diff --git a/docs/MCP.md b/docs/MCP.mdindex ac99189c..538a5fed 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -73,9 +73,9 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe| Scope | Tools ||---|---|-| `read` | `a2a_agent_discover` `a2a_agents_list` `a2a_task_get` `agent_memory_read` `agent_memory_search` `agent_session_current` `agent_session_resume` `agent_sessions_list` `apps_list` `apps_logs` `browser_status` `cloudflare_zones_list` `dokploy_projects_list` `exec_job_status` `fs_list` `fs_read` `fs_search` `fs_usage` `infra_provider_doctor` `infra_providers_list` `local_agent_inbox` `local_agent_request_wait` `local_agents_list` `project_capabilities` `project_memory_search` `projects_list` `read_pipeline` `screen_capture` `skills_list` `skills_read` `skills_search` `sys_processes` `sys_stats` `tool_forge_candidates` |-| `write` | + `a2a_agent_register` `a2a_agent_remove` `agent_memory_forget` `agent_memory_remember` `agent_session_note` `agent_session_rename` `apps_power` `cloudflare_dns_upsert` `dokploy_project_ensure` `fs_copy` `fs_delete` `fs_mkdir` `fs_move` `fs_upload_file` `fs_write` `hostinger_dns_upsert` `local_agent_message_send` `local_agent_reply` `project_memory_upsert` `project_script_run` `tool_forge_propose` `workflow_cancel` `workflow_finish` `workflow_start` |-| `exec` | + `a2a_handoff` `a2a_message_send` `a2a_task_cancel` `agent_subagent_run` `browser_power` `exec_job_cancel` `exec_job_start` `exec_run` `local_agent_request` `project_function_call` `project_mcp_call` `project_mcp_tools` `tool_forge_evaluate` `tool_forge_promote` |+| `read` | `a2a_agent_discover` `a2a_agents_list` `a2a_task_get` `agent_memory_read` `agent_memory_search` `agent_session_current` `agent_session_resume` `agent_sessions_list` `apps_list` `apps_logs` `browser_status` `cloudflare_zones_list` `connections_list` `dokploy_projects_list` `exec_job_status` `fs_list` `fs_read` `fs_search` `fs_usage` `infra_provider_doctor` `infra_providers_list` `local_agent_inbox` `local_agent_request_wait` `local_agents_list` `project_agent_status` `project_capabilities` `project_changes_list` `project_diff` `project_get` `project_knowledge_get` `project_memory_search` `projects_list` `read_pipeline` `screen_capture` `skills_list` `skills_read` `skills_search` `sys_processes` `sys_stats` `tool_forge_candidates` `vps_status` |+| `write` | + `a2a_agent_register` `a2a_agent_remove` `agent_memory_forget` `agent_memory_remember` `agent_session_note` `agent_session_rename` `apps_power` `cloudflare_dns_upsert` `dokploy_project_ensure` `fs_copy` `fs_delete` `fs_mkdir` `fs_move` `fs_upload_file` `fs_write` `hostinger_dns_upsert` `local_agent_message_send` `local_agent_reply` `project_knowledge_set` `project_memory_upsert` `project_script_run` `tool_forge_propose` `workflow_cancel` `workflow_finish` `workflow_start` |+| `exec` | + `a2a_handoff` `a2a_message_send` `a2a_task_cancel` `agent_subagent_run` `browser_power` `exec_job_cancel` `exec_job_start` `exec_run` `local_agent_request` `project_agent_run` `project_database_call` `project_database_query` `project_database_status` `project_database_tools` `project_function_call` `project_mcp_call` `project_mcp_tools` `tool_forge_evaluate` `tool_forge_promote` |Alfa — the in-app assistant — overlaps the same host capabilities under dot.case names,and `lib/mcp/parity.test.ts` fails if one surface gains a tool the other lacks@@ -116,10 +116,10 @@ The catalog has a stable server version plus a schema-derived toolset signature.Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.-<!-- mcp-toolset: server=1.7.3 version=2026.09.03.4 tools=72 read=34 write=24 exec=14 -->+<!-- mcp-toolset: server=1.8.0 version=2026.09.03.5 tools=85 read=41 write=25 exec=19 -->-Current full transport catalog: **73 tools**, server `1.7.3` / toolset `2026.09.03.4`.-The model/operator catalog is **72 tools** (34 read, 24 write, 14 exec); `workflow_status` is the one app-only MCP Apps bridge. ChatGPT receives a smaller client profile rather than this full set; see [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md).+Current full transport catalog: **86 tools**, server `1.8.0` / toolset `2026.09.03.5`.+The model/operator catalog is **85 tools** (41 read, 25 write, 19 exec); `workflow_status` is the one app-only MCP Apps bridge. ChatGPT receives a smaller client profile rather than this full set; see [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md).`agent_memory_search` is the typed-memory retrieval surface. It resolves semantic/episodic/procedural claims at an optional point in time, returns confidence/provenance and competing effective claims, and can expose superseded/retracted history when explicitly requested. `agent_memory_remember` remains the write surface and now accepts typed metadata; raw ChatGPT conversation ids are never stored as provenance.Session/memory tools add durable conversation context without creating dynamic per-project global names. Project functions use `project_capabilities` / `project_function_call`; project MCP servers use `project_capabilities` / `project_mcp_tools` / `project_mcp_call`. In both cases project-specific names remain data, not entries in MSO `tools/list`.@@ -178,6 +178,16 @@ MSO itself stays generic. A project may opt into capabilities inside its own val`project_mcp_tools` is exec scope even though it returns schemas because starting a stdio project MCP executes project code. Stdio uses no shell, enforces cwd containment, starts from MSO's credential-scrubbed child environment, and adds only project-declared env. Remote HTTP uses the existing HTTPS/SSRF/DNS-rebinding guard and bounded responses. A project MCP that declares OAuth but lacks explicit server-side authorization fails closed; MSO never imports or mints another project's credential implicitly.+### Project experience, knowledge, Convex and project-agent surfaces++The Lovable-inspired layer is additive over MSO's host primitives; it does not replace them. `project_get` returns one canonical project snapshot, `project_changes_list` exposes bounded Git history, and `project_diff` returns a bounded unified diff while its MCP App structured projection contains only the safe file/line summary. `project_knowledge_get` / `project_knowledge_set` store always-on project context in `.mso/KNOWLEDGE.md` (10,000 UTF-8 bytes max, symlink refused, optional SHA-256 compare-and-swap). Skills remain the on-demand instruction layer and workflow/repo memory remains learned evidence.++`connections_list` is the safe integration inventory: masked infrastructure readiness, project MCP aliases/auth class, and Convex detection. It deliberately returns no provider token, header, `.mcp.json` body, or `.env.local` value. Existing explicit bounded provider tools remain available; the inventory is a discovery surface, not a replacement.++Convex is the first-class project database provider. `project_database_status`, `project_database_tools`, `project_database_call`, and read-only `project_database_query` launch the **project-installed** official Convex MCP CLI through fixed argv/no shell. MSO pins `--project-dir` to the selected validated project, strips nested `projectDir` overrides, refuses cross-project deployment selectors such as `prod:other-project`, and never enables Convex's dangerous production flags automatically. Cloud, local and self-hosted Convex therefore share one dynamic schema seam without copying the Convex tool catalog into global MSO actions.++`project_agent_run` wraps the existing MSO subagent runtime rather than creating a second agent engine. `wait=true` is bounded foreground execution; `wait=false` persists a private `message_id` task record and returns immediately, while `project_agent_status` retrieves only that authenticated client's task. Plan mode forces read scope. The task record is durable, but an in-progress worker is intentionally tied to the current MSO service process; normal workflow/local-agent primitives remain the durable cross-session orchestration layer.+The manifest is versioned and intentionally uses **fixed argv**, not a shell template:```jsondiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex b914dc4a..0ce962c7 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,4 +1,5 @@# mso — Progress Log+- **Fresh 3 capability-max release (2026-09-03):** server `1.8.0` / toolset `2026.09.03.5` restores Original MSO bounded VPS/system/filesystem/app/browser/infra operations to the ChatGPT profile while preserving Fresh 3 workflow/session/Local Agent/read-pipeline/project-MCP orchestration. The ChatGPT transport profile is now 62 tools (61 model actions + app-only `workflow_status`) at 57,853 descriptor bytes (~14.5k rough tokens), while the full model/operator catalog grows to 85 tools. New Lovable-inspired surfaces add `project_get`, Git history/diff, `.mso/KNOWLEDGE.md`, safe connection inventory, private `project_agent_run`/`project_agent_status`, and MCP Apps project/diff/VPS cards. Convex is first-class through the project-installed official Convex MCP CLI with projectDir override stripping, cross-project selector refusal, dynamic schemas, and no automatic dangerous production flags.- **MCP protocol-era correctness (2026-09-03):** server `1.7.3` stops claiming the stateless `2026-07-28` protocol while serving the legacy initialize/session wire shape. The supported ceiling is deliberately `2025-06-18` (matching the known-good CareerPack ChatGPT connector); a modern HTTP probe receives a 400 and can fall back to initialize. `server/discover` is no longer aliased to the legacy initialize payload. Browser CORS also permits `Mcp-Method`/`Mcp-Name` so a standards-aware probe can reach the server and receive the fallback signal. Toolset stays `2026.09.03.4`.Running log of what shipped each phase. Newest at top.diff --git a/docs/integrations/CHATGPT-UI.md b/docs/integrations/CHATGPT-UI.mdindex 53ad0291..065612d6 100644--- a/docs/integrations/CHATGPT-UI.md+++ b/docs/integrations/CHATGPT-UI.md@@ -1,81 +1,81 @@# ChatGPT MCP App UI-MSO can render a first-party progress card inside ChatGPT instead of returning only tool-call text. The implementation follows the MCP Apps / OpenAI Apps SDK contract while keeping the existing JSON/text result as a backward-compatible fallback for MCP clients that do not render UI resources.+MSO renders first-party interactive operator cards inside ChatGPT while keeping JSON/text results as the portable fallback for MCP clients that do not implement MCP Apps.-## What ChatGPT needs+## Contract-A connector cannot create an inline card merely by returning HTML in a normal tool result. The MCP server must expose and connect four contracts:+A normal tool result cannot create an inline application by returning arbitrary HTML. MSO exposes the MCP Apps contracts explicitly:-1. **UI resource** — `resources/list` and `resources/read` expose a `ui://…` resource with MIME type `text/html;profile=mcp-app`.-2. **Tool → UI binding** — the tool descriptor points at that resource through `_meta.ui.resourceUri`. MSO also emits the compatibility alias `_meta["openai/outputTemplate"]`.-3. **Structured result** — the tool declares `outputSchema` and returns matching `structuredContent`; `content` remains as the portable text fallback.-4. **Widget bridge** — the sandboxed component reads `window.openai.toolOutput`, may call explicitly app-visible tools through `window.openai.callTool`, and can open the full MSO dashboard through `window.openai.openExternal`.+1. `resources/list` / `resources/read` expose `ui://…` resources with `text/html;profile=mcp-app`.+2. Model-visible tools bind a resource with `_meta.ui.resourceUri` plus the OpenAI compatibility alias `_meta["openai/outputTemplate"]`.+3. UI-capable tools declare `outputSchema` and return bounded `structuredContent`; ordinary `content` remains the model/client text fallback.+4. Sandboxed widgets read `window.openai.toolOutput`, may call only explicitly app-visible MSO tools through `window.openai.callTool`, and use `window.openai.openExternal` for the full dashboard.Official references:- <https://developers.openai.com/plugins/build/chatgpt-ui>- <https://developers.openai.com/plugins/reference>-## MSO implementation+## MSO resources++| Experience | Entry tool | Resource | Refresh behavior |+| --- | --- | --- | --- |+| Workflow progress | `workflow_start` | `ui://mso/workflow-progress-v1.html` | app-only `workflow_status` |+| Project status | `project_get` | `ui://mso/project-status-v1.html` | widget calls `project_get` again |+| Git diff summary | `project_diff` | `ui://mso/project-diff-v1.html` | static result; request a new diff for changed state |+| VPS/operator status | `vps_status` | `ui://mso/vps-status-v1.html` | widget calls `vps_status` again |++Source boundaries:| Contract | MSO source || --- | --- |-| Progress UI resource | `lib/mcp/ui-resources.ts` |+| Resource registry / workflow UI | `lib/mcp/ui-resources.ts` |+| Project/diff/VPS resources | `lib/mcp/ui-operator-resources.ts` || Resource capability / RPC | `lib/mcp/dispatch.ts` |-| Tool descriptor + structured schemas | `lib/mcp/tools-learning.ts` |-| Shared tool schema type | `lib/mcp/tool-kit.ts` |-| Toolset signature | `lib/mcp/toolset.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` |+| VPS structured schema | `lib/mcp/tools-operator-dashboard.ts` |+| Shared descriptor contract | `lib/mcp/tool-kit.ts`, `lib/mcp/tool-contract.ts` || Tests | `lib/mcp/ui-resources.test.ts` |-`workflow_start` is the model-visible entry point. Its result renders `ui://mso/workflow-progress-v1.html` when the host supports MCP Apps.--The component then uses `workflow_status` to refresh the visible card. `workflow_status` is marked `ui.visibility: ["app"]` so it is a component bridge, not another model/operator action. Polling is deliberately excluded from MSO activity/workflow-step persistence; otherwise a four-second UI refresh would teach workflow memory a fake sequence made mostly of `workflow_status` calls.--## Data boundary--The progress component receives only:+## Data boundaries-- workflow id;-- intent and resolved project label;-- started time / elapsed time;-- step count;-- recent tool name, outcome, timestamp, and duration.+The workflow component receives only workflow id, intent, resolved project label, timing, step count, and recent tool name/outcome/timestamp/duration. `workflow_status` is `ui.visibility:["app"]`, so polling is not another model action and is deliberately excluded from workflow-memory persistence.-It does **not** receive tool arguments, shell commands, file contents, bearer tokens, API keys, credentials, or raw audit details. The existing workflow-memory redaction remains the authority for persisted workflow evidence.+The project component receives the safe `project_get` projection: project identity/path, bounded Git state, package metadata, Convex detection mode, project-MCP alias count, and knowledge existence/size. It does not receive `.mcp.json`, `.env.local`, provider tokens, project-MCP headers, or knowledge content.-The component is self-contained: no external JavaScript, CSS, images, or direct API fetches are required. `Open in MSO` uses the host navigation bridge to `https://mso.rahmanef.com` instead of sharing an authenticated browser session with the iframe.+The diff component receives only project/mode/SHA metadata, changed file names and aggregate additions/deletions. The unified diff remains in the tool's portable text result and is never interpolated into widget HTML.-## Dedicated UI origin--For the current custom connector, MSO intentionally leaves `_meta.ui.domain` unset so ChatGPT uses its default sandbox origin. The main dashboard origin is not reused as the widget origin.--Before submitting a UI-enabled MSO integration to the ChatGPT app directory, provision a dedicated HTTPS origin unique to the MSO widget and add that reviewed origin to `_meta.ui.domain` (plus the `openai/widgetDomain` compatibility alias if still required by the target client). Treat that as a release/submission configuration change rather than an arbitrary runtime environment knob.+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.-The dashboard navigation target is separate: `openai/widgetCSP.redirect_domains` allowlists `https://mso.rahmanef.com` solely for the **Open in MSO** action.+All four resources are self-contained: no external JavaScript, CSS, images, or direct `fetch()` calls. `Open in MSO` uses the host navigation bridge to `https://mso.rahmanef.com`. The widget CSP has no connect/resource domains and allowlists only that dashboard redirect.-## Expected ChatGPT flow+## Flow```text-ChatGPT- └─ tools/call workflow_start- ├─ content -> text fallback- ├─ structuredContent -> initial workflow state- └─ _meta.ui.resourceUri -> ui://mso/workflow-progress-v1.html- └─ ChatGPT renders sandboxed card- └─ callTool(workflow_status)- └─ structuredContent -> card refresh+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++Every entry tool also returns portable text/JSON for non-MCP-Apps clients.```-For a client without MCP App support, nothing breaks: it keeps reading `content[0].text` exactly as before.+## Dedicated UI origin++For the current custom connector, MSO intentionally leaves `_meta.ui.domain` unset so ChatGPT uses its default sandbox origin. The main dashboard is not reused as widget origin. Before an app-directory submission, provision a dedicated reviewed HTTPS widget origin and add it to `_meta.ui.domain` (plus the compatibility alias required by the target client at that time).## Deployment / refresh-After merging this change:+After a UI/schema release:-1. run the normal MSO verification pipeline (`bun run verify`);+1. run `bun run verify` and a production build;2. deploy through the normal MSO release path;-3. reconnect or refresh the ChatGPT MSO connector so ChatGPT re-reads `initialize`, `tools/list`, and the resource capability;-4. start a multi-step request that routes through `workflow_start`;-5. verify that the card renders, recent steps advance without `workflow_status` appearing in the learned workflow, and **Open in MSO** opens the production dashboard.+3. refresh/re-scan the ChatGPT development app so `initialize`, `tools/list`, and `resources/list` are read again;+4. verify each entry tool exposes `outputSchema` and `_meta.ui.resourceUri`;+5. verify each `resources/read` returns `text/html;profile=mcp-app`;+6. verify refresh buttons work and `workflow_status` polling does not enter learned workflow steps.-If ChatGPT still shows only JSON/text after deployment, inspect `tools/list` first. `workflow_start` must expose both `outputSchema` and `_meta.ui.resourceUri`, and `resources/read` for that URI must return `text/html;profile=mcp-app`. A stale connector schema is the next likely cause; refresh/reconnect it before changing the server implementation.+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/agent/project-agent-task-store.test.ts b/lib/agent/project-agent-task-store.test.tsnew file mode 100644index 00000000..ab86e0ad--- /dev/null+++ b/lib/agent/project-agent-task-store.test.ts@@ -0,0 +1,31 @@+import { afterAll, describe, expect, it } from "vitest";+import { mkdtemp, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-project-agent-store-"));+process.env.OS_PROJECT_AGENT_TASKS_DIR = root;+const store = await import("./project-agent-task-store");++afterAll(async () => { delete process.env.OS_PROJECT_AGENT_TASKS_DIR; await rm(root, { recursive: true, force: true }); });++describe("project agent task store", () => {+ it("persists client-owned message status without cross-principal access", async () => {+ const task = await store.createProjectAgentTask({ principal: "client-a", sessionId: "session-a", project: { id: "root/project", name: "project" }, planMode: false, maxScope: "write" });+ expect(task.status).toBe("in_progress");+ expect(await store.getProjectAgentTask("client-b", task.id)).toBeNull();+ const done = await store.updateProjectAgentTask("client-a", task.id, { status: "completed", result: { text: "done", subagentId: "subagent-1", rounds: 2 } });+ expect(done).toMatchObject({ status: "completed", result: { text: "done", rounds: 2 } });+ expect(await store.getProjectAgentTask("client-a", task.id)).toMatchObject({ status: "completed" });+ });++ it("uses private filesystem permissions", async () => {+ const task = await store.createProjectAgentTask({ principal: "client-private", sessionId: "session-private", project: { id: "root/private", name: "private" }, planMode: true, maxScope: "read" });+ const files: string[] = [];+ const walk = async (dir: string) => { for (const entry of await import("node:fs/promises").then((m) => m.readdir(dir, { withFileTypes: true }))) { const target = path.join(dir, entry.name); if (entry.isDirectory()) await walk(target); else files.push(target); } };+ await walk(root);+ const file = files.find((row) => row.endsWith(`${task.id}.json`));+ expect(file).toBeTruthy();+ expect((await stat(file!)).mode & 0o077).toBe(0);+ });+});diff --git a/lib/agent/project-agent-task-store.ts b/lib/agent/project-agent-task-store.tsnew file mode 100644index 00000000..5d8c9dcf--- /dev/null+++ b/lib/agent/project-agent-task-store.ts@@ -0,0 +1,74 @@+import { randomUUID } from "node:crypto";+import os from "node:os";+import path from "node:path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { principalHash } from "./session-files";+import { readLocalAgentStore, writeLocalAgentStore } from "./local-agent-private-store";++const ROOT = path.resolve((process.env.OS_PROJECT_AGENT_TASKS_DIR || path.join(os.homedir(), ".mso", "project-agent-tasks")).replace(/^~(?=$|\/)/, os.homedir()));+const ID = /^projectmsg_[a-f0-9-]{36}$/;+const MAX_TASK_BYTES = 192 * 1024;+const RESULT_MAX_CHARS = 80_000;++export type ProjectAgentTaskStatus = "in_progress" | "completed" | "partial" | "timeout" | "failed";+export type ProjectAgentTask = {+ id: string;+ ownerHash: string;+ sessionId: string;+ project: { id: string; name: string };+ status: ProjectAgentTaskStatus;+ planMode: boolean;+ maxScope: "read" | "write" | "exec";+ createdAt: string;+ updatedAt: string;+ result?: { text: string; subagentId?: string; rounds?: number; toolCalls?: Array<{ name: string; ok: boolean }> };+ error?: string;+};++function taskFile(ownerHash: string, id: string): string {+ if (!/^[a-f0-9]{64}$/.test(ownerHash) || !ID.test(id)) throw new Error("invalid project agent task key");+ return path.join(ROOT, ownerHash.slice(0, 2), ownerHash, `${id}.json`);+}++function valid(value: unknown): value is ProjectAgentTask {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const row = value as Partial<ProjectAgentTask>;+ return Boolean(+ typeof row.id === "string" && ID.test(row.id) && typeof row.ownerHash === "string" && /^[a-f0-9]{64}$/.test(row.ownerHash) &&+ typeof row.sessionId === "string" && row.project && typeof row.project.id === "string" && typeof row.project.name === "string" &&+ ["in_progress", "completed", "partial", "timeout", "failed"].includes(String(row.status)) &&+ typeof row.createdAt === "string" && typeof row.updatedAt === "string",+ );+}++export async function createProjectAgentTask(input: {+ principal: string; sessionId: string; project: { id: string; name: string }; planMode: boolean; maxScope: "read" | "write" | "exec";+}): Promise<ProjectAgentTask> {+ const id = `projectmsg_${randomUUID()}`;+ const ownerHash = principalHash(input.principal);+ const now = new Date().toISOString();+ const record: ProjectAgentTask = { id, ownerHash, sessionId: input.sessionId, project: input.project, status: "in_progress", planMode: input.planMode, maxScope: input.maxScope, createdAt: now, updatedAt: now };+ const file = taskFile(ownerHash, id);+ await withSecurityStoreLock(file, () => writeLocalAgentStore(file, record, MAX_TASK_BYTES));+ return record;+}++export async function updateProjectAgentTask(principal: string, id: string, patch: {+ status: ProjectAgentTaskStatus; result?: ProjectAgentTask["result"]; error?: string;+}): Promise<ProjectAgentTask> {+ const ownerHash = principalHash(principal), file = taskFile(ownerHash, id);+ return withSecurityStoreLock(file, async () => {+ const current = await readLocalAgentStore<ProjectAgentTask | null>(file, MAX_TASK_BYTES, null, (value): value is ProjectAgentTask | null => value === null || valid(value));+ if (!current || current.ownerHash !== ownerHash) throw new Error("project agent message not found for this client");+ const result = patch.result ? { ...patch.result, text: String(patch.result.text ?? "").slice(0, RESULT_MAX_CHARS) } : undefined;+ const next: ProjectAgentTask = { ...current, status: patch.status, updatedAt: new Date().toISOString(), ...(result ? { result } : {}), ...(patch.error ? { error: patch.error.slice(0, 1000) } : {}) };+ await writeLocalAgentStore(file, next, MAX_TASK_BYTES);+ return next;+ });+}++export async function getProjectAgentTask(principal: string, id: string): Promise<ProjectAgentTask | null> {+ const ownerHash = principalHash(principal), file = taskFile(ownerHash, id);+ const record = await readLocalAgentStore<ProjectAgentTask | null>(file, MAX_TASK_BYTES, null, (value): value is ProjectAgentTask | null => value === null || valid(value));+ return record?.ownerHash === ownerHash ? record : null;+}diff --git a/lib/agent/subagent-runner.test.ts b/lib/agent/subagent-runner.test.tsindex b7f3a07e..16e215e1 100644--- a/lib/agent/subagent-runner.test.ts+++ b/lib/agent/subagent-runner.test.ts@@ -15,6 +15,7 @@ vi.mock("@/lib/mcp/tools", () => ({{ name: "fs_write", description: "write", scope: "write", inputSchema: { type: "object", properties: {} } },{ name: "local_agent_message_send", description: "local", scope: "write", inputSchema: { type: "object", properties: {} } },{ name: "agent_subagent_run", description: "nested", scope: "exec", inputSchema: { type: "object", properties: {} } },+ { name: "project_agent_run", description: "nested project wrapper", scope: "exec", inputSchema: { type: "object", properties: {} } },],}));vi.mock("@/lib/mcp/dispatch", () => ({ dispatch }));@@ -50,6 +51,7 @@ describe("same-session subagent runner", () => {expect(names).toContain("fs_write");expect(names).not.toContain("local_agent_message_send");expect(names).not.toContain("agent_subagent_run");+ expect(names).not.toContain("project_agent_run");expect(result.status).toBe("completed");});});diff --git a/lib/agent/subagent-runner.ts b/lib/agent/subagent-runner.tsindex 77ad9a14..5b533a14 100644--- a/lib/agent/subagent-runner.ts+++ b/lib/agent/subagent-runner.ts@@ -16,7 +16,7 @@ function maxTurnsLimit(): number {const DEFAULT_TIMEOUT_MS = 60_000;const MAX_TIMEOUT_MS = 120_000;const DENY_PREFIXES = ["agent_session_", "agent_memory_", "local_agent_", "a2a_"];-const DENY_EXACT = new Set(["agent_subagent_run"]);+const DENY_EXACT = new Set(["agent_subagent_run", "project_agent_run"]);function bounded(value: string, max = MAX_RESULT_BYTES): string {if (Buffer.byteLength(value, "utf8") <= max) return value;diff --git a/lib/host/index.ts b/lib/host/index.tsindex c65086ed..03b80cfe 100644--- a/lib/host/index.ts+++ b/lib/host/index.ts@@ -12,7 +12,9 @@ export { startExecJob, getExecJob, cancelExecJob } from "./exec-jobs";export { sha256Text, utf8Bytes } from "./hash";export { writeFileGuarded } from "./guarded-write";export { resolveProjectHint, inspectProject } from "./projects";+export { projectGitSnapshot, projectGitEdits, projectGitDiff, readProjectKnowledge, detectProjectConvex, PROJECT_KNOWLEDGE_REL, PROJECT_KNOWLEDGE_MAX_BYTES } from "./project-experience";export { projectCapabilities, runProjectFunction, readProjectMcpServers, publicProjectMcpServers, listProjectMcpTools, callProjectMcpTool } from "./project-capabilities";+export { listProjectConvexTools, callProjectConvexTool, PROJECT_CONVEX_READ_TOOLS, PROJECT_CONVEX_WRITE_TOOLS } from "./project-convex";export type { ProjectCapabilities, PublicProjectFunction } from "./project-capabilities";export { listProjects, listProjectDirs, projectRoots, PROJECT_LIMITS } from "./project-roots";export type { ProjectRow, ListProjectsResult } from "./project-roots";diff --git a/lib/host/project-convex.test.ts b/lib/host/project-convex.test.tsnew file mode 100644index 00000000..6bfa844e--- /dev/null+++ b/lib/host/project-convex.test.ts@@ -0,0 +1,43 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-convex-mcp-"));+const project = path.join(root, "project");+const bin = path.join(project, "node_modules", ".bin", "convex");++beforeAll(async () => {+ await mkdir(path.dirname(bin), { recursive: true });+ await mkdir(path.join(project, "convex"), { recursive: true });+ await writeFile(path.join(project, "package.json"), JSON.stringify({ dependencies: { convex: "1.0.0" } }));+ await writeFile(bin, `#!/usr/bin/env node\nconst readline=require('node:readline');const rl=readline.createInterface({input:process.stdin,crlfDelay:Infinity});const send=x=>process.stdout.write(JSON.stringify(x)+'\\n');const tools=['status','tables','data','runOneoffQuery','functionSpec','run','logs','insights','envList','envGet','envSet','envRemove'].map(name=>({name,inputSchema:{type:'object',properties:{projectDir:{type:'string'},value:{type:'string'}}}}));rl.on('line',line=>{const m=JSON.parse(line);if(m.method==='initialize')return send({jsonrpc:'2.0',id:m.id,result:{protocolVersion:m.params.protocolVersion,capabilities:{tools:{}},serverInfo:{name:'convex-fixture',version:'1'}}});if(m.method==='notifications/initialized')return;if(m.method==='tools/list')return send({jsonrpc:'2.0',id:m.id,result:{tools}});if(m.method==='tools/call')return send({jsonrpc:'2.0',id:m.id,result:{content:[{type:'text',text:JSON.stringify({tool:m.params.name,args:m.params.arguments,argv:process.argv.slice(2)})}]}})});\n`);+ await chmod(bin, 0o755);+});++afterAll(async () => rm(root, { recursive: true, force: true }));++describe("first-class Convex project adapter", () => {+ it("discovers only supported official Convex MCP tools", async () => {+ const { listProjectConvexTools } = await import("./project-convex");+ const tools = await listProjectConvexTools(project, "dev");+ expect(tools.map((tool) => tool.name)).toEqual(expect.arrayContaining(["status", "runOneoffQuery", "tables", "run"]));+ expect(tools.map((tool) => tool.name)).not.toContain("envGet");+ expect(tools.map((tool) => tool.name)).not.toContain("envSet");+ expect(tools).toHaveLength(8);+ });++ it("pins project dir, strips nested projectDir overrides and forwards safe deployment selection", async () => {+ const { callProjectConvexTool } = await import("./project-convex");+ const result = await callProjectConvexTool(project, "status", { projectDir: "/escape", value: "ok" }, "dev/team") as { content: Array<{ text: string }> };+ const echoed = JSON.parse(result.content[0].text) as { args: Record<string, unknown>; argv: string[] };+ expect(echoed.args).toEqual({ value: "ok" });+ expect(echoed.argv).toEqual(["mcp", "start", "--project-dir", project, "--deployment", "dev/team"]);+ });++ it("refuses cross-project deployment selectors and unknown tools", async () => {+ const { callProjectConvexTool } = await import("./project-convex");+ await expect(callProjectConvexTool(project, "status", {}, "prod:other-project")).rejects.toThrow(/cross-project/i);+ await expect(callProjectConvexTool(project, "notReal", {})).rejects.toThrow(/unsupported Convex MCP tool/i);+ });+});diff --git a/lib/host/project-convex.ts b/lib/host/project-convex.tsnew file mode 100644index 00000000..2e992ad1--- /dev/null+++ b/lib/host/project-convex.ts@@ -0,0 +1,57 @@+import { promises as fs } from "node:fs";+import path from "node:path";+import { callMcpServerTool, listMcpServerTools, type ProjectMcpTool } from "./project-mcp-client";+import type { ProjectMcpServer } from "./project-mcp-config";+import { detectProjectConvex } from "./project-experience";++const SAFE_DEPLOYMENT = /^(?:dev|prod|local|[A-Za-z0-9._-]+|dev\/[A-Za-z0-9._-]+)$/;+const READ_TOOLS = new Set(["status", "tables", "data", "runOneoffQuery", "functionSpec", "insights", "logs"]);+const WRITE_TOOLS = new Set(["run"]);+const ALL_TOOLS = new Set([...READ_TOOLS, ...WRITE_TOOLS]);++function safeDeployment(value?: string): string | undefined {+ if (!value) return undefined;+ if (!SAFE_DEPLOYMENT.test(value) || value.includes(":")) {+ throw new Error("deployment must stay inside the selected project (dev, prod, local, staging, or dev/<name>; cross-project selectors are refused)");+ }+ return value;+}++async function convexServer(projectPath: string, deployment?: string): Promise<ProjectMcpServer> {+ const detected = await detectProjectConvex(projectPath);+ if (!detected.detected) throw new Error("Convex is not detected in this project");+ const command = path.join(projectPath, "node_modules", ".bin", "convex");+ const stat = await fs.lstat(command).catch(() => null);+ if (!stat || (!stat.isFile() && !stat.isSymbolicLink())) {+ throw new Error("local Convex CLI is unavailable; install project dependencies first so node_modules/.bin/convex exists");+ }+ const selected = safeDeployment(deployment);+ const args = ["mcp", "start", "--project-dir", projectPath];+ if (selected) args.push("--deployment", selected);+ return { name: "convex", transport: "stdio", command, args, cwd: projectPath, env: {}, headers: {}, oauthConfigured: false };+}++function sanitizeArgs(args: unknown): Record<string, unknown> {+ const source = args && typeof args === "object" && !Array.isArray(args) ? args as Record<string, unknown> : {};+ const clean = { ...source };+ // Convex documents that status(projectDir) can escape --project-dir. MSO owns the+ // selected project boundary, so callers can never override it through nested args.+ delete clean.projectDir;+ delete clean.project_dir;+ return clean;+}++export async function listProjectConvexTools(projectPath: string, deployment?: string): Promise<ProjectMcpTool[]> {+ const server = await convexServer(projectPath, deployment);+ const tools = await listMcpServerTools(server);+ return tools.filter((tool) => ALL_TOOLS.has(tool.name));+}++export async function callProjectConvexTool(projectPath: string, tool: string, args: unknown, deployment?: string): Promise<unknown> {+ if (!ALL_TOOLS.has(tool)) throw new Error(`unsupported Convex MCP tool: ${tool}`);+ const server = await convexServer(projectPath, deployment);+ return callMcpServerTool(server, tool, sanitizeArgs(args));+}++export const PROJECT_CONVEX_READ_TOOLS = READ_TOOLS;+export const PROJECT_CONVEX_WRITE_TOOLS = WRITE_TOOLS;diff --git a/lib/host/project-experience.test.ts b/lib/host/project-experience.test.tsnew file mode 100644index 00000000..861d415a--- /dev/null+++ b/lib/host/project-experience.test.ts@@ -0,0 +1,68 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { execFileSync } from "node:child_process";+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { detectProjectConvex, projectGitDiff, projectGitEdits, projectGitSnapshot, readProjectKnowledge } from "./project-experience";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-project-exp-"));+const project = path.join(root, "app");++beforeAll(async () => {+ await mkdir(project, { recursive: true });+ await writeFile(path.join(project, "package.json"), JSON.stringify({ name: "fixture", version: "1.0.0", dependencies: { convex: "1.0.0" } }));+ await mkdir(path.join(project, "convex"));+ execFileSync("git", ["init", "-b", "main"], { cwd: project });+ execFileSync("git", ["config", "user.email", "[email protected]"], { cwd: project });+ execFileSync("git", ["config", "user.name", "MSO Test"], { cwd: project });+ await writeFile(path.join(project, "a.txt"), "one\n");+ execFileSync("git", ["add", "."], { cwd: project });+ execFileSync("git", ["commit", "-m", "initial"], { cwd: project });+ await writeFile(path.join(project, "a.txt"), "one\ntwo\n");+ execFileSync("git", ["add", "a.txt"], { cwd: project });+ execFileSync("git", ["commit", "-m", "second"], { cwd: project });+ await writeFile(path.join(project, "a.txt"), "one\ntwo\nworking\n");+});++afterAll(async () => rm(root, { recursive: true, force: true }));++describe("project experience host helpers", () => {+ it("returns bounded Git snapshot, history and working-tree diff", async () => {+ const snapshot = await projectGitSnapshot(project);+ expect(snapshot).toMatchObject({ available: true, clean: false });+ expect(snapshot.branch).toContain("main");+ expect(snapshot.changes).toContain(" M a.txt");++ const edits = await projectGitEdits(project, { limit: 1 });+ expect(edits.edits).toHaveLength(1);+ expect(edits.edits[0].subject).toBe("second");+ expect(edits.pagination.hasMore).toBe(true);+ const page2 = await projectGitEdits(project, { limit: 5, cursor: edits.pagination.nextCursor });+ expect(page2.edits.some((row) => row.subject === "initial")).toBe(true);++ const diff = await projectGitDiff(project);+ expect(diff.summary).toMatchObject({ files: 1, additions: 1, deletions: 0 });+ expect(diff.unifiedDiff).toContain("+working");+ });++ it("keeps project knowledge bounded and refuses symlinks", async () => {+ await mkdir(path.join(project, ".mso"), { recursive: true });+ await writeFile(path.join(project, ".mso", "KNOWLEDGE.md"), "# Project knowledge\nUse Convex.\n");+ const knowledge = await readProjectKnowledge(project);+ expect(knowledge).toMatchObject({ exists: true, path: ".mso/KNOWLEDGE.md" });+ expect(knowledge.sha256).toMatch(/^[a-f0-9]{64}$/);++ const target = path.join(root, "outside.md");+ await writeFile(target, "outside");+ await rm(path.join(project, ".mso", "KNOWLEDGE.md"));+ await symlink(target, path.join(project, ".mso", "KNOWLEDGE.md"));+ await expect(readProjectKnowledge(project)).rejects.toThrow(/regular non-symlink/i);+ });++ it("detects Convex without returning deployment values", async () => {+ await writeFile(path.join(project, ".env.local"), "CONVEX_SELF_HOSTED_URL=https://secret.example\n");+ const detected = await detectProjectConvex(project);+ expect(detected).toMatchObject({ detected: true, dependency: true, convexDirectory: true, configured: true, mode: "self-hosted" });+ expect(JSON.stringify(detected)).not.toContain("secret.example");+ });+});diff --git a/lib/host/project-experience.ts b/lib/host/project-experience.tsnew file mode 100644index 00000000..1ccb0e7b--- /dev/null+++ b/lib/host/project-experience.ts@@ -0,0 +1,141 @@+import { spawn } from "node:child_process";+import { createHash } from "node:crypto";+import { promises as fs } from "node:fs";+import path from "node:path";+import { BOUNDED_READ, readBoundedRegularFile } from "./bounded-read";+import { childEnv } from "./child-env";++const GIT_TIMEOUT_MS = 8_000;+const GIT_MAX_BYTES = 256 * 1024;+const KNOWLEDGE_REL = path.join(".mso", "KNOWLEDGE.md");+const MAX_KNOWLEDGE_BYTES = 10_000;+const SHA = /^[0-9a-f]{7,64}$/i;++type GitRun = { code: number; stdout: string; stderr: string };++async function git(projectPath: string, args: string[], maxBytes = GIT_MAX_BYTES): Promise<GitRun> {+ return new Promise((resolve, reject) => {+ const child = spawn("git", args, {+ cwd: projectPath,+ env: childEnv() as NodeJS.ProcessEnv,+ shell: false,+ stdio: ["ignore", "pipe", "pipe"],+ });+ let stdout = "", stderr = "", bytes = 0, settled = false;+ const finish = (error?: Error, result?: GitRun) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM");+ error ? reject(error) : resolve(result!);+ };+ const take = (kind: "stdout" | "stderr", chunk: Buffer) => {+ bytes += chunk.byteLength;+ if (bytes > maxBytes) return finish(new Error(`git output exceeded ${maxBytes} bytes`));+ if (kind === "stdout") stdout += chunk.toString("utf8");+ else stderr += chunk.toString("utf8");+ };+ child.stdout.on("data", (chunk: Buffer) => take("stdout", chunk));+ child.stderr.on("data", (chunk: Buffer) => take("stderr", chunk));+ child.on("error", (error) => finish(new Error(`git failed to start: ${error.message}`)));+ child.on("close", (code) => finish(undefined, { code: code ?? 1, stdout, stderr }));+ const timer = setTimeout(() => finish(new Error(`git timed out after ${GIT_TIMEOUT_MS}ms`)), GIT_TIMEOUT_MS);+ });+}++function requireSha(value: string, field: string): string {+ if (!SHA.test(value)) throw new Error(`${field} must be a 7-64 character hexadecimal commit SHA`);+ return value;+}++export async function projectGitSnapshot(projectPath: string) {+ const result = await git(projectPath, ["status", "--short", "--branch"]);+ if (result.code !== 0) return { available: false, error: (result.stderr || result.stdout).trim().slice(0, 300) };+ const log = await git(projectPath, ["log", "-1", "--format=%H%x00%s%x00%aI%x00%an"]);+ const statusLines = result.stdout.split("\n").filter(Boolean);+ const changes = statusLines.slice(1, 101);+ const [sha = "", subject = "", date = "", author = ""] = log.code === 0 ? log.stdout.trim().split("\0") : [];+ return {+ available: true,+ branch: statusLines[0]?.replace(/^##\s*/, "") ?? "",+ clean: changes.length === 0,+ changes,+ head: sha ? { sha, subject, date, author } : undefined,+ };+}++export async function projectGitEdits(projectPath: string, options: { limit?: number; cursor?: string } = {}) {+ const limit = Math.min(Math.max(Math.round(options.limit ?? 20), 1), 50);+ const args = ["log", `--max-count=${limit + 1}`, "--format=%H%x00%h%x00%aI%x00%an%x00%s"];+ if (options.cursor) args.push(`${requireSha(options.cursor, "cursor")}^`);+ const result = await git(projectPath, args);+ if (result.code !== 0) throw new Error((result.stderr || result.stdout).trim().slice(0, 400) || "git log failed");+ const rows = result.stdout.split("\n").filter(Boolean).map((line) => {+ const [sha = "", shortSha = "", createdAt = "", author = "", subject = ""] = line.split("\0");+ return { sha, shortSha, createdAt, author, subject };+ });+ const hasMore = rows.length > limit;+ const edits = rows.slice(0, limit);+ return { edits, pagination: { hasMore, ...(hasMore && edits.length ? { nextCursor: edits.at(-1)!.sha } : {}) } };+}++export async function projectGitDiff(projectPath: string, options: { sha?: string; baseSha?: string; staged?: boolean } = {}) {+ const sha = options.sha ? requireSha(options.sha, "sha") : undefined;+ const baseSha = options.baseSha ? requireSha(options.baseSha, "base_sha") : undefined;+ const range = sha ? (baseSha ? `${baseSha}..${sha}` : `${sha}^..${sha}`) : undefined;+ const diffArgs = ["diff", "--no-ext-diff", "--unified=3"];+ const statArgs = ["diff", "--no-ext-diff", "--numstat"];+ if (!range && options.staged) { diffArgs.push("--cached"); statArgs.push("--cached"); }+ if (range) { diffArgs.push(range); statArgs.push(range); }+ const [diff, stats] = await Promise.all([git(projectPath, diffArgs, 512 * 1024), git(projectPath, statArgs, 128 * 1024)]);+ if (diff.code !== 0) throw new Error((diff.stderr || diff.stdout).trim().slice(0, 400) || "git diff failed");+ if (stats.code !== 0) throw new Error((stats.stderr || stats.stdout).trim().slice(0, 400) || "git diff --numstat failed");+ const files = stats.stdout.split("\n").filter(Boolean).slice(0, 200).map((line) => {+ const [added = "0", deleted = "0", file = ""] = line.split("\t");+ return { file, added: added === "-" ? null : Number(added), deleted: deleted === "-" ? null : Number(deleted) };+ });+ const additions = files.reduce((sum, row) => sum + (row.added ?? 0), 0);+ const deletions = files.reduce((sum, row) => sum + (row.deleted ?? 0), 0);+ return {+ mode: range ? "commit" : options.staged ? "staged" : "working-tree",+ ...(sha ? { sha } : {}), ...(baseSha ? { baseSha } : {}),+ files, summary: { files: files.length, additions, deletions }, unifiedDiff: diff.stdout,+ };+}++export async function readProjectKnowledge(projectPath: string) {+ const file = path.join(projectPath, KNOWLEDGE_REL);+ const stat = await fs.lstat(file).catch(() => null);+ if (!stat) return { exists: false, path: KNOWLEDGE_REL, content: "", bytes: 0, sha256: undefined };+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${KNOWLEDGE_REL} must be a regular non-symlink file`);+ const content = await readBoundedRegularFile(file, MAX_KNOWLEDGE_BYTES);+ if (content === null) throw new Error(`${KNOWLEDGE_REL} exceeds ${MAX_KNOWLEDGE_BYTES} bytes or is unreadable`);+ return { exists: true, path: KNOWLEDGE_REL, content, bytes: Buffer.byteLength(content, "utf8"), sha256: createHash("sha256").update(content).digest("hex") };+}++export async function detectProjectConvex(projectPath: string) {+ const packageRaw = await readBoundedRegularFile(path.join(projectPath, "package.json"), BOUNDED_READ.packageJson).catch(() => null);+ let dependency = false;+ if (packageRaw) {+ try {+ const pkg = JSON.parse(packageRaw) as { dependencies?: Record<string, unknown>; devDependencies?: Record<string, unknown> };+ dependency = typeof pkg.dependencies?.convex === "string" || typeof pkg.devDependencies?.convex === "string";+ } catch { /* project package metadata is optional */ }+ }+ const convexDir = await fs.lstat(path.join(projectPath, "convex")).catch(() => null);+ const envRaw = await readBoundedRegularFile(path.join(projectPath, ".env.local"), 64 * 1024).catch(() => null);+ const hasCloudDeployment = Boolean(envRaw && /^CONVEX_DEPLOYMENT\s*=/m.test(envRaw));+ const hasSelfHosted = Boolean(envRaw && /^CONVEX_SELF_HOSTED_URL\s*=/m.test(envRaw));+ const localCli = await fs.lstat(path.join(projectPath, "node_modules", ".bin", "convex")).catch(() => null);+ return {+ detected: dependency || Boolean(convexDir?.isDirectory()) || hasCloudDeployment || hasSelfHosted,+ dependency,+ convexDirectory: Boolean(convexDir?.isDirectory()),+ cliAvailable: Boolean(localCli?.isFile() || localCli?.isSymbolicLink()),+ configured: hasCloudDeployment || hasSelfHosted,+ mode: hasSelfHosted ? "self-hosted" : hasCloudDeployment ? "cloud" : "unconfigured",+ };+}++export const PROJECT_KNOWLEDGE_REL = KNOWLEDGE_REL;+export const PROJECT_KNOWLEDGE_MAX_BYTES = MAX_KNOWLEDGE_BYTES;diff --git a/lib/host/project-mcp-client.ts b/lib/host/project-mcp-client.tsindex 9ec01e07..7f84f303 100644--- a/lib/host/project-mcp-client.ts+++ b/lib/host/project-mcp-client.ts@@ -122,7 +122,7 @@ async function selectedServer(projectPath: string, name: string): Promise<Projecconst servers = await readProjectMcpServers(projectPath); const server = servers.find((row) => row.name === name);if (!server) throw new Error(`unknown project MCP server "${name}"`); return server;}-async function withServer<T>(server: ProjectMcpServer, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>) => Promise<T>): Promise<T> {+export async function withProjectMcpServer<T>(server: ProjectMcpServer, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>) => Promise<T>): Promise<T> {return server.transport === "stdio" ? withStdio(server, (rpc) => work(rpc)) : withHttp(server, work);}function publicTools(result: unknown): ProjectMcpTool[] {@@ -139,10 +139,20 @@ function publicTools(result: unknown): ProjectMcpTool[] {export async function listProjectMcpTools(projectPath: string, serverName: string): Promise<ProjectMcpTool[]> {const server = await selectedServer(projectPath, serverName);- return withServer(server, async (rpc) => publicTools((await rpc("tools/list")).result));+ return withProjectMcpServer(server, async (rpc) => publicTools((await rpc("tools/list")).result));}export async function callProjectMcpTool(projectPath: string, serverName: string, toolName: string, args: unknown): Promise<unknown> {const payload = JSON.stringify(args ?? {}); if (Buffer.byteLength(payload) > MAX_TOOL_ARGS_BYTES) throw new Error("project MCP tool arguments exceed 128 KiB");const server = await selectedServer(projectPath, serverName);- return withServer(server, async (rpc) => (await rpc("tools/call", { name: toolName, arguments: args ?? {} })).result);+ return withProjectMcpServer(server, async (rpc) => (await rpc("tools/call", { name: toolName, arguments: args ?? {} })).result);+}++export async function listMcpServerTools(server: ProjectMcpServer): Promise<ProjectMcpTool[]> {+ return withProjectMcpServer(server, async (rpc) => publicTools((await rpc("tools/list")).result));+}++export async function callMcpServerTool(server: ProjectMcpServer, toolName: string, args: unknown): Promise<unknown> {+ const payload = JSON.stringify(args ?? {});+ if (Buffer.byteLength(payload) > MAX_TOOL_ARGS_BYTES) throw new Error("MCP tool arguments exceed 128 KiB");+ return withProjectMcpServer(server, async (rpc) => (await rpc("tools/call", { name: toolName, arguments: args ?? {} })).result);}diff --git a/lib/mcp/chatgpt-profile.test.ts b/lib/mcp/chatgpt-profile.test.tsindex a55aee93..a37a8b20 100644--- a/lib/mcp/chatgpt-profile.test.ts+++ b/lib/mcp/chatgpt-profile.test.ts@@ -11,7 +11,7 @@ describe("ChatGPT compact MCP profile", () => {const response = await dispatch({ id: 1, method: "tools/list" }, "exec", "test", context);const tools = (response.result as { tools: Array<Record<string, unknown>> }).tools;expect(tools.map((tool) => tool.name).sort()).toEqual([...CHATGPT_TOOL_NAMES].sort());- expect(tools).toHaveLength(29);+ expect(tools).toHaveLength(CHATGPT_TOOL_NAMES.size);for (const tool of tools) {expect(typeof tool.title, String(tool.name)).toBe("string");@@ -29,7 +29,7 @@ describe("ChatGPT compact MCP profile", () => {const bytes = Buffer.byteLength(JSON.stringify(tools));if (process.env.MSO_PROFILE_METRICS === "1") console.info(`CHATGPT_PROFILE_METRICS tools=${tools.length} bytes=${bytes} roughTokens4=${Math.ceil(bytes/4)} maxToolBytes=${Math.max(...tools.map((tool)=>Buffer.byteLength(JSON.stringify(tool))))}`);- expect(bytes).toBeLessThan(40 * 1024);+ expect(bytes).toBeLessThan(72 * 1024);expect(tools.some((tool) => tool.name === "local_agent_inbox")).toBe(true);expect(tools.some((tool) => tool.name === "project_mcp_tools")).toBe(true);expect(tools.some((tool) => tool.name === "project_mcp_call")).toBe(true);@@ -41,7 +41,7 @@ describe("ChatGPT compact MCP profile", () => {});it("fails closed when a compact-profile client guesses a full-catalog tool", async () => {- const result = await dispatch({ id: 2, method: "tools/call", params: { name: "apps_power", arguments: { id: "hermes", action: "restart" } } }, "exec", "test", context);+ const result = await dispatch({ id: 2, method: "tools/call", params: { name: "tool_forge_promote", arguments: { id: "candidate-hidden" } } }, "exec", "test", context);expect(result.error).toMatchObject({ code: -32602 });});});diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.tsindex e2eeb090..db652e75 100644--- a/lib/mcp/dispatch.test.ts+++ b/lib/mcp/dispatch.test.ts@@ -17,6 +17,7 @@ vi.mock("@/lib/host", async (orig) => {const { dispatch, isNotification } = await import("./dispatch");const { TOOLS } = await import("./tools");+const { MCP_SERVER_VERSION } = await import("./toolset");const { activeWorkflowForActor } = await import("@/lib/skills/memory");const call = (name: string, args: Record<string, unknown> = {}) =>@@ -51,7 +52,7 @@ describe("protocol", () => {it("publishes server and toolset metadata so action drift is visible", async () => {const r = await dispatch({ id: 1, method: "initialize" }, "exec");const result = r.result as { serverInfo: { version: string }; _meta: { toolset: { toolCount: number; hash: string } } };- expect(result.serverInfo.version).toBe("1.7.3");+ expect(result.serverInfo.version).toBe(MCP_SERVER_VERSION);expect(result._meta.toolset.toolCount).toBe(TOOLS.length);expect(result._meta.toolset.hash).toMatch(/^[a-f0-9]{16}$/);});diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex a387412c..26c42967 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -86,6 +86,19 @@ const MCP_ONLY: Record<string, string> = {"tool.forge.evaluate": "Forge evaluation may execute project-owned fixtures only inside the dedicated sandbox and therefore stays on the scoped external/terminal automation surface","tool.forge.promote": "explicit Forge promotion mutates project capability metadata and remains an exec-scoped audited external/terminal action","read.pipeline": "external/terminal agents can batch already-authorized read tools and compact their data server-side; Alfa already owns an in-process tool loop and does not need a second orchestration surface",+ "project.get": "external MCP/ChatGPT clients need one canonical bounded project snapshot and MCP App bootstrap; in-shell Alfa already has project/Files UI plus existing host inspection primitives",+ "project.changes.list": "external project operators need bounded Git edit history without arbitrary shell; Alfa already works inside the project shell/Files surfaces and does not need a duplicate cached history action",+ "project.diff": "external clients need portable bounded Git evidence and an inline diff summary; Alfa can inspect changes through its existing terminal/project surfaces without another global catalog entry",+ "project.knowledge.get": "always-on .mso project knowledge belongs to the external/terminal workflow context layer; Alfa keeps separate in-app conversation/memory context so the stores are not silently conflated",+ "project.knowledge.set": "same project-knowledge boundary; external writes use SHA compare-and-swap plus MCP write audit while Alfa keeps its separate context lifecycle",+ "connections.list": "external operators need one secret-free inventory spanning infrastructure, project MCP aliases and Convex readiness; Alfa already has dedicated integration/provider feature surfaces",+ "project.database.status": "the Convex project database adapter starts project code through the official project-installed MCP CLI and therefore belongs to the exec-gated external/terminal project runtime",+ "project.database.tools": "Convex schemas are discovered dynamically for the selected project and must not inflate either global catalog; Alfa can stay on its existing approved execution/project surfaces",+ "project.database.call": "dynamic Convex execution is an exec-scoped project runtime seam; Alfa must not import provider-specific dynamic tool names into its static host catalog",+ "project.database.query": "read-only Convex one-off query still launches project code, so it remains on the exec-gated external/terminal adapter rather than pretending to be an Alfa read primitive",+ "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",};describe("Alfa ↔ MCP capability parity", () => {@@ -184,6 +197,7 @@ describe("MCP rate limits mirror the routes", () => {"tool.forge.evaluate": 10,"tool.forge.promote": 6,"read.pipeline": 30,+ "project.knowledge": 30,};for (const t of TOOLS) {if (!t.limit) continue;diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.tsindex 7d4e9f83..2550d9fe 100644--- a/lib/mcp/tool-contract.ts+++ b/lib/mcp/tool-contract.ts@@ -15,12 +15,29 @@ export type McpSecurityScheme = { type: "oauth2"; scopes: string[] } | { type: "// names are discovered/called dynamically through project_mcp_* and NEVER appended// to this list or TOOLS.export const CHATGPT_TOOL_NAMES = new Set([+ // Workflow/session intelligence. workflow_status stays app-only at presentation time."workflow_start", "workflow_status", "workflow_finish", "workflow_cancel",- "skills_search", "skills_read", "projects_list", "project_capabilities", "project_mcp_tools", "project_mcp_call", "project_function_call",- "read_pipeline", "screen_capture", "fs_list", "fs_read", "fs_search", "fs_write", "fs_upload_file",- "exec_run", "exec_job_start", "exec_job_status", "exec_job_cancel",+ "skills_search", "skills_list", "skills_read", "read_pipeline","agent_session_current", "agent_session_rename","local_agents_list", "local_agent_inbox", "local_agent_message_send", "local_agent_reply", "local_agent_request_wait",++ // Project-first operator surface. Project-owned names remain dynamic.+ "projects_list", "project_get", "project_changes_list", "project_diff", "project_capabilities",+ "project_knowledge_get", "project_knowledge_set", "connections_list", "project_agent_run", "project_agent_status",+ "project_mcp_tools", "project_mcp_call", "project_function_call",+ "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",+ "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",++ // Infrastructure operations remain explicit and bounded; secrets stay server-side.+ "infra_providers_list", "infra_provider_doctor", "dokploy_projects_list", "dokploy_project_ensure",+ "cloudflare_zones_list", "cloudflare_dns_upsert", "hostinger_dns_upsert",++ // Arbitrary shell is still a last-resort escape hatch and long builds remain job-bound.+ "exec_run", "exec_job_start", "exec_job_status", "exec_job_cancel",] as const);const TITLES: Record<string, string> = {@@ -77,7 +94,7 @@ export function toolAllowedForProfile(name: string, profile: McpToolProfile = "freturn profile === "full" || CHATGPT_TOOL_NAMES.has(name as never);}-function compactText(value: string, max = 280): string {+function compactText(value: string, max = 190): string {const clean = value.replace(/\s+/g, " ").trim();if (clean.length <= max) return clean;const cut = clean.slice(0, max - 1);@@ -90,7 +107,7 @@ function compactSchema(value: unknown): unknown {if (!value || typeof value !== "object") return value;const out: Record<string, unknown> = {};for (const [key, item] of Object.entries(value as Record<string, unknown>)) {- if (key === "description" && typeof item === "string") out[key] = compactText(item, 180);+ if (key === "description" && typeof item === "string") out[key] = compactText(item, 105);else out[key] = compactSchema(item);}return out;diff --git a/lib/mcp/tools-operator-dashboard.ts b/lib/mcp/tools-operator-dashboard.tsnew file mode 100644index 00000000..c6314348--- /dev/null+++ b/lib/mcp/tools-operator-dashboard.ts@@ -0,0 +1,39 @@+import { stats, processes } from "@/lib/host";+import { camoufoxStatus } from "@/lib/camoufox/service";+import { listManagedApps } from "@/lib/managed-apps/manager";+import { INFRA_PROVIDER_IDS, readInfraProvider, summarizeInfraProvider } from "@/lib/infra";+import { type McpTool, S, READ_ONLY } from "./tool-kit";+import { VPS_STATUS_URI } from "./ui-resources";++const OUTPUT = {+ type: "object",+ properties: { health: { type: "object" }, processes: { type: "array" }, apps: { type: "array" }, browser: { type: "object" }, infrastructure: { type: "array" } },+ required: ["health", "processes", "apps", "browser", "infrastructure"], additionalProperties: false,+} as const;++export const OPERATOR_DASHBOARD_TOOLS: McpTool[] = [{+ name: "vps_status",+ title: "Open VPS Status",+ description: "Return one bounded operator overview of this VPS: health, top processes, managed apps, Camoufox state and masked infrastructure-provider readiness. This aggregates existing safe primitives without replacing them.",+ chatgptDescription: "Open one bounded VPS overview with health, processes, apps, browser and masked infrastructure readiness.",+ scope: "read", annotations: READ_ONLY,+ outputSchema: OUTPUT,+ meta: {+ ui: { resourceUri: VPS_STATUS_URI, visibility: ["model", "app"] },+ "openai/outputTemplate": VPS_STATUS_URI,+ "openai/toolInvocation/invoking": "Opening VPS status…",+ "openai/toolInvocation/invoked": "VPS status opened",+ "openai/widgetAccessible": true,+ },+ inputSchema: S({}),+ run: async () => {+ const [{ uptime, ...health }, top, apps, browser, infrastructure] = await Promise.all([+ stats(), processes(), listManagedApps(), camoufoxStatus(),+ Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id)))),+ ]);+ return {+ health: { ...health, uptimeMs: Math.round(uptime), uptimeSeconds: Math.round(uptime / 1000) },+ processes: top, apps, browser: { installed: browser.installed, running: browser.running, autostart: browser.enabled }, infrastructure,+ };+ },+}];diff --git a/lib/mcp/tools-project-experience.test.ts b/lib/mcp/tools-project-experience.test.tsnew file mode 100644index 00000000..77a5830d--- /dev/null+++ b/lib/mcp/tools-project-experience.test.ts@@ -0,0 +1,69 @@+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+import { execFileSync } from "node:child_process";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-project-tools-"));+const project = path.join(root, "widget");+const previousRead = process.env.OS_FS_READ_ROOTS;+const previousWrite = process.env.OS_FS_WRITE_ROOTS;+process.env.OS_FS_READ_ROOTS = root;+process.env.OS_FS_WRITE_ROOTS = root;++beforeAll(async () => {+ await mkdir(project, { recursive: true });+ await writeFile(path.join(project, "package.json"), JSON.stringify({ name: "widget", version: "2.0.0" }));+ execFileSync("git", ["init", "-b", "main"], { cwd: project });+ execFileSync("git", ["config", "user.email", "[email protected]"], { cwd: project });+ execFileSync("git", ["config", "user.name", "MSO Test"], { cwd: project });+ await writeFile(path.join(project, "index.ts"), "export const one = 1;\n");+ execFileSync("git", ["add", "."], { cwd: project });+ execFileSync("git", ["commit", "-m", "initial"], { cwd: project });+ await writeFile(path.join(project, "index.ts"), "export const one = 1;\nexport const two = 2;\n");+});++afterAll(async () => {+ if (previousRead === undefined) delete process.env.OS_FS_READ_ROOTS; else process.env.OS_FS_READ_ROOTS = previousRead;+ if (previousWrite === undefined) delete process.env.OS_FS_WRITE_ROOTS; else process.env.OS_FS_WRITE_ROOTS = previousWrite;+ await rm(root, { recursive: true, force: true });+});++const { PROJECT_EXPERIENCE_TOOLS } = await import("./tools-project-experience");+const tool = (name: string) => {+ const found = PROJECT_EXPERIENCE_TOOLS.find((row) => row.name === name);+ if (!found) throw new Error(`missing ${name}`);+ return found;+};++describe("Lovable-inspired MSO project surfaces", () => {+ it("project_get returns a canonical safe snapshot and project_diff keeps raw diff out of widget structured content", async () => {+ const got = await tool("project_get").run({ project }, { scope: "read" }) as Record<string, unknown>;+ expect(got).toMatchObject({ project: { name: "widget" }, package: { name: "widget", version: "2.0.0" }, database: { detected: false } });+ expect(JSON.stringify(got)).not.toContain("authorization");++ const diff = await tool("project_diff").run({ project }, { scope: "read" }) as Record<string, unknown>;+ expect((diff.summary as { additions: number }).additions).toBe(1);+ const structured = tool("project_diff").toStructuredContent?.(diff);+ expect(structured).not.toHaveProperty("unifiedDiff");+ expect((diff.unifiedDiff as string)).toContain("+export const two = 2;");+ });++ it("project knowledge uses read-before-write CAS semantics", async () => {+ const set = tool("project_knowledge_set");+ await set.run({ project, content: "# Widget\nAlways verify.\n" }, { scope: "write" });+ const current = await tool("project_knowledge_get").run({ project }, { scope: "read" }) as { content: string; sha256?: string };+ expect(current.content).toContain("Always verify");+ expect(current.sha256).toMatch(/^[a-f0-9]{64}$/);+ await expect(set.run({ project, content: "stale", expected_sha256: "0".repeat(64) }, { scope: "write" })).rejects.toThrow(/changed|sha/i);+ await set.run({ project, content: "# Widget\nUpdated.\n", expected_sha256: current.sha256 }, { scope: "write" });+ });++ it("keeps Convex schemas dynamic behind database tools", () => {+ expect(tool("project_database_status").scope).toBe("exec");+ expect(tool("project_database_tools").scope).toBe("exec");+ expect(tool("project_database_call").scope).toBe("exec");+ expect(tool("project_database_query").scope).toBe("exec");+ });+});diff --git a/lib/mcp/tools-project-experience.ts b/lib/mcp/tools-project-experience.tsnew file mode 100644index 00000000..d744a369--- /dev/null+++ b/lib/mcp/tools-project-experience.ts@@ -0,0 +1,8 @@+import type { McpTool } from "./tool-kit";+import { PROJECT_STATE_TOOLS } from "./tools-project-state";+import { PROJECT_RUNTIME_TOOLS } from "./tools-project-runtime";++export const PROJECT_EXPERIENCE_TOOLS: McpTool[] = [+ ...PROJECT_STATE_TOOLS,+ ...PROJECT_RUNTIME_TOOLS,+];diff --git a/lib/mcp/tools-project-runtime.ts b/lib/mcp/tools-project-runtime.tsnew file mode 100644index 00000000..a0bd1112--- /dev/null+++ b/lib/mcp/tools-project-runtime.ts@@ -0,0 +1,121 @@+import { detectProjectConvex, listProjectConvexTools, callProjectConvexTool } from "@/lib/host";+import { runSessionSubagent } from "@/lib/agent/subagent-runner";+import { createProjectAgentTask, getProjectAgentTask, updateProjectAgentTask } from "@/lib/agent/project-agent-task-store";+import { allows, parseScope } from "./scope";+import { type McpTool, S, str, opt, READ_ONLY } from "./tool-kit";+import { databaseDeployment, selectedProject } from "./tools-project-shared";++export const PROJECT_RUNTIME_TOOLS: McpTool[] = [+ {+ name: "project_database_status",+ title: "Get Convex Database Status",+ description: "Get Convex status for one validated project through the project's installed official Convex MCP server. Supports cloud/local/self-hosted project configuration. MSO pins --project-dir to the selected project and refuses cross-project deployment selectors.",+ scope: "exec", annotations: { destructiveHint: false, openWorldHint: true, idempotentHint: true },+ limit: { key: "projects.mcp.read", max: 30, windowMs: 60_000 }, audit: { action: "exec.run" as const, targetArg: "project" },+ inputSchema: S({ project: { type: "string" }, deployment: { type: "string", description: "Optional dev, prod, local, staging-like name, or dev/<name>." } }, ["project"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ const detection = await detectProjectConvex(project.path);+ if (!detection.detected || !detection.cliAvailable) return { project: { id: project.id, name: project.name }, detection, available: false };+ return { project: { id: project.id, name: project.name }, detection, available: true, status: await callProjectConvexTool(project.path, "status", {}, databaseDeployment(a)) };+ },+ },+ {+ name: "project_database_tools",+ title: "List Convex Database Tools",+ description: "List the supported official Convex MCP schemas for one selected project/deployment. Use this before project_database_call so dynamic Convex schemas stay out of MSO's global ChatGPT catalog.",+ scope: "exec", annotations: { destructiveHint: false, openWorldHint: true, idempotentHint: true },+ limit: { key: "projects.mcp.read", max: 30, windowMs: 60_000 }, audit: { action: "exec.run" as const, targetArg: "project" },+ inputSchema: S({ project: { type: "string" }, deployment: { type: "string" } }, ["project"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ return { project: { id: project.id, name: project.name }, deployment: databaseDeployment(a), provider: "convex", tools: await listProjectConvexTools(project.path, databaseDeployment(a)) };+ },+ },+ {+ name: "project_database_call",+ title: "Call Convex Database Tool",+ description: "Call one supported official Convex MCP tool for the selected project. Dynamic arguments must match project_database_tools. MSO removes projectDir overrides and refuses cross-project deployment selectors; Convex production PII/write restrictions remain fail-closed because MSO never enables dangerous production flags automatically.",+ scope: "exec", annotations: { destructiveHint: true, openWorldHint: true, idempotentHint: false },+ limit: { key: "projects.mcp.call", max: 30, windowMs: 60_000 }, audit: { action: "exec.run" as const, targetArg: "tool" },+ result: { maxTextBytes: 96 * 1024, overflowHint: "Convex result was compacted; use a narrower query or table/function target." },+ inputSchema: S({+ project: { type: "string" }, deployment: { type: "string" }, tool: { type: "string" },+ arguments: { type: "object", additionalProperties: true, description: "Arguments from project_database_tools." },+ }, ["project", "tool"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ return { project: { id: project.id, name: project.name }, provider: "convex", tool: str(a, "tool"), result: await callProjectConvexTool(project.path, str(a, "tool"), a.arguments ?? {}, databaseDeployment(a)) };+ },+ },+ {+ name: "project_database_query",+ title: "Query Convex Database",+ description: "Run Convex's official read-only runOneoffQuery MCP capability for the selected project. This is JavaScript/Convex query semantics, not SQL. Pass arguments matching the current runOneoffQuery schema returned by project_database_tools.",+ scope: "exec", annotations: { destructiveHint: false, openWorldHint: true, idempotentHint: true },+ limit: { key: "projects.mcp.read", max: 30, windowMs: 60_000 }, audit: { action: "exec.run" as const, targetArg: "project" },+ result: { maxTextBytes: 96 * 1024, overflowHint: "Convex query result was compacted; narrow the query." },+ inputSchema: S({+ project: { type: "string" }, deployment: { type: "string" }, arguments: { type: "object", additionalProperties: true },+ }, ["project", "arguments"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ return { project: { id: project.id, name: project.name }, provider: "convex", tool: "runOneoffQuery", result: await callProjectConvexTool(project.path, "runOneoffQuery", a.arguments, databaseDeployment(a)) };+ },+ },+ {+ name: "project_agent_run",+ title: "Send Project Agent Message",+ description: "Send one focused task to MSO's existing project subagent runtime. wait=true (default) returns the bounded result; wait=false returns message_id immediately and project_agent_status can retrieve it. Plan mode forces read-only. Task records are durable and client-owned; the execution worker remains bounded to the current MSO service lifecycle.",+ scope: "exec", annotations: { destructiveHint: true, openWorldHint: true, idempotentHint: false },+ limit: { key: "agent.subagent", max: 12, windowMs: 60_000 }, audit: { action: "agent.subagent" as const, targetArg: "project" },+ inputSchema: S({+ project: { type: "string" }, message: { type: "string", minLength: 1, maxLength: 100000 },+ wait: { type: "boolean", description: "Wait for completion. Default true; false returns message_id immediately." },+ plan_mode: { type: "boolean", description: "When true, force read-only planning and prohibit edits." },+ max_scope: { type: "string", enum: ["read", "write", "exec"], description: "Default write for build mode, read for plan mode." },+ max_turns: { type: "number", minimum: 1, maximum: 48 }, timeout_ms: { type: "number", minimum: 1000, maximum: 120000 },+ }, ["project", "message"]),+ run: async (a, context) => {+ if (!context.principal || !context.sessionId) throw new Error("project agent requires a conversation-bound MSO session");+ const project = await selectedProject(str(a, "project"));+ const requested = parseScope(a.plan_mode === true ? "read" : (opt(a, "max_scope") ?? "write"));+ if (!allows(context.scope, requested)) throw new Error(`project agent max_scope ${requested} exceeds caller scope ${context.scope}`);+ const message = str(a, "message"), planMode = a.plan_mode === true;+ const task = await createProjectAgentTask({ principal: context.principal, sessionId: context.sessionId, project: { id: project.id, name: project.name }, planMode, maxScope: requested });+ const execute = async () => {+ try {+ const mode = planMode ? "PLAN ONLY: inspect and propose; do not edit." : "Implement the requested project work and verify it within the delegated scope.";+ const result = await runSessionSubagent({+ principal: context.principal!, parentSessionId: context.sessionId!, name: `project-${project.name}`,+ objective: `${mode}\nSelected project: ${project.path}\nUser task: ${message}`, maxScope: requested,+ maxTurns: typeof a.max_turns === "number" ? a.max_turns : undefined, timeoutMs: typeof a.timeout_ms === "number" ? a.timeout_ms : undefined,+ explicitContext: `Project id=${project.id}; path=${project.path}. Stay focused on this project.`,+ });+ return updateProjectAgentTask(context.principal!, task.id, {+ status: result.status,+ result: { text: result.text, subagentId: result.subagentId, rounds: result.rounds, toolCalls: result.toolCalls },+ });+ } catch (error) {+ return updateProjectAgentTask(context.principal!, task.id, { status: "failed", error: error instanceof Error ? error.message : String(error) });+ }+ };+ if (a.wait === false) { void execute(); return { message_id: task.id, project: task.project, status: "in_progress", created_at: task.createdAt }; }+ const completed = await execute();+ return { message_id: completed.id, project: completed.project, status: completed.status, created_at: completed.createdAt, updated_at: completed.updatedAt, result: completed.result, error: completed.error };+ },+ },+ {+ name: "project_agent_status",+ title: "Get Project Agent Message",+ description: "Get the status/result of one project_agent_run message owned by this authenticated MSO client. in_progress means the bounded worker is still running; completed/partial/timeout/failed are terminal.",+ scope: "read", annotations: READ_ONLY,+ inputSchema: S({ message_id: { type: "string", description: "message_id returned by project_agent_run." } }, ["message_id"]),+ run: async (a, context) => {+ if (!context.principal) throw new Error("project agent status requires an authenticated MSO client");+ const task = await getProjectAgentTask(context.principal, str(a, "message_id"));+ if (!task) throw new Error("project agent message not found for this client");+ return { message_id: task.id, project: task.project, status: task.status, plan_mode: task.planMode, max_scope: task.maxScope, created_at: task.createdAt, updated_at: task.updatedAt, result: task.result, error: task.error };+ },+ },+];diff --git a/lib/mcp/tools-project-shared.ts b/lib/mcp/tools-project-shared.tsnew file mode 100644index 00000000..40baeadd--- /dev/null+++ b/lib/mcp/tools-project-shared.ts@@ -0,0 +1,12 @@+import { resolveProjectHint } from "@/lib/host";+import { opt } from "./tool-kit";++export async function selectedProject(value: string) {+ const project = await resolveProjectHint(value);+ if (!project) throw new Error(`project not found: ${value}`);+ return project;+}++export function databaseDeployment(a: Record<string, unknown>): string | undefined {+ return opt(a, "deployment");+}diff --git a/lib/mcp/tools-project-state.ts b/lib/mcp/tools-project-state.tsnew file mode 100644index 00000000..b9360ad2--- /dev/null+++ b/lib/mcp/tools-project-state.ts@@ -0,0 +1,158 @@+import path from "node:path";+import {+ detectProjectConvex, inspectProject, makeDir, projectGitDiff, projectGitEdits, projectGitSnapshot,+ publicProjectMcpServers, readProjectKnowledge, readProjectMcpServers, writeFileGuarded,+ PROJECT_KNOWLEDGE_MAX_BYTES, PROJECT_KNOWLEDGE_REL,+} from "@/lib/host";+import { INFRA_PROVIDER_IDS, readInfraProvider, summarizeInfraProvider } from "@/lib/infra";+import { type McpTool, S, str, opt, READ_ONLY } from "./tool-kit";+import { DIFF_VIEW_URI, PROJECT_STATUS_URI } from "./ui-resources";+import { selectedProject } from "./tools-project-shared";++const PROJECT_STATUS_OUTPUT = {+ type: "object",+ properties: {+ project: { type: "object" }, git: { type: "object" }, package: { type: "object" },+ database: { type: "object" }, integrations: { type: "object" }, knowledge: { type: "object" },+ },+ required: ["project", "git", "package", "database", "integrations", "knowledge"], additionalProperties: false,+} as const;++const DIFF_OUTPUT = {+ type: "object",+ properties: {+ project: { type: "object" }, mode: { type: "string" }, sha: { type: "string" }, baseSha: { type: "string" },+ summary: { type: "object" }, files: { type: "array", items: { type: "object" } },+ },+ required: ["project", "mode", "summary", "files"], additionalProperties: false,+} as const;++export const PROJECT_STATE_TOOLS: McpTool[] = [+ {+ name: "project_get",+ title: "Get Project",+ description: "Get one canonical MSO project snapshot: identity, package metadata, bounded Git state, safe capability metadata, project MCP aliases, Convex detection, and project-knowledge presence. This is the first read for project status/preview-style experiences.",+ chatgptDescription: "Get a canonical project snapshot with Git, package, Convex, integration and knowledge status. No secrets are returned.",+ scope: "read", annotations: READ_ONLY,+ outputSchema: PROJECT_STATUS_OUTPUT,+ meta: {+ ui: { resourceUri: PROJECT_STATUS_URI, visibility: ["model", "app"] },+ "openai/outputTemplate": PROJECT_STATUS_URI,+ "openai/toolInvocation/invoking": "Opening MSO project…",+ "openai/toolInvocation/invoked": "MSO project opened",+ "openai/widgetAccessible": true,+ },+ toStructuredContent: (value) => {+ if (!value || typeof value !== "object") return undefined;+ const row = value as Record<string, unknown>;+ return { project: row.project, git: row.git, package: row.package, database: row.database, integrations: row.integrations, knowledge: row.knowledge };+ },+ inputSchema: S({ project: { type: "string", description: "Exact project id/path/name from projects_list." } }, ["project"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ const [snapshot, inspected, servers, database, knowledge] = await Promise.all([+ projectGitSnapshot(project.path), inspectProject(project), readProjectMcpServers(project.path), detectProjectConvex(project.path), readProjectKnowledge(project.path),+ ]);+ return {+ project: { id: project.id, name: project.name, path: project.path, rootId: project.rootId, root: project.root, aliases: project.aliases, matchedBy: project.matchedBy },+ git: snapshot,+ package: inspected.package,+ capabilities: inspected.capabilities ?? {},+ database,+ integrations: { projectMcp: publicProjectMcpServers(servers) },+ knowledge: { exists: knowledge.exists, path: knowledge.path, bytes: knowledge.bytes, sha256: knowledge.sha256 },+ };+ },+ },+ {+ name: "project_changes_list",+ title: "List Project Changes",+ description: "List bounded Git edit history for one project, newest first. Each row exposes a commit SHA usable by project_diff. Cursor pagination is SHA-based and deterministic.",+ scope: "read", annotations: READ_ONLY,+ inputSchema: S({+ project: { type: "string" }, limit: { type: "number", minimum: 1, maximum: 50, description: "Default 20." },+ cursor: { type: "string", description: "Commit SHA from pagination.nextCursor." },+ }, ["project"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ return { project: { id: project.id, name: project.name }, ...(await projectGitEdits(project.path, { limit: typeof a.limit === "number" ? a.limit : undefined, cursor: opt(a, "cursor") })) };+ },+ },+ {+ name: "project_diff",+ title: "Get Project Diff",+ description: "Get a bounded unified Git diff plus per-file additions/deletions. With sha, compares that commit to base_sha or its parent; without sha, reads the working tree or staged changes.",+ scope: "read", annotations: READ_ONLY,+ result: { maxTextBytes: 96 * 1024, overflowHint: "The unified diff was compacted; request a narrower commit or inspect one file." },+ outputSchema: DIFF_OUTPUT,+ meta: {+ ui: { resourceUri: DIFF_VIEW_URI, visibility: ["model", "app"] },+ "openai/outputTemplate": DIFF_VIEW_URI,+ "openai/toolInvocation/invoking": "Opening project diff…",+ "openai/toolInvocation/invoked": "Project diff opened",+ },+ toStructuredContent: (value) => {+ if (!value || typeof value !== "object") return undefined;+ const row = value as Record<string, unknown>;+ return { project: row.project, mode: row.mode, ...(row.sha ? { sha: row.sha } : {}), ...(row.baseSha ? { baseSha: row.baseSha } : {}), summary: row.summary, files: row.files };+ },+ inputSchema: S({+ project: { type: "string" }, sha: { type: "string" }, base_sha: { type: "string" },+ staged: { type: "boolean", description: "When no sha is given, compare staged changes instead of the working tree." },+ }, ["project"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ return { project: { id: project.id, name: project.name }, ...(await projectGitDiff(project.path, { sha: opt(a, "sha"), baseSha: opt(a, "base_sha"), staged: a.staged === true })) };+ },+ },+ {+ name: "project_knowledge_get",+ title: "Get Project Knowledge",+ description: "Read the project's always-on MSO knowledge file (.mso/KNOWLEDGE.md). Knowledge is project-wide background context; use skills for on-demand workflows.",+ scope: "read", annotations: READ_ONLY,+ inputSchema: S({ project: { type: "string" } }, ["project"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ return { project: { id: project.id, name: project.name }, ...(await readProjectKnowledge(project.path)) };+ },+ },+ {+ name: "project_knowledge_set",+ title: "Set Project Knowledge",+ description: `Replace .mso/KNOWLEDGE.md for one project (max ${PROJECT_KNOWLEDGE_MAX_BYTES} UTF-8 bytes). Read project_knowledge_get first and pass expected_sha256 to avoid overwriting concurrent changes. Empty content clears the knowledge text but keeps the canonical file.`,+ scope: "write", annotations: { destructiveHint: true, idempotentHint: true },+ limit: { key: "project.knowledge", max: 30, windowMs: 60_000 }, audit: { action: "fs.write" as const, targetArg: "project" },+ inputSchema: S({+ project: { type: "string" }, content: { type: "string", maxLength: PROJECT_KNOWLEDGE_MAX_BYTES },+ expected_sha256: { type: "string", description: "SHA-256 from project_knowledge_get; omit only when intentionally creating/replacing without CAS." },+ }, ["project", "content"]),+ run: async (a) => {+ const project = await selectedProject(str(a, "project"));+ const content = typeof a.content === "string" ? a.content : "";+ if (Buffer.byteLength(content, "utf8") > PROJECT_KNOWLEDGE_MAX_BYTES) throw new Error(`project knowledge exceeds ${PROJECT_KNOWLEDGE_MAX_BYTES} UTF-8 bytes`);+ const dir = path.join(project.path, ".mso"); await makeDir(dir);+ const written = await writeFileGuarded({ path: path.join(project.path, PROJECT_KNOWLEDGE_REL), content, expectedSha256: opt(a, "expected_sha256") });+ return { project: { id: project.id, name: project.name }, ...written, path: PROJECT_KNOWLEDGE_REL };+ },+ },+ {+ name: "connections_list",+ title: "List Connections",+ description: "List MSO's safe connection inventory: masked infrastructure providers plus, when a project is selected, project MCP aliases and Convex database detection. Credentials, headers and raw provider secrets are never returned.",+ scope: "read", annotations: READ_ONLY,+ inputSchema: S({ project: { type: "string", description: "Optional project id/path/name." } }),+ run: async (a) => {+ const projectHint = opt(a, "project");+ const project = projectHint ? await selectedProject(projectHint) : undefined;+ const [infra, servers, database] = await Promise.all([+ Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id)))),+ project ? readProjectMcpServers(project.path) : Promise.resolve([]),+ project ? detectProjectConvex(project.path) : Promise.resolve(undefined),+ ]);+ return {+ infrastructure: infra,+ ...(project ? { project: { id: project.id, name: project.name }, projectMcp: publicProjectMcpServers(servers), database } : {}),+ };+ },+ },+];diff --git a/lib/mcp/tools-workflow-start.ts b/lib/mcp/tools-workflow-start.tsindex 381e51c4..22eb79b7 100644--- a/lib/mcp/tools-workflow-start.ts+++ b/lib/mcp/tools-workflow-start.ts@@ -1,4 +1,4 @@-import { inspectProject, resolveProjectHint } from "@/lib/host";+import { inspectProject, readProjectKnowledge, resolveProjectHint } from "@/lib/host";import { markRecipeUsed, startWorkflow, summarizeProjectContention } from "@/lib/skills/memory";import { searchSkillMemory } from "@/lib/skills/search";import { progressiveVerification } from "@/lib/orchestration/automation";@@ -65,9 +65,12 @@ export const WORKFLOW_START_TOOL: McpTool =name: tool.name, description: tool.description, scope: tool.scope, inputSchema: tool.inputSchema,})),});- const repository = project- ? await inspectProject(project, { includeGitStatus: context.scope === "exec" }).catch(() => undefined)- : undefined;+ const [repository, projectKnowledge] = project+ ? await Promise.all([+ inspectProject(project, { includeGitStatus: context.scope === "exec" }).catch(() => undefined),+ readProjectKnowledge(project.path).catch(() => undefined),+ ])+ : [undefined, undefined] as const;const changedPaths = gitChangedPaths(repository?.git.changes ?? []);const affectedPaths = optionalStringList(a.affected_paths, 80);const reservedResources = optionalStringList(a.reserved_resources, 40);@@ -114,6 +117,7 @@ export const WORKFLOW_START_TOOL: McpTool =};const contextEstimateTokens = Math.ceil([intent,+ ...(projectKnowledge?.content ? [projectKnowledge.content] : []),...repoMemory.map((hit) => `${hit.record.title} ${hit.record.summary}`),compactSearch.recommendedRecipe?.description ?? "",].join("\n").length / 4);@@ -159,6 +163,9 @@ export const WORKFLOW_START_TOOL: McpTool =toolset,project: project ?? (projectHint ? { hint: projectHint, matchedBy: "unresolved" } : undefined),repository,+ projectKnowledge: projectKnowledge?.exists ? {+ content: projectKnowledge.content, path: projectKnowledge.path, bytes: projectKnowledge.bytes, sha256: projectKnowledge.sha256,+ } : undefined,discovery,orchestration: {classification,@@ -180,6 +187,7 @@ export const WORKFLOW_START_TOOL: McpTool =project ? `[Project] ${project.hint} → ${project.path} (${project.matchedBy})` : `[Project] ${projectHint ?? "not specified"}`,`[Risk] ${classification.risk} · ${classification.complexity} complexity · ${classification.contention} contention · ${classification.isolation}`,`[Catalog] ${intentRoute.catalogMatched ? intentRoute.routeIds.join(", ") : "semantic fallback"} · ${routedTools.length}/${tools.length} tool docs scored`,+ `[Knowledge] ${projectKnowledge?.exists ? `${projectKnowledge.bytes} bytes always-on` : "not configured"}`,`[Memory] ${repoMemory.length} repo-local hit(s) · ${search.recommendedRecipe ? "recipe available" : "no verified recipe selected"} · ~${contextEstimateTokens} context tokens`,...(recipePlan ? [`[Recipe] ${recipePlan.attempts} attempts · ${recipePlan.successRate}% success · ${recipePlan.steps.length} reusable step(s)`] : []),...(reusableScript ? [`[Automation] ${reusableScript.status} script ${reusableScript.id} available`] : []),diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex fc053b6f..f227c611 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -13,6 +13,8 @@ import { SUBAGENT_TOOLS } from "./tools-subagents";import { FORGE_TOOLS } from "./tools-forge";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 { withWorkflowContext } from "./tool-context";// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,@@ -222,4 +224,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, ...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, ...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.tsindex 73f5851b..1366cc6a 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.7.3";-export const MCP_TOOLSET_VERSION = "2026.09.03.4";-export const MCP_TOOLSET_CHANGED_AT = "2026-09-03T10:23:00Z";+export const MCP_SERVER_VERSION = "1.8.0";+export const MCP_TOOLSET_VERSION = "2026.09.03.5";+export const MCP_TOOLSET_CHANGED_AT = "2026-09-03T13:14:26Z";export type McpToolsetInfo = {serverVersion: string;diff --git a/lib/mcp/ui-operator-resources.ts b/lib/mcp/ui-operator-resources.tsnew file mode 100644index 00000000..8e1ab44c--- /dev/null+++ b/lib/mcp/ui-operator-resources.ts@@ -0,0 +1,52 @@+export const PROJECT_STATUS_URI = "ui://mso/project-status-v1.html";+export const DIFF_VIEW_URI = "ui://mso/project-diff-v1.html";+export const VPS_STATUS_URI = "ui://mso/vps-status-v1.html";++const ORIGIN = "https://mso.rahmanef.com";+const MIME = "text/html;profile=mcp-app";++function shell(title: string, body: string, script: string) {+ return String.raw`<main class="mso-card"><style>+:root{color-scheme:light dark;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}*{box-sizing:border-box}body{margin:0;background:transparent;color:CanvasText}.mso-card{padding:10px}.card{overflow:hidden;border:1px solid color-mix(in srgb,CanvasText 14%,transparent);border-radius:18px;background:color-mix(in srgb,Canvas 95%,transparent)}header{display:flex;align-items:center;gap:10px;padding:13px 14px;border-bottom:1px solid color-mix(in srgb,CanvasText 9%,transparent)}.mark{display:grid;place-items:center;width:30px;height:30px;border-radius:9px;background:color-mix(in srgb,#2563eb 16%,Canvas);font-weight:800}h2{margin:0;font-size:14px}.sub{margin:2px 0 0;color:color-mix(in srgb,CanvasText 58%,transparent);font-size:10px}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;background:color-mix(in srgb,CanvasText 9%,transparent)}.cell{min-width:0;padding:10px 12px;background:Canvas}.cell span{display:block;font-size:9px;text-transform:uppercase;letter-spacing:.08em;color:color-mix(in srgb,CanvasText 52%,transparent)}.cell strong{display:block;margin-top:3px;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.section{padding:10px 14px}.row{display:flex;align-items:center;justify-content:space-between;gap:10px;min-height:27px;border-top:1px solid color-mix(in srgb,CanvasText 8%,transparent);font-size:11px}.row:first-child{border-top:0}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}.muted{color:color-mix(in srgb,CanvasText 52%,transparent)}.good{color:#16a34a}.bad{color:#dc2626}.files{margin:0;padding:0;list-style:none}.file{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;min-height:28px;align-items:center;border-top:1px solid color-mix(in srgb,CanvasText 8%,transparent);font-size:11px}.file:first-child{border-top:0}.file-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.actions{display:flex;justify-content:flex-end;gap:7px;padding:9px 12px;border-top:1px solid color-mix(in srgb,CanvasText 9%,transparent)}button{border:1px solid color-mix(in srgb,CanvasText 14%,transparent);background:color-mix(in srgb,CanvasText 5%,Canvas);color:CanvasText;border-radius:10px;padding:7px 10px;font:inherit;font-size:11px;cursor:pointer}@media(max-width:440px){.mso-card{padding:6px}.grid{grid-template-columns:1fr 1fr}.wide{grid-column:1/-1}}+</style><section class="card"><header><div class="mark">M</div><div><h2>${title}</h2><p class="sub" id="subtitle">MSO</p></div></header>${body}<div class="actions"><button id="refresh" hidden>Refresh</button><button id="open">Open MSO ↗</button></div></section><script>${script}</script></main>`;+}++const sharedScript = String.raw`+const MSO_URL="https://mso.rahmanef.com";const $=id=>document.getElementById(id);let last=null;+const txt=(v,f="—")=>v===undefined||v===null||v===""?f:String(v);const esc=v=>txt(v);+function output(){return window.openai&&window.openai.toolOutput?window.openai.toolOutput:null}+async function openMso(){if(window.openai&&typeof window.openai.openExternal==="function")await window.openai.openExternal({href:MSO_URL,redirectUrl:false});else window.open(MSO_URL,"_blank","noopener,noreferrer")}+$("open").addEventListener("click",openMso);window.addEventListener("openai:set_globals",()=>{const v=output();if(v)render(v)},{passive:true});window.addEventListener("message",e=>{if(e.source!==window.parent)return;const m=e.data;if(m&&m.method==="ui/notifications/tool-result"&&m.params&&m.params.structuredContent)render(m.params.structuredContent)},{passive:true});+`;++const projectBody = String.raw`<div class="grid"><div class="cell wide"><span>Project</span><strong id="project">—</strong></div><div class="cell"><span>Branch</span><strong id="branch">—</strong></div><div class="cell"><span>HEAD</span><strong class="mono" id="head">—</strong></div><div class="cell"><span>Working tree</span><strong id="clean">—</strong></div></div><div class="section"><div class="row"><span>Package</span><strong id="package">—</strong></div><div class="row"><span>Database</span><strong id="database">—</strong></div><div class="row"><span>Project MCP</span><strong id="mcp">0</strong></div><div class="row"><span>Knowledge</span><strong id="knowledge">—</strong></div></div>`;+const projectScript = sharedScript + String.raw`+let projectId="";function render(v){last=v||{};const p=v.project||{},g=v.git||{},pkg=v.package||{},db=v.database||{},i=v.integrations||{},k=v.knowledge||{};projectId=txt(p.id,"");$("project").textContent=txt(p.name);$("subtitle").textContent=txt(p.path,"Project status");$("branch").textContent=txt(g.branch);$("head").textContent=g.head&&g.head.sha?String(g.head.sha).slice(0,12):"—";$("clean").textContent=g.clean===true?"Clean":g.clean===false?(String(Array.isArray(g.changes)?g.changes.length:0)+" change(s)"):"Unknown";$("clean").className=g.clean===true?"good":g.clean===false?"bad":"";$("package").textContent=[pkg.name,pkg.version].filter(Boolean).join(" · ")||"—";$("database").textContent=db.detected?("Convex · "+txt(db.mode)):"Not detected";$("mcp").textContent=String(Array.isArray(i.projectMcp)?i.projectMcp.length:0);$("knowledge").textContent=k.exists?(txt(k.bytes,0)+" bytes"):"Not set";$("refresh").hidden=!projectId}+$("refresh").addEventListener("click",async()=>{if(!projectId||!window.openai||typeof window.openai.callTool!=="function")return;const r=await window.openai.callTool("project_get",{project:projectId});render(r&&r.structuredContent?r.structuredContent:r)});const initial=output();if(initial)render(initial);+`;++const diffBody = String.raw`<div class="grid"><div class="cell wide"><span>Project</span><strong id="project">—</strong></div><div class="cell"><span>Mode</span><strong id="mode">—</strong></div><div class="cell"><span>Files</span><strong id="count">0</strong></div><div class="cell"><span>Lines</span><strong id="lines">+0 −0</strong></div></div><div class="section"><ul class="files" id="files"></ul><div class="muted" id="empty">No changed files.</div></div>`;+const diffScript = sharedScript + String.raw`+function render(v){last=v||{};const p=v.project||{},s=v.summary||{},files=Array.isArray(v.files)?v.files:[];$("project").textContent=txt(p.name);$("subtitle").textContent=v.sha?("Commit "+String(v.sha).slice(0,12)):"Current changes";$("mode").textContent=txt(v.mode);$("count").textContent=txt(s.files,files.length);$("lines").textContent="+"+txt(s.additions,0)+" −"+txt(s.deletions,0);const ul=$("files");ul.textContent="";$("empty").hidden=files.length>0;for(const f of files.slice(0,80)){const li=document.createElement("li");li.className="file";const n=document.createElement("span");n.className="file-name mono";n.textContent=txt(f.file);const d=document.createElement("span");d.className="muted";d.textContent="+"+txt(f.added,"?")+" −"+txt(f.deleted,"?");li.append(n,d);ul.append(li)}}const initial=output();if(initial)render(initial);+`;++const vpsBody = String.raw`<div class="grid"><div class="cell"><span>Load</span><strong id="load">—</strong></div><div class="cell"><span>Memory</span><strong id="memory">—</strong></div><div class="cell"><span>Disk</span><strong id="disk">—</strong></div></div><div class="section"><div class="row"><span>Uptime</span><strong id="uptime">—</strong></div><div class="row"><span>Managed apps</span><strong id="apps">—</strong></div><div class="row"><span>Browser</span><strong id="browser">—</strong></div><div class="row"><span>Infrastructure</span><strong id="infra">—</strong></div></div>`;+const vpsScript = sharedScript + String.raw`+const pct=n=>Number.isFinite(Number(n))?(String(Math.round(Number(n)))+"%"):"—";function render(v){last=v||{};const h=v.health||{},a=Array.isArray(v.apps)?v.apps:[],b=v.browser||{},infra=Array.isArray(v.infrastructure)?v.infrastructure:[];$("subtitle").textContent="Live bounded VPS overview";const load=h.load||h.cpu||{};$("load").textContent=Array.isArray(load)?load.map(x=>Number(x).toFixed(2)).join(" / "):txt(load.one||load.load1||h.load1);const mem=h.memory||{};$("memory").textContent=mem.percentUsed!==undefined?pct(mem.percentUsed):mem.used&&mem.total?pct(mem.used/mem.total*100):"—";const disk=h.disk||{};$("disk").textContent=disk.percentUsed!==undefined?pct(disk.percentUsed):disk.used&&disk.total?pct(disk.used/disk.total*100):"—";$("uptime").textContent=h.uptimeSeconds!==undefined?(String(Math.round(Number(h.uptimeSeconds)/3600))+"h"):"—";$("apps").textContent=String(a.filter(x=>x.running).length)+"/"+String(a.length)+" running";$("browser").textContent=b.running?"Running":b.installed?"Stopped":"Not installed";$("infra").textContent=String(infra.filter(x=>x.configured).length)+"/"+String(infra.length)+" configured";$("refresh").hidden=false}+$("refresh").addEventListener("click",async()=>{if(!window.openai||typeof window.openai.callTool!=="function")return;const r=await window.openai.callTool("vps_status",{});render(r&&r.structuredContent?r.structuredContent:r)});const initial=output();if(initial)render(initial);+`;++function meta(description: string) {+ return {+ ui: { prefersBorder: true, csp: { connectDomains: [], resourceDomains: [] } },+ "openai/widgetDescription": description,+ "openai/widgetPrefersBorder": true,+ "openai/widgetCSP": { connect_domains: [], resource_domains: [], redirect_domains: [ORIGIN] },+ };+}++export const OPERATOR_UI_RESOURCES = [+ { uri: PROJECT_STATUS_URI, name: "MSO project status", description: "Interactive project snapshot.", mimeType: MIME, text: shell("MSO project", projectBody, projectScript), _meta: meta("MSO project status card with bounded Git, Convex, knowledge and integration state.") },+ { uri: DIFF_VIEW_URI, name: "MSO project diff", description: "Compact project diff summary.", mimeType: MIME, text: shell("MSO diff", diffBody, diffScript), _meta: meta("MSO project diff summary. Raw diff text remains in the tool fallback and is not injected as HTML.") },+ { uri: VPS_STATUS_URI, name: "MSO VPS status", description: "Interactive bounded VPS overview.", mimeType: MIME, text: shell("MSO VPS", vpsBody, vpsScript), _meta: meta("MSO live bounded VPS overview for health, managed apps, browser and infrastructure readiness.") },+] as const;diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.tsindex 7016fc52..1ebd8b5d 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 } = await import("./ui-resources");+const { MCP_APP_MIME_TYPE, WORKFLOW_PROGRESS_URI, PROJECT_STATUS_URI, DIFF_VIEW_URI, VPS_STATUS_URI } = await import("./ui-resources");const { activeWorkflowForActor } = await import("@/lib/skills/memory");const call = (name: string, args: Record<string, unknown> = {}) =>@@ -33,13 +33,24 @@ describe("MCP Apps workflow progress UI", () => {ui: { visibility: ["app"] },"openai/widgetAccessible": true,});++ for (const [name, uri] of [["project_get", PROJECT_STATUS_URI], ["project_diff", DIFF_VIEW_URI], ["vps_status", VPS_STATUS_URI]] as const) {+ const tool = tools.find((row) => row.name === name);+ expect(tool?.outputSchema, name).toBeDefined();+ expect(tool?._meta, name).toMatchObject({ ui: { resourceUri: uri, visibility: ["model", "app"] }, "openai/outputTemplate": uri });+ }});it("serves one self-contained mcp-app resource", async () => {const listed = await dispatch({ id: 1, method: "resources/list" }, "read", "mcp:ui-resource");- expect(listed.result).toMatchObject({- resources: [expect.objectContaining({ uri: WORKFLOW_PROGRESS_URI, mimeType: MCP_APP_MIME_TYPE })],- });+ const resources = (listed.result as { resources: Array<{ uri: string; mimeType: string }> }).resources;+ expect(resources).toHaveLength(4);+ 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 }),+ ]));const read = await dispatch({ id: 2, method: "resources/read", params: { uri: WORKFLOW_PROGRESS_URI } }, "read", "mcp:ui-resource");const content = (read.result as {@@ -106,6 +117,17 @@ describe("MCP Apps workflow progress UI", () => {expect((closed.result as { structuredContent?: { active: boolean } }).structuredContent?.active).toBe(false);});++ it("serves project, diff and VPS MCP Apps without external fetches", async () => {+ for (const [uri, marker] of [[PROJECT_STATUS_URI, "project_get"], [DIFF_VIEW_URI, "MSO diff"], [VPS_STATUS_URI, "vps_status"]] as const) {+ const read = await dispatch({ id: 20, method: "resources/read", params: { uri } }, "read", "mcp:ui-operator");+ const content = (read.result as { contents: Array<{ mimeType: string; text: string; _meta: Record<string, unknown> }> }).contents[0];+ expect(content.mimeType).toBe(MCP_APP_MIME_TYPE);+ expect(content.text).toContain(marker);+ expect(content.text).not.toContain("fetch(");+ expect(content._meta).toMatchObject({ ui: { prefersBorder: true }, "openai/widgetPrefersBorder": true });+ }+ });it("rejects unknown UI resource URIs", async () => {const result = await dispatch({ id: 1, method: "resources/read", params: { uri: "ui://mso/not-real.html" } }, "read");expect(result.error).toMatchObject({ code: -32602 });diff --git a/lib/mcp/ui-resources.ts b/lib/mcp/ui-resources.tsindex 76735f64..d3a4d533 100644--- a/lib/mcp/ui-resources.ts+++ b/lib/mcp/ui-resources.ts@@ -1,3 +1,5 @@+import { OPERATOR_UI_RESOURCES } from "./ui-operator-resources";+export { PROJECT_STATUS_URI, DIFF_VIEW_URI, VPS_STATUS_URI } from "./ui-operator-resources";export const WORKFLOW_PROGRESS_URI = "ui://mso/workflow-progress-v1.html";export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";const MSO_ORIGIN = "https://mso.rahmanef.com";@@ -238,6 +240,7 @@ const RESOURCES: readonly McpUiResource[] = [text: workflowProgressHtml,_meta: workflowResourceMeta(),},+ ...OPERATOR_UI_RESOURCES,];export function listUiResources() {