Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(mcp): streamline bootstrap and workflow visibility

Rahmand1acb585aea9
diff --git a/CLAUDE.md b/CLAUDE.md
index 7bf7243c..7bd7a780 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -306,8 +306,8 @@ that is the kill switch, and demo mode forces it off. Read `docs/MCP.md` first.
decision, see the integration doc below). `tools/list` filters by it AND `tools/call`
re-checks it — a client can call a name it was never shown.
- **Tool names are a cross-repo contract.** `rahmanef63/connectors-gateway` registered
- mso as a connector on 2026-08-17 and pins 15 of the 17 names as literal strings
- (`x-upstream`), omitting `exec_run` and `browser_power` entirely. Renaming or removing
+ mso as a connector on 2026-08-17 and pins 15 of the 21 names as literal strings
+ (`x-upstream`), omitting `exec_run`, `browser_power`, and the four workflow/visual tools added later. `GET /mcp` plus `_meta.toolset` now expose a version/hash/name manifest for parity checks. Renaming or removing
a tool here breaks it with **no error in either repo** — `parity.test.ts` guards the
Alfa axis, not this one. Read `docs/CONNECTORS-GATEWAY-INTEGRATION.md` before touching
a tool name.
diff --git a/app/api/mcp/tokens/route.ts b/app/api/mcp/tokens/route.ts
index 7d305947..e2e038eb 100644
--- a/app/api/mcp/tokens/route.ts
+++ b/app/api/mcp/tokens/route.ts
@@ -2,6 +2,8 @@ import { NextResponse } from "next/server";
import { verifyAuth } from "@/lib/agent/server";
import { listTokens, revokeToken, revokeAllTokens } from "@/lib/mcp/store";
import { mcpEnabled, maxScope } from "@/lib/mcp/scope";
+import { TOOLS } from "@/lib/mcp/tools";
+import { toolsetInfo } from "@/lib/mcp/toolset";
// Token management for Settings → MCP. Under /api on purpose: this one IS
// cookie-authenticated and DOES want the depth-2 CSRF gate in proxy.ts, unlike
@@ -12,7 +14,7 @@ export const dynamic = "force-dynamic";
export async function GET(req: Request) {
if (!(await verifyAuth(req))) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
- return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), tokens: await listTokens() });
+ return NextResponse.json({ enabled: mcpEnabled(), maxScope: maxScope(), toolset: toolsetInfo(TOOLS), tokens: await listTokens() });
}
export async function DELETE(req: Request) {
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index fa8fa1b8..4ba4772b 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -3,6 +3,8 @@ import { validateToken, touchToken } from "@/lib/mcp/store";
import { mcpEnabled } from "@/lib/mcp/scope";
import { publicOrigin, clientIp } from "@/lib/mcp/origin";
import { rateLimited } from "@/lib/host";
+import { TOOLS } from "@/lib/mcp/tools";
+import { toolsetInfo } from "@/lib/mcp/toolset";
// The MCP endpoint. Deliberately at /mcp and NOT under /api: proxy.ts blocks
// mutating /api that cannot prove same-origin, and an MCP client is by definition
@@ -70,5 +72,6 @@ export async function GET(req: Request) {
transport: "streamable-http (JSON-RPC over POST)",
auth: "Bearer <mcp token> — obtain via OAuth 2.1 + PKCE",
authorization_servers: [publicOrigin(req)],
+ toolset: toolsetInfo(TOOLS),
});
}
diff --git a/claude-skills/mso-deploy/SKILL.md b/claude-skills/mso-deploy/SKILL.md
new file mode 100644
index 00000000..ed2e4fc1
--- /dev/null
+++ b/claude-skills/mso-deploy/SKILL.md
@@ -0,0 +1,24 @@
+---
+name: mso-deploy
+description: Ship MSO safely using its verified release path: preflight, out-of-tree verification, commit and push gates, build then restart, health and chunk checks, and visual proof.
+metadata:
+ mso:
+ risk: high
+ policy: verify-ship-prove
+---
+
+# /mso-deploy — production release recipe
+
+Call `workflow_start` with the complete change and deployment intent. Confirm the resolved project is the production MSO checkout and inspect `CLAUDE.md` plus the top of `docs/PROGRESS.md` before shipping.
+
+## Required order
+
+1. Targeted tests and `bun run verify`.
+2. `bash scripts/verify-build.sh` for an out-of-tree compile check.
+3. Review clean diff and append the shipped reasoning to `docs/PROGRESS.md`.
+4. Run `bun run ship "<conventional commit>"`.
+5. Verify `mso.service` is active, `/api/health` reports the new build, and a CSS/JS chunk referenced by live HTML serves the correct MIME type.
+6. Run the live smoke test and `screen_capture` for visual proof.
+7. Call `workflow_finish(success=true)` only after all checks pass.
+
+`git push` alone is not deployment. The production checkout's `.next` is live: build then restart immediately, never restart before build, and never leave an in-place build without the matching restart. Long release commands should run as a background host job with their log and exit code polled, not by inserting fixed `sleep` delays into every check.
diff --git a/claude-skills/mso-repo-work/SKILL.md b/claude-skills/mso-repo-work/SKILL.md
new file mode 100644
index 00000000..54a5bd87
--- /dev/null
+++ b/claude-skills/mso-repo-work/SKILL.md
@@ -0,0 +1,33 @@
+---
+name: mso-repo-work
+description: Change an MSO-managed code repository efficiently: resolve aliases, inspect Git once, search broadly in one scoped batch, patch safely, and verify only what the change can break.
+metadata:
+ mso:
+ risk: medium
+ policy: inspect-batch-patch-verify
+---
+
+# /mso-repo-work — fast, bounded repository changes
+
+For multi-step work, call `workflow_start` directly. It already searches skills and prior recipes, resolves aliases such as `os-vps` → `mso`, reports the current toolset, and returns repository context.
+
+## Route selection
+
+- One or two direct file operations: bounded `fs_*` tools.
+- Repository-wide search, Git inspection, tests, builds, or three or more related checks: one narrow `exec_run` batch.
+- Destructive cleanup, history rewrites, force push, credential changes, or deleting user data: require explicit approval.
+
+A useful first batch is:
+
+```bash
+set -euo pipefail
+git status -sb
+git log -1 --oneline --decorate
+rg -n "<target>" app lib frontend scripts docs
+```
+
+Do not perform one tool call per folder. Read the exact files returned by search. When replacing an existing text file through MCP, use `fs_read` first and pass its SHA-256 as `fs_write.expected_sha256`; a changed file must be inspected again rather than overwritten.
+
+## Finish
+
+Run the smallest relevant test first, then typecheck/lint or the project verification command. For MSO itself, a check build must use `scripts/verify-build.sh`; never run `next build` in the live checkout merely to test compilation. Review `git diff --check`, `git diff --stat`, and the final diff before `workflow_finish`.
diff --git a/claude-skills/mso-service-debug/SKILL.md b/claude-skills/mso-service-debug/SKILL.md
new file mode 100644
index 00000000..e5b22691
--- /dev/null
+++ b/claude-skills/mso-service-debug/SKILL.md
@@ -0,0 +1,23 @@
+---
+name: mso-service-debug
+description: Diagnose an MSO or managed-app failure with the smallest safe path: telemetry, bounded status and logs, one scoped system batch only when needed, then restart and verify.
+metadata:
+ mso:
+ risk: medium
+ policy: observe-before-restart
+---
+
+# /mso-service-debug — diagnose before touching service state
+
+Call `workflow_start` directly for a multi-step incident. Begin with `sys_stats`, `apps_list`, and `apps_logs`; these answer most CPU, memory, stopped-service, and journal questions without shell power.
+
+Use one scoped `exec_run` batch only when bounded tools cannot identify the cause:
+
+```bash
+set -euo pipefail
+systemctl --no-pager --full status <unit> || true
+journalctl -u <unit> -n 120 --no-pager || true
+ss -ltnp | head -n 80
+```
+
+Do not restart first and erase the failure state. Record the first concrete error, inspect its configuration/source, then make the smallest repair. Prefer `apps_power` for known managed applications. After restart, verify active state, endpoint health, relevant logs, and—when UI changed—capture the MSO screen. Save the verified route with `workflow_finish`.
diff --git a/claude-skills/mso/SKILL.md b/claude-skills/mso/SKILL.md
index d9dde390..137cc1a1 100644
--- a/claude-skills/mso/SKILL.md
+++ b/claude-skills/mso/SKILL.md
@@ -1,6 +1,6 @@
---
name: mso
-description: Control MSO and its VPS safely. Prefer bounded file/system/app capabilities, use the MSO CLI for parity/debugging, and use full shell only when no bounded operation covers the task.
+description: Control MSO and its VPS safely. Prefer bounded operations for direct work, use one scoped terminal batch for repository-wide tasks, and verify every mutation.
metadata:
mso:
risk: high
@@ -20,7 +20,7 @@ Choose the least-powerful capability that can finish the task:
3. **MSO CLI/API** — when reproducing exactly what the UI/API does.
4. **Full shell (`exec`)** — only when the bounded surface cannot express the task.
-Never choose Bash merely because it is shorter. The permission boundary is a feature. Before destructive actions, service topology changes, credential changes, production rollback, or deleting data you did not create in the current task, require explicit human approval.
+Never choose Bash merely because it is shorter for a simple operation. For repository-wide work, one scoped terminal batch is safer and faster than many disconnected discovery calls. The permission boundary remains a feature. Before destructive actions, service topology changes, credential changes, production rollback, or deleting data you did not create in the current task, require explicit human approval.
## Resolve the install — never hardcode a username/path
@@ -37,14 +37,16 @@ MSO_CLI="$MSO_ROOT/bin/mso"
Use the absolute CLI path above in automation. `$HOME/.local/bin/mso` is a convenience symlink and may not be on PATH in non-login shells, CI, MCP executors, or systemd.
-## Learning loop — search first, keep the fastest verified path
+## Learning loop — bootstrap once, keep the fastest verified path
-For any task likely to need two or more tool calls:
+For any task likely to need two or more operational calls:
-1. Call `skills_search` with the user's complete intent. It searches trusted skills, the live MCP tool catalog, and learned recipes using the local semantic index.
-2. Call `workflow_start` before the first operational tool. Reuse a relevant successful recipe when it is still safe and applicable.
-3. Execute with bounded tools first and verify the result.
-4. Call `workflow_finish` with `success=true` only after verification. MSO stores the redacted tool sequence and durations, merges equivalent intents, and keeps the fastest successful path.
+1. Call `workflow_start` directly with the user's complete intent, project hint and constraints. It already searches trusted skills, the live MCP tool catalog and learned recipes, resolves project aliases, and reports the current toolset.
+2. Reuse a relevant successful recipe when it is still safe and applicable.
+3. Use bounded tools for one or two direct operations. For repository-wide search, Git, tests, builds, or three or more related checks, use one narrow `exec_run` batch when exec scope is available.
+4. Verify independently, then call `workflow_finish(success=true)`.
+
+Use `skills_search` by itself for capability research or an unfamiliar single-step task; do not call it immediately before `workflow_start` for the same work. MSO stores the redacted tool sequence and durations, merges equivalent intents, and keeps the fastest successful path.
The memory never stores `fs_write.content`, raw file bodies, bearer tokens, browser credentials, or full secret-looking command arguments. Failed runs are useful evidence but never replace a successful best path.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 080b9dbd..152687a8 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` streamline bootstrap and workflow visibility
- add semantic skill memory and workflow recipes
- add secure temporary screenshot links
- add MCP screenshots and live activity
diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
index d2de3e37..8a580791 100644
--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md
+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
@@ -1,90 +1,71 @@
# mso → Connectors Gateway
-**Status: mso is a registered connector there as of 2026-08-17** (`connectors-gateway@03e0948`).
-Nothing in THIS repo changed to make that happen — no config, no code, no token. This
-file exists so the next person here knows the dependency is there, because otherwise
-it is invisible from inside mso.
+**Status:** mso is a registered connector in `rahmanef63/connectors-gateway` as of 2026-08-17. MSO is the provider; the gateway is one consumer alongside ChatGPT, Claude.ai and Cursor. Every client reaches `https://mso.rahmanef.com/mcp` through the same OAuth and scope rules documented in [`MCP.md`](./MCP.md).
-Direction matters: mso is the **provider**. `rahmanef63/connectors-gateway` is a consumer
-of mso's MCP surface, alongside CareerPack and Composio. It reaches mso the same way
-ChatGPT or Claude.ai would — over `https://mso.rahmanef.com/mcp`, through the OAuth in
-[`MCP.md`](./MCP.md). mso grants it nothing special.
+## Cross-repo contract
-## The thing that will break, and how
+MSO currently exposes **21 tool names**. The gateway manifest still maps **15** of them through literal `x-upstream` strings:
-The gateway keeps its own manifest of mso's tools, and it pins **upstream tool names as
-strings**:
-
-```
-connectors-gateway/adapters/remote-mcp/connectors/mso.connector.json
- { "id": "mso.fs.delete", …, "x-upstream": "fs_delete" }
+```json
+{ "id": "mso.fs.delete", "x-upstream": "fs_delete" }
```
-There is no shared type, no generated client, and no build step that reads this repo.
+Renaming or removing a tool here breaks that action at runtime even when both repositories typecheck. Adding a tool here does not make it appear in the gateway until its manifest is deliberately updated.
+
+The runtime contract is no longer invisible:
-**So renaming or removing a tool in `lib/mcp/tools.ts` or `tools-read.ts` breaks the
-gateway silently.** Both repos still typecheck, both test suites still pass, and the
-failure only shows up as one action erroring at call time for whoever is using it. The
-same is true in reverse: a tool ADDED here does not appear in the gateway until someone
-edits that JSON.
+- unauthenticated `GET /mcp` returns the current toolset version, hash, count and names;
+- MCP `initialize` and `tools/list` return `_meta.toolset` for the token's visible scope;
+- Settings → MCP shows the same signature and lets the operator mark the ChatGPT action snapshot as refreshed;
+- the signature hashes names, descriptions, schemas, scope, annotations and limits, so a schema-only change is visible too.
-`lib/mcp/parity.test.ts` already guards the Alfa ↔ MCP axis. It does not know about this
-one. If you rename a tool, grep the gateway repo for its name.
+A consumer CI should compare the upstream names it pins against this runtime manifest. Source parsing remains useful for review, but it is no longer the only way to detect drift.
-## What is exposed there, and what is deliberately not
+## What the gateway exposes
-15 of the 17 tools. The whole `read` and `write` tiers, and **neither `exec` tool**:
+The gateway has not yet synchronized the six tools added or deliberately withheld from its 15-action manifest:
-| Omitted | Why |
+| Not mapped in gateway | Reason/status |
|---|---|
-| `exec_run` | arbitrary shell on the VPS the gateway itself runs on |
-| `browser_power` | drives the Camoufox profile holding live Google / LinkedIn sessions |
+| `exec_run` | deliberately omitted: arbitrary owner-level shell |
+| `browser_power` | deliberately omitted: controls a browser profile holding live sessions |
+| `skills_search` | added to MSO after the original gateway manifest |
+| `screen_capture` | added later; secure MSO-only visual artifact, requires a product decision in the gateway |
+| `workflow_start` | added later; should be mapped together with `workflow_finish` |
+| `workflow_finish` | added later; actor-scoped recipe boundary |
-They are **omitted from the manifest, not disabled in policy**. That was decided in the
-gateway's `docs/16-connector-strategy.md` before the connector was written: a disabled
-action is one policy edit away from live, while a name absent from the catalog cannot be
-resolved into an action id at all.
+`fs_delete` and `apps_power` remain the gateway's highest-risk mapped actions and should keep its human approval policy. The gateway's policy layer supplements, never replaces, MSO's scope checks, path jail, audit trail and per-operation rate limits.
-`connectors-gateway/adapters/remote-mcp/src/mso.test.ts` pins it, and checks `x-upstream`
-rather than the local id — so renaming an action over there cannot smuggle the same shell
-back in.
+## Change procedure
-Two tools are rated `R3` + destructive there, which routes them through that platform's
-human approval queue before they ever reach mso: **`fs_delete`** and **`apps_power`**. The
-second one because stopping or restarting a daemon cuts off whatever is using it.
+Before changing the MCP catalog:
-## Open decision — yours, not the gateway's
+1. Read `lib/mcp/tools.ts`, `tools-read.ts`, `tools-learning.ts` and `toolset.ts`.
+2. Do not rename a public tool unless migration is intentional.
+3. Run MSO parity, dispatch and toolset tests.
+4. Compare the new `GET /mcp` signature and names with the gateway manifest.
+5. Update the gateway mapping or explicitly document why a capability stays absent.
+6. Refresh affected custom-app action snapshots after deployment.
-`.env.local` on the running box has:
+The Alfa ↔ MCP axis is guarded by `lib/mcp/parity.test.ts`; this document and the runtime toolset signature cover the cross-repo axis until the gateway adds an automated parity check.
-```
-OS_MCP_MAX_SCOPE=exec
-```
-
-`MCP.md`'s own example in this repo says `write`, and the gateway's `docs/16` says to
-narrow it to `write` before connecting mso. It has **not** been changed — that is a
-production config change to this application, so it is the owner's call rather than a
-side effect of work done in another repo.
+## Scope ceiling
-Narrowing it costs nothing for this integration: the gateway omits both `exec` tools, so
-it never asks for that scope. What the ceiling protects against is a *different* token —
-minted later, from the consent screen, by anyone who can sign in — being able to reach
-`exec_run` at all.
+The running MSO instance currently allows tokens up to:
-## What was done in this repo: nothing
+```text
+OS_MCP_MAX_SCOPE=exec
+```
-The gateway's manifest was written by reading `lib/mcp/tools.ts`, `lib/mcp/tools-read.ts`
-and `lib/mcp/tool-kit.ts` directly, rather than by calling `tools/list` against the live
-server. That was deliberate: it meant **no MCP bearer had to be minted on this deployment**
-to build the integration. `mso mcp list` was empty before and is empty after.
+The gateway's mapped actions do not require `exec`, so narrowing the gateway token to `write` costs it nothing. The server-wide ceiling remains an owner decision because it also governs separately minted ChatGPT, Claude or Cursor tokens.
-## Checking it from here
+## Operator checks
```bash
-mso mcp list # tokens the gateway (or anything else) holds. Empty = not connected yet.
-mso audit 50 # every mutating MCP call, actor `mcp:<id>`
+curl -s https://mso.rahmanef.com/mcp | jq '.toolset'
+mso mcp list
+mso mcp activity 100
+mso audit 50 mcp.
```
-The gateway side lives at `connectors-gateway/docs/16-connector-strategy.md` (why mso is
-connected read/write only) and `docs/18-oauth.md` (how a client authorizes to that gateway
-— unrelated to how the gateway authorizes to mso).
+The gateway strategy and its user-facing OAuth are maintained in the gateway repository. This file owns only the provider-side contract and drift procedure.
diff --git a/docs/MCP.md b/docs/MCP.md
index e2b2c6e8..06145ced 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -87,19 +87,34 @@ restarting a daemon does not require handing one over either.
`tools/list` is filtered by the token's scope, and `tools/call` re-checks it — a
client that calls a tool it was never shown still gets refused.
+## Toolset version, hash and action refresh
+
+The catalog has a stable server version plus a schema-derived toolset signature. It is returned by public `GET /mcp`, MCP `initialize`, scoped `tools/list`, and the authenticated Settings → MCP endpoint. The signature changes when a name, description, input schema, scope, annotation or per-operation limit changes—not only when the tool count changes.
+
+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.
+
+Current catalog: **21 tools**. Public names remain stable in this release.
+
+## Safe text inspection and overwrite
+
+`fs_read` returns `content`, UTF-8 byte count and SHA-256. For an existing file, pass that digest as `fs_write.expected_sha256`; the write is refused if another process changed the file since inspection. Omitting it preserves create/legacy overwrite behaviour. Workflow memory stores the path, never the content or digest.
+
## Semantic skill search and learned workflows
-MSO does not need to rediscover the same safe procedure on every conversation. Its
-learning loop has three layers:
+MSO does not need to rediscover the same safe procedure on every conversation.
+For a multi-step task, `workflow_start` is the **single bootstrap call**. It:
+
+1. creates the actor-scoped task boundary;
+2. searches trusted `SKILL.md` instructions, the current scoped MCP catalog and learned recipes;
+3. resolves project paths and aliases such as `os-vps` → `mso`;
+4. returns toolset version/hash/count, package metadata and bounded Git context;
+5. recommends the closest successful recipe and execution policy.
-1. `skills_search` searches trusted `SKILL.md` instructions, the live MCP tool
- catalog and previously learned workflows.
-2. `workflow_start` creates an actor-scoped task boundary before multi-step work and
- returns the closest prior recipe, including its best tool sequence, success rate
- and fastest verified duration.
-3. `workflow_finish` records the verified outcome and merges semantically equivalent
- intents. A faster successful run replaces the best path; a failed run remains
- evidence but never replaces a successful recipe.
+Use `skills_search` alone for capability research or an unfamiliar single-step task;
+do not call it immediately before `workflow_start` for the same work. After independent
+verification, `workflow_finish` records the redacted sequence and merges semantically
+equivalent intents. A faster successful run replaces the best path; a failed run remains
+evidence but never replaces a successful recipe.
The index uses `mso-local-hybrid-v1`: a deterministic, local 384-dimensional
feature-hashed vector over words, bilingual aliases, bigrams and character n-grams,
@@ -108,10 +123,10 @@ or token budget. This is a small local semantic router for MSO's skill/tool cata
not a general-purpose cloud embedding model. A future encoder can re-index recipes
because every saved vector carries its version.
-Connected clients receive this sequence in the MCP `initialize.instructions` field:
+Connected clients receive the bootstrap, terminal-batching, verification and visible-trace policy in MCP `initialize.instructions`:
```text
-skills_search → workflow_start → bounded operational tools → verify → workflow_finish
+workflow_start → bounded tools or one scoped terminal batch → verify → workflow_finish
```
A recipe is guidance, not permission. The connector still checks current tool
@@ -177,10 +192,12 @@ MSO keeps two deliberately different records.
Every MCP tool call, including reads, produces correlated `started` and terminal
(`completed`, `failed`, `denied`, `rate_limited`) rows in
-`~/.mso/mcp-activity.log`. When a workflow is active, the rows carry its
-`workflowId`, so the Assistant can show one task as a continuous sequence rather
-than unrelated calls. Targets are truncated and secret-looking values are redacted;
-`fs_write.content`, file bodies, bearer values and raw tool results are never stored.
+`~/.mso/mcp-activity.log`. Workflow rows carry `workflowId`, intent and project, so
+Assistant → MCP groups one task into a collapsible sequence instead of unrelated calls.
+Each row renders a high-level feature badge/icon such as Skills, Files, Terminal, Git,
+Build, Verify or Screenshot, plus status, duration and redacted target. This is an
+execution trace, not private chain-of-thought. `fs_write.content`, file bodies, bearer
+values and raw tool results are never stored.
View it in **Assistant → MCP** (live polling with pause/resume) or from the CLI:
@@ -261,10 +278,13 @@ lib/mcp/scope.ts the read/write/exec ladder + the env kill switch
lib/mcp/store.ts ~/.mso/mcp.json — clients, codes, tokens (hashed)
lib/mcp/tool-kit.ts McpTool, direct image content and run context
lib/mcp/tools-read.ts bounded reads + skills_search + screen_capture
-lib/mcp/tools-learning.ts actor-scoped workflow_start / workflow_finish
+lib/mcp/tools-learning.ts one-call bootstrap + workflow_start / workflow_finish
+lib/mcp/toolset.ts server/toolset version, schema hash and scoped manifest
lib/mcp/tools.ts write/exec tools and the assembled catalog
-lib/mcp/activity.ts live correlated tool activity
-lib/mcp/dispatch.ts JSON-RPC, scope checks, activity + recipe capture
+lib/mcp/activity.ts workflow-correlated live activity
+lib/mcp/dispatch.ts JSON-RPC, scope checks, metadata, activity + recipe capture
+lib/host/projects.ts bounded project resolution, aliases and repo context
+lib/host/guarded-write.ts optimistic SHA-256 file overwrite guard
lib/skills/catalog.ts trusted SKILL.md roots and provenance
lib/skills/semantic.ts local hybrid embedding/search primitives
lib/skills/search.ts unified skill/tool/recipe ranking
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index bce42e81..bbfc00d9 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -8,6 +8,62 @@ Running log of what shipped each phase. Newest at top.
> Read those phases as history. **This file is the source of truth for what exists** —
> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.
+## 2026-08-19 — MCP one-call bootstrap, visible workflows and faster repository work (DONE)
+
+A refreshed ChatGPT connection proved the server really exposed all 21 MCP tools, but
+it also made the remaining orchestration cost visible. The client still had to search
+skills and start a workflow as separate calls; `os-vps` no longer matched the renamed
+`mso` directory; MCP activity was a flat list even though the backend already stored a
+`workflowId`; tool descriptions and schemas could change without an operator-visible
+signature; and the systemd environment handed `exec_run` no `~/.bun/bin`, so every Bun
+command first failed or required an absolute path. The live baseline also returned no
+toolset metadata from `GET /mcp`, and `fs_search("os-vps")` returned an empty result.
+
+This release keeps the public catalog at **21 stable names** and makes the existing
+`workflow_start` the one bootstrap call for multi-step work. It now starts the
+actor-scoped workflow, searches trusted skills/tools/recipes, resolves the project,
+returns package and Git context, reports the scoped toolset version/hash/count, and
+emits the high-level `[MSO]`, `[Project]`, and `[Plan]` trace. `skills_search` remains the
+standalone capability-research route; clients are explicitly told not to call it
+immediately before `workflow_start` for the same task. Initialize instructions now
+prefer bounded tools for one or two direct operations and one narrow terminal batch for
+repository-wide search, Git, tests, builds, or three-plus related checks. They request
+feature badges such as Skills, Files, Terminal, Git, Build, Verify and Screenshot—not
+private chain-of-thought.
+
+Project resolution now has safe aliases for `os-vps`, Manef Shell OS and MSO, with an
+immediate exact-name/alias return instead of parsing every project package. Package and
+Git metadata refuse symlinks. `fs_read` returns UTF-8 bytes plus SHA-256, and
+`fs_write.expected_sha256` provides an optimistic stale-overwrite guard. Spawned shells
+retain secret scrubbing but prepend the owner's `~/.local/bin` and `~/.bun/bin`, so Bun
+and owner-installed CLIs work without rediscovery after restart.
+
+The MCP protocol, public `/mcp` descriptor and Settings API now expose server version
+`1.2.0` plus a schema-derived toolset signature (`2026.08.19.1`). Settings → MCP displays
+that signature and records a browser-local acknowledgement after ChatGPT is refreshed;
+a later change becomes a visible stale-snapshot warning. Assistant → MCP now groups
+activity by workflow intent/project, collapses start/completion pairs, aggregates steps
+and duration, and renders feature-specific icons. Only a completed `workflow_finish`
+marks a workflow Verified; standalone calls are merely Completed. Workflow intent and
+project are redacted/truncated before persistence.
+
+Three official operational skills were added: `mso-repo-work`, `mso-deploy`, and
+`mso-service-debug`. The MCP and connectors-gateway documentation now treats the 21-tool
+runtime signature as the cross-client contract and records that the gateway still maps
+15 actions. New public `repo_*` or `job_*` names were deliberately not added in this
+release: keeping the action catalog stable lets the refreshed connection benefit
+immediately, while scoped terminal batching and the existing release/job infrastructure
+cover the current bottleneck without another catalog expansion.
+
+Verification before ship: targeted bootstrap, alias, symlink, guarded-write, toolset,
+activity and dispatch tests passed; `bun run verify` passed typecheck and lint, **144 test
+files / 1,351 tests**, the coverage thresholds (22.51% statements, 20.80% branches,
+16.67% functions, 23.02% lines), 765-file cycle scan with zero value cycles, both light
+and dark contrast audits with zero AA failures, and a clean high/critical dependency
+audit. The committed pre-push gate performs the out-of-tree production build again
+before any push, and `bun run ship` preserves the required commit → changelog → push →
+build → restart order.
+
## 2026-08-19 — v0.2.1: self-update stopped assuming passwordless sudo (DONE)
A real 0.2.0 installation exposed the gap: Settings found the incoming commits, but
diff --git a/frontend/slices/assistant/components/mcp-activity-model.test.ts b/frontend/slices/assistant/components/mcp-activity-model.test.ts
new file mode 100644
index 00000000..b22d785d
--- /dev/null
+++ b/frontend/slices/assistant/components/mcp-activity-model.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { groupActivity, type McpActivityRow } from "./mcp-activity-model";
+
+const row = (value: Partial<McpActivityRow> & Pick<McpActivityRow, "id" | "tool" | "state">): McpActivityRow => ({
+ ts: "2026-08-19T14:00:00.000Z", ...value,
+});
+
+describe("MCP activity workflow grouping", () => {
+ it("collapses start/completion pairs and groups a task chronologically", () => {
+ const groups = groupActivity([
+ row({ id: "b", tool: "exec_run", state: "completed", workflowId: "w", durationMs: 20, ts: "2026-08-19T14:00:02.000Z" }),
+ row({ id: "b", tool: "exec_run", state: "started", workflowId: "w", ts: "2026-08-19T14:00:01.000Z" }),
+ row({ id: "a", tool: "workflow_start", state: "completed", workflowId: "w", workflowIntent: "deploy", workflowProject: "~/projects/mso" }),
+ ]);
+ expect(groups).toHaveLength(1);
+ expect(groups[0]).toMatchObject({ workflowId: "w", intent: "deploy", project: "~/projects/mso", state: "active", durationMs: 20 });
+ expect(groups[0].rows.map((entry) => entry.id)).toEqual(["a", "b"]);
+ });
+
+ it("marks a workflow verified only after workflow_finish", () => {
+ const [group] = groupActivity([
+ row({ id: "z", tool: "workflow_finish", state: "completed", workflowId: "w" }),
+ row({ id: "a", tool: "sys_stats", state: "completed", workflowId: "w" }),
+ ]);
+ expect(group.state).toBe("done");
+ });
+ it("marks a completed standalone call without calling it verified", () => {
+ const [group] = groupActivity([row({ id: "one", tool: "sys_stats", state: "completed" })]);
+ expect(group.state).toBe("completed");
+ });
+
+});
diff --git a/frontend/slices/assistant/components/mcp-activity-model.ts b/frontend/slices/assistant/components/mcp-activity-model.ts
new file mode 100644
index 00000000..fdfef4ea
--- /dev/null
+++ b/frontend/slices/assistant/components/mcp-activity-model.ts
@@ -0,0 +1,70 @@
+export type McpActivityState = "started" | "completed" | "failed" | "denied" | "rate_limited";
+
+export type McpActivityRow = {
+ id: string;
+ ts: string;
+ actor?: string | null;
+ tool: string;
+ state: McpActivityState;
+ scope?: string;
+ workflowId?: string;
+ workflowIntent?: string;
+ workflowProject?: string;
+ target?: string;
+ durationMs?: number;
+ detail?: string;
+};
+
+export type McpActivityGroup = {
+ key: string;
+ workflowId?: string;
+ intent?: string;
+ project?: string;
+ rows: McpActivityRow[];
+ state: "running" | "attention" | "done" | "completed" | "active";
+ durationMs: number;
+ updatedAt: string;
+};
+
+export function collapseActivity(entries: McpActivityRow[], limit = 120): McpActivityRow[] {
+ const seen = new Set<string>();
+ return entries.filter((entry) => {
+ if (seen.has(entry.id)) return false;
+ seen.add(entry.id);
+ return true;
+ }).slice(0, limit);
+}
+
+export function groupActivity(entries: McpActivityRow[]): McpActivityGroup[] {
+ const groups = new Map<string, McpActivityGroup>();
+ for (const row of collapseActivity(entries)) {
+ const key = row.workflowId ? `workflow:${row.workflowId}` : `single:${row.id}`;
+ const current = groups.get(key) ?? {
+ key,
+ workflowId: row.workflowId,
+ intent: row.workflowIntent,
+ project: row.workflowProject,
+ rows: [],
+ state: "active" as const,
+ durationMs: 0,
+ updatedAt: row.ts,
+ };
+ current.intent ??= row.workflowIntent;
+ current.project ??= row.workflowProject;
+ current.rows.push(row);
+ current.durationMs += row.durationMs ?? 0;
+ if (new Date(row.ts).getTime() > new Date(current.updatedAt).getTime()) current.updatedAt = row.ts;
+ groups.set(key, current);
+ }
+
+ for (const group of groups.values()) {
+ group.rows.sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime());
+ if (group.rows.some((row) => row.state === "started")) group.state = "running";
+ else if (group.rows.some((row) => ["failed", "denied", "rate_limited"].includes(row.state))) group.state = "attention";
+ else if (group.rows.some((row) => row.tool === "workflow_finish" && row.state === "completed")) group.state = "done";
+ else if (!group.workflowId && group.rows.every((row) => row.state === "completed")) group.state = "completed";
+ else group.state = "active";
+ }
+
+ return [...groups.values()].sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
+}
diff --git a/frontend/slices/assistant/components/mcp-activity-view.tsx b/frontend/slices/assistant/components/mcp-activity-view.tsx
index 2d66fab6..eaf2bae9 100644
--- a/frontend/slices/assistant/components/mcp-activity-view.tsx
+++ b/frontend/slices/assistant/components/mcp-activity-view.tsx
@@ -1,20 +1,13 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { Activity, Camera, CheckCircle2, CircleDashed, ShieldAlert, XCircle } from "lucide-react";
+import {
+ Activity, BadgeCheck, BookOpen, Boxes, Camera, CheckCircle2, ChevronDown, CircleDashed,
+ FolderTree, Gauge, GitBranch, Globe2, Hammer, Route, Search, ShieldAlert, SquareTerminal,
+ Wrench, XCircle, type LucideIcon,
+} from "lucide-react";
import { Button } from "@/components/ui/button";
-
-export type McpActivityRow = {
- id: string;
- ts: string;
- actor?: string | null;
- tool: string;
- state: "started" | "completed" | "failed" | "denied" | "rate_limited";
- scope?: string;
- target?: string;
- durationMs?: number;
- detail?: string;
-};
+import { groupActivity, type McpActivityGroup, type McpActivityRow } from "./mcp-activity-model";
const stateMeta = {
started: { label: "running", Icon: CircleDashed, cls: "text-info" },
@@ -24,14 +17,90 @@ const stateMeta = {
rate_limited: { label: "limited", Icon: ShieldAlert, cls: "text-warning" },
} as const;
+const groupMeta = {
+ running: { label: "Running", Icon: CircleDashed, cls: "text-info" },
+ attention: { label: "Needs attention", Icon: ShieldAlert, cls: "text-warning" },
+ done: { label: "Verified", Icon: BadgeCheck, cls: "text-success" },
+ completed: { label: "Completed", Icon: CheckCircle2, cls: "text-success" },
+ active: { label: "In progress", Icon: Route, cls: "text-muted-foreground" },
+} as const;
+
+function toolMeta(row: McpActivityRow): { Icon: LucideIcon; label: string } {
+ const target = (row.target ?? "").toLowerCase();
+ if (row.tool.startsWith("skills_")) return { Icon: BookOpen, label: "Skills" };
+ if (row.tool.startsWith("workflow_")) return { Icon: Route, label: "Workflow" };
+ if (row.tool === "screen_capture") return { Icon: Camera, label: "Screenshot" };
+ if (row.tool === "fs_search") return { Icon: Search, label: "Search" };
+ if (row.tool.startsWith("fs_")) return { Icon: FolderTree, label: "Files" };
+ if (row.tool.startsWith("sys_")) return { Icon: Gauge, label: "System" };
+ if (row.tool.startsWith("apps_")) return { Icon: Boxes, label: "Apps" };
+ if (row.tool.startsWith("browser_")) return { Icon: Globe2, label: "Browser" };
+ if (row.tool === "exec_run" && /(build|test|verify|lint|typecheck|coverage)/.test(target))
+ return { Icon: target.includes("verify") ? BadgeCheck : Hammer, label: target.includes("verify") ? "Verify" : "Build/Test" };
+ if (row.tool === "exec_run" && /(^|\s)git(\s|$)/.test(target)) return { Icon: GitBranch, label: "Git" };
+ if (row.tool === "exec_run") return { Icon: SquareTerminal, label: "Terminal" };
+ return { Icon: Wrench, label: "Tool" };
+}
+
+const fmtDuration = (ms: number) => ms >= 1000 ? `${(ms / 1000).toFixed(ms >= 10_000 ? 0 : 1)}s` : `${ms}ms`;
+
+function WorkflowDetails({ group, initiallyOpen }: { group: McpActivityGroup; initiallyOpen: boolean }) {
+ const [open, setOpen] = useState(initiallyOpen);
+ const renderedOpen = group.state === "running" || open;
+ const status = groupMeta[group.state];
+ const StatusIcon = status.Icon;
+
+ return (
+ <details
+ className="group rounded-xl border border-border/70 bg-card/50"
+ open={renderedOpen}
+ onToggle={(event) => { if (group.state !== "running") setOpen(event.currentTarget.open); }}
+ >
+ <summary className="flex cursor-pointer list-none items-start gap-2 px-3 py-2.5">
+ <StatusIcon className={`mt-0.5 size-4 shrink-0 ${status.cls} ${group.state === "running" ? "animate-spin" : ""}`} />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-xs font-medium">{group.intent ?? (group.workflowId ? "MSO workflow" : group.rows[0]?.tool)}</p>
+ <p className="truncate text-[10px] text-muted-foreground">
+ {group.project ?? "No project"} · {group.rows.length} step{group.rows.length === 1 ? "" : "s"}
+ {group.durationMs ? ` · ${fmtDuration(group.durationMs)}` : ""} · {new Date(group.updatedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })}
+ </p>
+ </div>
+ <span className={`shrink-0 text-[10px] ${status.cls}`}>{status.label}</span>
+ <ChevronDown className="mt-0.5 size-3.5 shrink-0 text-muted-foreground transition-transform group-open:rotate-180" />
+ </summary>
+ <ul className="space-y-1 border-t border-border/70 p-2">
+ {group.rows.map((row) => {
+ const state = stateMeta[row.state];
+ const StateIcon = state.Icon;
+ const feature = toolMeta(row);
+ const FeatureIcon = feature.Icon;
+ return (
+ <li key={row.id} className="flex items-start gap-2 rounded-lg px-2 py-1.5 hover:bg-secondary/40">
+ <FeatureIcon className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-baseline gap-1.5">
+ <span className="text-[10px] text-muted-foreground">[{feature.label}]</span>
+ <code className="truncate font-mono text-[11px] font-medium">{row.tool}</code>
+ </div>
+ {row.target || row.detail ? <p className="truncate font-mono text-[10px] text-muted-foreground">{row.target ?? row.detail}</p> : null}
+ </div>
+ <StateIcon className={`mt-0.5 size-3 shrink-0 ${state.cls} ${row.state === "started" ? "animate-spin" : ""}`} />
+ {row.durationMs != null ? <span className="shrink-0 text-[9px] text-muted-foreground">{fmtDuration(row.durationMs)}</span> : null}
+ </li>
+ );
+ })}
+ </ul>
+ </details>
+ );
+}
+
export function McpActivityView() {
const [entries, setEntries] = useState<McpActivityRow[]>([]);
const [paused, setPaused] = useState(false);
-
const load = useCallback(() => {
- fetch("/api/mcp/activity?limit=160", { cache: "no-store" })
- .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
- .then((d: { entries?: McpActivityRow[] }) => setEntries(d.entries ?? []))
+ fetch("/api/mcp/activity?limit=200", { cache: "no-store" })
+ .then((response) => response.ok ? response.json() : Promise.reject(new Error(String(response.status))))
+ .then((data: { entries?: McpActivityRow[] }) => setEntries(data.entries ?? []))
.catch(() => undefined);
}, []);
@@ -42,18 +111,8 @@ export function McpActivityView() {
return () => window.clearInterval(timer);
}, [load, paused]);
- // The log writes one row at start and one at completion. Newest-first means the
- // first row for each id is the current state; collapse the pair for a readable
- // live feed instead of showing every tool twice.
- const rows = useMemo(() => {
- const seen = new Set<string>();
- return entries.filter((e) => {
- if (seen.has(e.id)) return false;
- seen.add(e.id);
- return true;
- }).slice(0, 80);
- }, [entries]);
- const running = rows.filter((r) => r.state === "started").length;
+ const groups = useMemo(() => groupActivity(entries), [entries]);
+ const running = groups.filter((group) => group.state === "running").length;
return (
<div className="flex h-full min-h-0 flex-col bg-background">
@@ -62,51 +121,26 @@ export function McpActivityView() {
<div className="min-w-0 flex-1">
<p className="text-xs font-semibold">MCP Activity</p>
<p className="text-[10px] text-muted-foreground">
- {running ? `${running} tool call${running === 1 ? "" : "s"} running now` : "Live tool-call trail from connected AI clients"}
+ {running ? `${running} workflow${running === 1 ? "" : "s"} running now` : "Live workflows grouped by task and feature"}
</p>
</div>
<span className="flex items-center gap-1 rounded-full bg-secondary px-2 py-1 text-[10px] text-muted-foreground">
<span className={`size-1.5 rounded-full ${paused ? "bg-muted-foreground" : "bg-success animate-pulse"}`} />
{paused ? "Paused" : "Live"}
</span>
- <Button variant="ghost" size="sm" className="h-8 text-[11px]" onClick={() => setPaused((v) => !v)}>
+ <Button variant="ghost" size="sm" className="h-8 text-[11px]" onClick={() => setPaused((value) => !value)}>
{paused ? "Resume" : "Pause"}
</Button>
</div>
-
<div className="min-h-0 flex-1 overflow-auto p-3">
- {rows.length === 0 ? (
+ {groups.length === 0 ? (
<div className="grid h-full place-items-center text-center text-xs text-muted-foreground">
- <div>
- <Camera className="mx-auto mb-2 size-7 opacity-60" />
- No MCP activity yet. Ask ChatGPT to check the VPS or capture the MSO screen.
- </div>
+ <div><Camera className="mx-auto mb-2 size-7 opacity-60" />No MCP activity yet.</div>
</div>
) : (
- <ul className="space-y-1.5">
- {rows.map((row) => {
- const meta = stateMeta[row.state];
- const Icon = meta.Icon;
- return (
- <li key={row.id} className="flex items-start gap-2 rounded-lg border border-border/70 bg-card/50 px-2.5 py-2">
- <Icon className={`mt-0.5 size-3.5 shrink-0 ${meta.cls} ${row.state === "started" ? "animate-spin" : ""}`} />
- <div className="min-w-0 flex-1">
- <div className="flex items-baseline gap-1.5">
- <code className="truncate font-mono text-[11px] font-medium">{row.tool}</code>
- <span className={`shrink-0 text-[10px] ${meta.cls}`}>{meta.label}</span>
- {row.durationMs != null ? <span className="shrink-0 text-[10px] text-muted-foreground">{row.durationMs} ms</span> : null}
- </div>
- {row.target || row.detail ? (
- <p className="truncate font-mono text-[10px] text-muted-foreground">{row.target ?? row.detail}</p>
- ) : null}
- </div>
- <time className="shrink-0 text-[9px] text-muted-foreground">
- {new Date(row.ts).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" })}
- </time>
- </li>
- );
- })}
- </ul>
+ <div className="space-y-2">
+ {groups.map((group, index) => <WorkflowDetails key={group.key} group={group} initiallyOpen={group.state === "running" || index < 2} />)}
+ </div>
)}
</div>
</div>
diff --git a/frontend/slices/os-settings/components/mcp-section.tsx b/frontend/slices/os-settings/components/mcp-section.tsx
index 0a508719..206ea25c 100644
--- a/frontend/slices/os-settings/components/mcp-section.tsx
+++ b/frontend/slices/os-settings/components/mcp-section.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { SettingsSection } from "@/features/shell-settings";
import { toast } from "@/features/os-shell";
import { IS_DEMO } from "@/lib/demo";
+import { McpToolsetCard, type McpToolsetInfo } from "./mcp-toolset-card";
type AuditRow = {
ts?: string;
@@ -55,7 +56,7 @@ function CopyRow({ label, value }: { label: string; value: string }) {
}
export function McpSection() {
- const [state, setState] = useState<{ enabled: boolean; maxScope: string; tokens: TokenRow[] } | null>(null);
+ const [state, setState] = useState<{ enabled: boolean; maxScope: string; toolset: McpToolsetInfo; tokens: TokenRow[] } | null>(null);
const [trail, setTrail] = useState<AuditRow[]>([]);
const [origin, setOrigin] = useState("");
@@ -124,6 +125,7 @@ export function McpSection() {
<code className="font-mono">{origin}/mcp</code> and nothing else. Highest tier this server will
mint: <strong>{state.maxScope}</strong> (<code className="font-mono">OS_MCP_MAX_SCOPE</code>).
</p>
+ <McpToolsetCard info={state.toolset} />
</div>
<div className="mt-3 border-t border-border pt-3">
diff --git a/frontend/slices/os-settings/components/mcp-toolset-card.tsx b/frontend/slices/os-settings/components/mcp-toolset-card.tsx
new file mode 100644
index 00000000..c3632cd2
--- /dev/null
+++ b/frontend/slices/os-settings/components/mcp-toolset-card.tsx
@@ -0,0 +1,77 @@
+"use client";
+
+import { useMemo, useState, useSyncExternalStore } from "react";
+import { BadgeCheck, Copy, RefreshCw, Wrench } from "lucide-react";
+import { Button } from "@/components/ui/button";
+
+export type McpToolsetInfo = {
+ serverVersion: string;
+ version: string;
+ hash: string;
+ changedAt: string;
+ toolCount: number;
+ byScope: { read: number; write: number; exec: number };
+};
+
+const ACK_KEY = "mso.mcp.toolset-ack";
+const ACK_EVENT = "mso:mcp-toolset-ack";
+const subscribeAck = (callback: () => void) => {
+ window.addEventListener("storage", callback);
+ window.addEventListener(ACK_EVENT, callback);
+ return () => {
+ window.removeEventListener("storage", callback);
+ window.removeEventListener(ACK_EVENT, callback);
+ };
+};
+const ackSnapshot = () => window.localStorage.getItem(ACK_KEY);
+const serverAckSnapshot = () => null;
+
+export function McpToolsetCard({ info }: { info: McpToolsetInfo }) {
+ const signature = useMemo(() => `${info.version}:${info.hash}:${info.toolCount}`, [info]);
+ const ack = useSyncExternalStore(subscribeAck, ackSnapshot, serverAckSnapshot);
+ const [copied, setCopied] = useState(false);
+ const current = ack === signature;
+ const changed = Boolean(ack && !current);
+
+ return (
+ <div className="mt-3 rounded-xl border border-border bg-secondary/30 p-3">
+ <div className="flex items-start gap-2">
+ <Wrench className="mt-0.5 size-4 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <p className="text-xs font-medium">MCP toolset {info.version}</p>
+ <span className="rounded bg-secondary px-1.5 py-0.5 font-mono text-[10px]">{info.toolCount} tools</span>
+ <span className="font-mono text-[10px] text-muted-foreground">{info.hash}</span>
+ </div>
+ <p className="mt-1 text-[11px] text-muted-foreground">
+ Server {info.serverVersion} · read {info.byScope.read} · write {info.byScope.write} · exec {info.byScope.exec} · changed {info.changedAt.slice(0, 10)}
+ </p>
+ <p className={`mt-1 text-[11px] ${changed ? "text-warning" : "text-muted-foreground"}`}>
+ {current
+ ? "ChatGPT action snapshot marked current for this browser."
+ : changed
+ ? "Toolset signature changed. Refresh or reconnect the MSO app in ChatGPT, then mark it current."
+ : "After refreshing the MSO app in ChatGPT, mark this signature current so future drift is visible."}
+ </p>
+ </div>
+ {current ? <BadgeCheck className="size-4 shrink-0 text-success" /> : <RefreshCw className="size-4 shrink-0 text-warning" />}
+ </div>
+ <div className="mt-2 flex gap-2">
+ <Button
+ type="button" variant="secondary" size="sm" className="h-8 text-[11px]"
+ onClick={() => { window.localStorage.setItem(ACK_KEY, signature); window.dispatchEvent(new Event(ACK_EVENT)); }}
+ >
+ {current ? "Marked refreshed" : "Mark ChatGPT refreshed"}
+ </Button>
+ <Button
+ type="button" variant="ghost" size="sm" className="h-8 text-[11px]"
+ onClick={() => void navigator.clipboard.writeText(signature).then(() => {
+ setCopied(true); window.setTimeout(() => setCopied(false), 1500);
+ })}
+ >
+ <Copy className="mr-1 size-3.5" />{copied ? "Copied" : "Copy signature"}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/lib/host/child-env.test.ts b/lib/host/child-env.test.ts
index 63f50314..54632a50 100644
--- a/lib/host/child-env.test.ts
+++ b/lib/host/child-env.test.ts
@@ -25,7 +25,7 @@ describe("childEnv (secret scrub for spawned shells)", () => {
saved.OS_FS_READ_ROOTS = process.env.OS_FS_READ_ROOTS;
process.env.OS_FS_READ_ROOTS = "/srv";
const env = childEnv();
- expect(env.PATH).toBe(process.env.PATH);
+ for (const part of (process.env.PATH ?? "").split(":")) expect(env.PATH?.split(":")).toContain(part);
expect(env.NODE_ENV).toBe(process.env.NODE_ENV);
expect(env.OS_FS_READ_ROOTS).toBe("/srv"); // bounds config is not a secret
});
@@ -44,4 +44,14 @@ describe("childEnv (secret scrub for spawned shells)", () => {
const env = childEnv();
expect(Object.values(env).every((v) => typeof v === "string")).toBe(true);
});
+ it("adds owner CLI directories to PATH without duplicates", () => {
+ saved.HOME = process.env.HOME;
+ saved.PATH = process.env.PATH;
+ process.env.HOME = "/home/tester";
+ process.env.PATH = "/usr/bin:/home/tester/.bun/bin";
+ const env = childEnv();
+ expect(env.PATH?.split(":").slice(0, 2)).toEqual(["/home/tester/.local/bin", "/home/tester/.bun/bin"]);
+ expect(env.PATH?.split(":").filter((part) => part === "/home/tester/.bun/bin")).toHaveLength(1);
+ });
+
});
diff --git a/lib/host/child-env.ts b/lib/host/child-env.ts
index 9279c8ba..37a6293b 100644
--- a/lib/host/child-env.ts
+++ b/lib/host/child-env.ts
@@ -1,9 +1,12 @@
+import os from "os";
+import path from "path";
+
// SERVER-ONLY. The environment handed to spawned shells (exec + PTY) with the
// app's OWN secrets scrubbed out. Without this, any `printenv` in the terminal
// reveals the session secret / login password / browser secret / agent token /
// BYOK key — which would let a hijacked session mint cookies forever, defeating
-// the credential denylist in paths.ts. PATH/HOME/SHELL/locale + everything else
-// pass through unchanged (a real login shell still works).
+// the credential denylist in paths.ts. HOME/SHELL/locale + everything else pass through; PATH is supplemented with
+// owner CLI directories (a real login shell still works).
//
// Residual (documented in SECURITY.md): a same-uid process can still read
// /proc/<pid>/environ of the mso process itself — the boundary is the OS
@@ -34,5 +37,13 @@ export function childEnv(): Record<string, string> {
for (const [k, v] of Object.entries(process.env)) {
if (v !== undefined && !isSecretVar(k)) env[k] = v;
}
+ // systemd commonly supplies only system paths. MSO-managed projects use Bun and
+ // owner-installed CLIs, so every exec/PTY otherwise starts by rediscovering an
+ // absolute binary path. These are executable directories, not credentials, and
+ // the child already runs as the same owner. Keep them first, without duplicates.
+ const home = env.HOME || os.homedir();
+ const userBins = [path.join(home, ".local/bin"), path.join(home, ".bun/bin")];
+ const current = (env.PATH || "").split(path.delimiter).filter(Boolean);
+ env.PATH = [...new Set([...userBins, ...current])].join(path.delimiter);
return env;
}
diff --git a/lib/host/fs.ts b/lib/host/fs.ts
index 08d58290..7ee5d197 100644
--- a/lib/host/fs.ts
+++ b/lib/host/fs.ts
@@ -5,6 +5,7 @@ import { promises as fs, createReadStream, type ReadStream } from "fs";
import path from "path";
import type { FsList, FsUsage } from "@/lib/os-api/types";
import { HostError } from "./host-error";
+import { projectAliasTarget } from "./project-aliases";
import {
appSecretCopyFilter,
assertNoAppSecretDescendants,
@@ -121,6 +122,12 @@ export async function searchFs(
const max = opts.max ?? 30;
const maxDepth = opts.maxDepth ?? 6;
const out: { name: string; path: string; kind: "dir" }[] = [];
+ const alias = projectAliasTarget(query);
+ if (alias) {
+ const candidate = await resolveReadable(path.join(root, alias)).catch(() => null);
+ if (candidate && (await fs.stat(candidate).catch(() => null))?.isDirectory())
+ return [{ name: alias, path: candidate, kind: "dir" }];
+ }
async function walk(dir: string, depth: number): Promise<void> {
if (out.length >= max || depth > maxDepth) return;
@@ -133,7 +140,8 @@ export async function searchFs(
for (const e of ents) {
if (out.length >= max) return;
if (!e.isDirectory()) continue;
- if (e.name.toLowerCase().includes(q)) out.push({ name: e.name, path: path.join(dir, e.name), kind: "dir" });
+ const hitPath = path.join(dir, e.name);
+ if (e.name.toLowerCase().includes(q) && !out.some((hit) => hit.path === hitPath)) out.push({ name: e.name, path: hitPath, kind: "dir" });
if (!SEARCH_SKIP.has(e.name) && !e.name.startsWith(".")) await walk(path.join(dir, e.name), depth + 1);
}
}
diff --git a/lib/host/guarded-write.test.ts b/lib/host/guarded-write.test.ts
new file mode 100644
index 00000000..7166f4bd
--- /dev/null
+++ b/lib/host/guarded-write.test.ts
@@ -0,0 +1,38 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-guarded-write-"));
+const previousRead = process.env.OS_FS_READ_ROOTS;
+const previousWrite = process.env.OS_FS_WRITE_ROOTS;
+process.env.OS_FS_READ_ROOTS = dir;
+process.env.OS_FS_WRITE_ROOTS = dir;
+const { sha256Text } = await import("./hash");
+const { writeFileGuarded } = await import("./guarded-write");
+
+describe("guarded file writes", () => {
+ beforeAll(async () => { await fs.writeFile(path.join(dir, "note.txt"), "one"); });
+ 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 fs.rm(dir, { recursive: true, force: true });
+ });
+
+ it("writes when the inspected hash still matches", async () => {
+ const result = await writeFileGuarded({
+ path: path.join(dir, "note.txt"), content: "two", expectedSha256: sha256Text("one"),
+ });
+ expect(result).toMatchObject({ bytes: 3, sha256: sha256Text("two"), previousSha256: sha256Text("one") });
+ expect(await fs.readFile(path.join(dir, "note.txt"), "utf8")).toBe("two");
+ });
+
+ it("refuses a stale overwrite and leaves current bytes intact", async () => {
+ await expect(writeFileGuarded({
+ path: path.join(dir, "note.txt"), content: "three", expectedSha256: sha256Text("one"),
+ })).rejects.toThrow("File changed since fs_read");
+ expect(await fs.readFile(path.join(dir, "note.txt"), "utf8")).toBe("two");
+ });
+});
diff --git a/lib/host/guarded-write.ts b/lib/host/guarded-write.ts
new file mode 100644
index 00000000..4f68f30d
--- /dev/null
+++ b/lib/host/guarded-write.ts
@@ -0,0 +1,28 @@
+import { HostError } from "./host-error";
+import { readFile, writeFile } from "./fs";
+import { sha256Text, utf8Bytes } from "./hash";
+
+export async function writeFileGuarded(input: {
+ path: string;
+ content: string;
+ expectedSha256?: string;
+}): Promise<{ path: string; bytes: number; sha256: string; previousSha256?: string }> {
+ let previousSha256: string | undefined;
+ if (input.expectedSha256) {
+ if (!/^[a-f0-9]{64}$/i.test(input.expectedSha256))
+ throw new HostError("expected_sha256 must be a 64-character SHA-256 hex digest from fs_read");
+ const current = await readFile(input.path).catch(() => {
+ throw new HostError("expected_sha256 requires an existing readable file");
+ });
+ previousSha256 = sha256Text(current);
+ if (previousSha256.toLowerCase() !== input.expectedSha256.toLowerCase())
+ throw new HostError("File changed since fs_read; inspect it again before overwriting");
+ }
+ await writeFile(input.path, input.content);
+ return {
+ path: input.path,
+ bytes: utf8Bytes(input.content),
+ sha256: sha256Text(input.content),
+ ...(previousSha256 ? { previousSha256 } : {}),
+ };
+}
diff --git a/lib/host/hash.ts b/lib/host/hash.ts
new file mode 100644
index 00000000..fe3de151
--- /dev/null
+++ b/lib/host/hash.ts
@@ -0,0 +1,9 @@
+import { createHash } from "crypto";
+
+export function sha256Text(value: string): string {
+ return createHash("sha256").update(value, "utf8").digest("hex");
+}
+
+export function utf8Bytes(value: string): number {
+ return Buffer.byteLength(value, "utf8");
+}
diff --git a/lib/host/index.ts b/lib/host/index.ts
index c2a98fc9..ce5a2d13 100644
--- a/lib/host/index.ts
+++ b/lib/host/index.ts
@@ -8,6 +8,11 @@ export { zipStream } from "./fs-zip";
export { parseMultipart, boundaryFromContentType, UploadTooLargeError } from "./multipart";
export type { MultipartPart } from "./multipart";
export { runCommand } from "./exec";
+export { sha256Text, utf8Bytes } from "./hash";
+export { writeFileGuarded } from "./guarded-write";
+export { resolveProjectHint, inspectProject } from "./projects";
+export { normalizeProjectKey, projectAliasesFor, projectAliasTarget } from "./project-aliases";
+export type { ProjectResolution } from "./projects";
export { openPty, attachPty, writePty, resizePty, closePty, hasPty } from "./pty";
export { stats, processes } from "./sys";
export { captureMsoScreen } from "./screenshot";
diff --git a/lib/host/project-aliases.ts b/lib/host/project-aliases.ts
new file mode 100644
index 00000000..8083df19
--- /dev/null
+++ b/lib/host/project-aliases.ts
@@ -0,0 +1,20 @@
+const PROJECT_ALIASES = [
+ { alias: "os-vps", target: "mso" },
+ { alias: "manef shell os", target: "mso" },
+ { alias: "manef-shell-os", target: "mso" },
+ { alias: "mso vps", target: "mso" },
+] as const;
+
+export function normalizeProjectKey(value: string): string {
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, "");
+}
+
+export function projectAliasTarget(value: string): string | undefined {
+ const key = normalizeProjectKey(value);
+ return PROJECT_ALIASES.find((row) => normalizeProjectKey(row.alias) === key)?.target;
+}
+
+export function projectAliasesFor(target: string): string[] {
+ const key = normalizeProjectKey(target);
+ return PROJECT_ALIASES.filter((row) => normalizeProjectKey(row.target) === key).map((row) => row.alias);
+}
diff --git a/lib/host/projects.test.ts b/lib/host/projects.test.ts
new file mode 100644
index 00000000..18cb4d81
--- /dev/null
+++ b/lib/host/projects.test.ts
@@ -0,0 +1,57 @@
+import { afterAll, describe, expect, it } from "vitest";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-projects-"));
+const previousRead = process.env.OS_FS_READ_ROOTS;
+process.env.OS_FS_READ_ROOTS = root;
+await fs.mkdir(path.join(root, "mso"));
+await fs.writeFile(path.join(root, "mso", "package.json"), JSON.stringify({ name: "mso", version: "1.2.3", scripts: { test: "vitest" } }));
+const { inspectProject, projectAliasTarget, resolveProjectHint, searchFs } = await import("./index");
+
+describe("project resolver", () => {
+ afterAll(async () => {
+ if (previousRead === undefined) delete process.env.OS_FS_READ_ROOTS;
+ else process.env.OS_FS_READ_ROOTS = previousRead;
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it("maps historic MSO names to the canonical project", async () => {
+ expect(projectAliasTarget("os-vps")).toBe("mso");
+ await expect(resolveProjectHint("Manef Shell OS", root)).resolves.toMatchObject({
+ name: "mso", path: path.join(root, "mso"), matchedBy: "alias",
+ });
+ });
+
+ it("resolves package and directory names without an alias", async () => {
+ await expect(resolveProjectHint("mso", root)).resolves.toMatchObject({ name: "mso", matchedBy: "name" });
+ });
+ it("makes fs_search resolve the historic os-vps alias immediately", async () => {
+ const hits = await searchFs("os-vps", { root, maxDepth: 1 });
+ expect(hits).toEqual([{ name: "mso", path: path.join(root, "mso"), kind: "dir" }]);
+ });
+
+ it("does not follow package or git metadata symlinks", async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "mso-project-outside-"));
+ await fs.writeFile(path.join(outside, "package.json"), JSON.stringify({ name: "secret-package" }));
+
+ const linked = path.join(root, "linked");
+ await fs.mkdir(linked);
+ await fs.symlink(path.join(outside, "package.json"), path.join(linked, "package.json"));
+ const linkedResolution = await resolveProjectHint("linked", root);
+ expect(linkedResolution).not.toBeNull();
+ const linkedInspection = await inspectProject(linkedResolution!);
+ expect(linkedInspection.package.name).toBeUndefined();
+ expect(linkedInspection.package.scripts).toEqual([]);
+
+ const evil = path.join(root, "evil");
+ await fs.mkdir(evil);
+ await fs.symlink(outside, path.join(evil, ".git"));
+ const evilResolution = await resolveProjectHint("evil", root);
+ expect(evilResolution).not.toBeNull();
+ await expect(inspectProject(evilResolution!)).resolves.toMatchObject({ git: { available: false, statusChecked: false } });
+ await fs.rm(outside, { recursive: true, force: true });
+ });
+
+});
diff --git a/lib/host/projects.ts b/lib/host/projects.ts
new file mode 100644
index 00000000..80250e55
--- /dev/null
+++ b/lib/host/projects.ts
@@ -0,0 +1,152 @@
+import { promises as fs } from "fs";
+import path from "path";
+import { runCommand } from "./exec";
+import { normalizeProjectKey, projectAliasesFor, projectAliasTarget } from "./project-aliases";
+import { resolveReadable } from "./paths";
+
+export type ProjectResolution = {
+ hint: string;
+ name: string;
+ path: string;
+ packageName?: string;
+ aliases: string[];
+ matchedBy: "path" | "name" | "alias" | "package" | "fuzzy";
+};
+
+type PackageMeta = { name?: string; version?: string; scripts: string[] };
+type GitMeta = {
+ available: boolean;
+ branch?: string;
+ clean?: boolean;
+ changes?: string[];
+ head?: { sha: string; subject?: string; date?: string };
+ statusChecked: boolean;
+ error?: string;
+};
+
+async function readRegularText(file: string): Promise<string> {
+ const stat = await fs.lstat(file).catch(() => null);
+ if (!stat?.isFile() || stat.isSymbolicLink()) return "";
+ return fs.readFile(file, "utf8").catch(() => "");
+}
+
+async function packageMeta(dir: string): Promise<PackageMeta> {
+ try {
+ const raw = await readRegularText(path.join(dir, "package.json"));
+ if (!raw) return { scripts: [] };
+ const parsed = JSON.parse(raw) as {
+ name?: unknown; version?: unknown; scripts?: unknown;
+ };
+ return {
+ name: typeof parsed.name === "string" ? parsed.name : undefined,
+ version: typeof parsed.version === "string" ? parsed.version : undefined,
+ scripts: parsed.scripts && typeof parsed.scripts === "object" ? Object.keys(parsed.scripts) : [],
+ };
+ } catch {
+ return { scripts: [] };
+ }
+}
+
+async function boundedGitMeta(dir: string): Promise<GitMeta> {
+ const gitDir = path.join(dir, ".git");
+ const gitStat = await fs.lstat(gitDir).catch(() => null);
+ if (!gitStat?.isDirectory() || gitStat.isSymbolicLink()) return { available: false, statusChecked: false };
+ const head = await readRegularText(path.join(gitDir, "HEAD"));
+ if (!head) return { available: false, statusChecked: false };
+ const candidateRef = head.trim().startsWith("ref: ") ? head.trim().slice(5) : undefined;
+ const ref = candidateRef && /^refs\/(?:heads|remotes)\/[a-z0-9._\/-]+$/i.test(candidateRef) && !candidateRef.includes("..")
+ ? candidateRef
+ : undefined;
+ const branch = ref?.replace(/^refs\/heads\//, "");
+ let sha = ref ? (await readRegularText(path.join(gitDir, ref))).trim() : head.trim();
+ if (!sha && ref) {
+ const packed = await readRegularText(path.join(gitDir, "packed-refs"));
+ sha = packed.split("\n").find((line) => line.endsWith(` ${ref}`))?.split(" ")[0] ?? "";
+ }
+ return { available: true, branch, statusChecked: false, ...(sha ? { head: { sha } } : {}) };
+}
+
+async function fullGitMeta(dir: string): Promise<GitMeta> {
+ const marker = "__MSO_HEAD__";
+ const result = await runCommand(`git status --short --branch && printf '\n${marker}\n' && git log -1 --format='%H%n%s%n%aI'`, dir);
+ if (result.code !== 0)
+ return { available: false, statusChecked: true, error: (result.stderr || result.stdout).trim().slice(0, 220) };
+ const [statusPart, headPart = ""] = result.stdout.split(`\n${marker}\n`);
+ const statusLines = statusPart.split("\n").filter(Boolean);
+ const changes = statusLines.slice(1, 81);
+ const [sha = "", subject = "", date = ""] = headPart.trim().split("\n");
+ return {
+ available: true,
+ branch: statusLines[0]?.replace(/^##\s*/, ""),
+ clean: changes.length === 0,
+ changes,
+ statusChecked: true,
+ head: { sha, subject, date },
+ };
+}
+
+export async function resolveProjectHint(hint: string, rootHint = "~/projects"): Promise<ProjectResolution | null> {
+ const raw = hint.trim();
+ if (!raw) return null;
+ const pathHint = raw.startsWith("projects/") ? `~/${raw}` : raw;
+ if (/^(?:~\/|\/|\.\.?\/)/.test(pathHint)) {
+ const resolved = await resolveReadable(pathHint).catch(() => null);
+ if (resolved && (await fs.stat(resolved).catch(() => null))?.isDirectory()) {
+ const meta = await packageMeta(resolved);
+ return { hint: raw, name: path.basename(resolved), path: resolved, packageName: meta.name, aliases: projectAliasesFor(path.basename(resolved)), matchedBy: "path" };
+ }
+ }
+
+ const root = await resolveReadable(rootHint);
+ const query = normalizeProjectKey(raw);
+ const aliasTarget = projectAliasTarget(raw);
+
+ // Known aliases and exact directory names are the common path. Resolve them in
+ // one bounded stat/read instead of scanning and parsing every project package.
+ const directName = aliasTarget ?? (/^[a-z0-9._-]+$/i.test(raw) ? raw : undefined);
+ if (directName) {
+ const candidate = await resolveReadable(path.join(root, directName)).catch(() => null);
+ if (candidate && (await fs.stat(candidate).catch(() => null))?.isDirectory()) {
+ const meta = await packageMeta(candidate);
+ const name = path.basename(candidate);
+ return {
+ hint: raw,
+ name,
+ path: candidate,
+ packageName: meta.name,
+ aliases: projectAliasesFor(name),
+ matchedBy: aliasTarget ? "alias" : "name",
+ };
+ }
+ }
+
+ const entries = (await fs.readdir(root, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).slice(0, 300);
+ const candidates = await Promise.all(entries.map(async (entry) => {
+ const dir = path.join(root, entry.name);
+ const meta = await packageMeta(dir);
+ const nameKey = normalizeProjectKey(entry.name);
+ const packageKey = normalizeProjectKey(meta.name ?? "");
+ let score = 0;
+ let matchedBy: ProjectResolution["matchedBy"] = "fuzzy";
+ if (nameKey === query) { score = 100; matchedBy = "name"; }
+ else if (aliasTarget && nameKey === normalizeProjectKey(aliasTarget)) { score = 98; matchedBy = "alias"; }
+ else if (packageKey && packageKey === query) { score = 94; matchedBy = "package"; }
+ else if (nameKey.includes(query) || query.includes(nameKey)) score = 65;
+ else if (packageKey && (packageKey.includes(query) || query.includes(packageKey))) score = 60;
+ return { entry, dir, meta, score, matchedBy };
+ }));
+ const best = candidates.sort((a, b) => b.score - a.score || a.entry.name.localeCompare(b.entry.name))[0];
+ if (!best || best.score < 60) return null;
+ return {
+ hint: raw, name: best.entry.name, path: best.dir, packageName: best.meta.name,
+ aliases: projectAliasesFor(best.entry.name), matchedBy: best.matchedBy,
+ };
+}
+
+export async function inspectProject(project: ProjectResolution, options: { includeGitStatus?: boolean } = {}) {
+ return {
+ git: options.includeGitStatus ? await fullGitMeta(project.path) : await boundedGitMeta(project.path),
+ package: await packageMeta(project.path),
+ };
+}
diff --git a/lib/mcp/activity.test.ts b/lib/mcp/activity.test.ts
index b4306e23..7be66fac 100644
--- a/lib/mcp/activity.test.ts
+++ b/lib/mcp/activity.test.ts
@@ -24,4 +24,13 @@ describe("MCP activity stream", () => {
expect(rows[0]).toMatchObject({ id: "a", state: "completed", durationMs: 12 });
expect(rows[1]).toMatchObject({ id: "a", state: "started" });
});
+ it("preserves redacted workflow context for UI grouping", async () => {
+ await recordMcpActivity({
+ id: "flow", tool: "exec_run", state: "completed", scope: "exec", workflowId: "w1",
+ workflowIntent: "deploy token=secret-value", workflowProject: "~/projects/mso", durationMs: 8,
+ });
+ const [row] = await readMcpActivity(1);
+ expect(row).toMatchObject({ workflowId: "w1", workflowIntent: "deploy token=[redacted]", workflowProject: "~/projects/mso" });
+ });
+
});
diff --git a/lib/mcp/activity.ts b/lib/mcp/activity.ts
index 81ac23cf..80ac90d8 100644
--- a/lib/mcp/activity.ts
+++ b/lib/mcp/activity.ts
@@ -13,6 +13,8 @@ export interface McpActivityEntry {
state: McpActivityState;
scope?: string;
workflowId?: string;
+ workflowIntent?: string;
+ workflowProject?: string;
target?: string;
durationMs?: number;
detail?: string;
@@ -59,6 +61,8 @@ export function recordMcpActivity(entry: Omit<McpActivityEntry, "ts"> & { ts?: s
const line = JSON.stringify({
...entry,
ts: entry.ts ?? new Date().toISOString(),
+ workflowIntent: trunc(entry.workflowIntent ? safeActivityText(entry.workflowIntent) : undefined, 500),
+ workflowProject: trunc(entry.workflowProject ? safeActivityText(entry.workflowProject) : undefined, 240),
target: trunc(entry.target),
detail: trunc(entry.detail, 220),
}) + "\n";
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index 727b139f..8df0b53a 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -25,10 +25,25 @@ describe("protocol", () => {
expect((r.result as Record<string, unknown>).protocolVersion).toBe("2025-06-18");
});
- it("advertises the learning loop to connected MCP clients", async () => {
- const r = await dispatch({ id: 1, method: "initialize" }, "read");
- expect((r.result as { instructions?: string }).instructions).toContain("skills_search");
- expect((r.result as { instructions?: string }).instructions).toContain("workflow_finish");
+ it("advertises only the workflow operations available at each scope", async () => {
+ const read = await dispatch({ id: 1, method: "initialize" }, "read");
+ const readInstructions = (read.result as { instructions?: string }).instructions;
+ expect(readInstructions).toContain("skills_search");
+ expect(readInstructions).not.toContain("workflow_start");
+ expect(readInstructions).not.toContain("workflow_finish");
+
+ const exec = await dispatch({ id: 2, method: "initialize" }, "exec");
+ const execInstructions = (exec.result as { instructions?: string }).instructions;
+ expect(execInstructions).toContain("workflow_start");
+ expect(execInstructions).toContain("workflow_finish");
+ });
+
+ 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.2.0");
+ expect(result._meta.toolset.toolCount).toBe(TOOLS.length);
+ expect(result._meta.toolset.hash).toMatch(/^[a-f0-9]{16}$/);
});
it("answers ping and initialized", async () => {
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
index 84d19af0..50559765 100644
--- a/lib/mcp/dispatch.ts
+++ b/lib/mcp/dispatch.ts
@@ -1,13 +1,10 @@
import { audit, rateLimited } from "@/lib/host";
-import { TOOLS, TOOLS_BY_NAME } from "./tools";
-import { isMcpDirectResult } from "./tool-kit";
+import { activeWorkflowForActor, recordWorkflowStep, type ActiveWorkflow } from "@/lib/skills/memory";
import { activityTarget, newActivityId, recordMcpActivity } from "./activity";
-import { activeWorkflowForActor, recordWorkflowStep } from "@/lib/skills/memory";
import { allows, type Scope } from "./scope";
-
-// JSON-RPC 2.0 dispatch for the MCP server. No SDK: the surface is initialize,
-// ping, notifications/*, tools/list and tools/call, and hand-rolling it is far
-// less code than adapting a transport we do not use.
+import { isMcpDirectResult } from "./tool-kit";
+import { MCP_SERVER_VERSION, toolsetInfo } from "./toolset";
+import { TOOLS, TOOLS_BY_NAME } from "./tools";
export interface RpcRequest {
jsonrpc?: string;
@@ -16,10 +13,7 @@ export interface RpcRequest {
params?: { name?: string; arguments?: Record<string, unknown>; protocolVersion?: string };
}
-// Newest version every shipping client still accepts. We echo the client's own
-// version when it sends one, per the spec's negotiation rule.
const PROTOCOL = "2024-11-05";
-
export const UNAUTHORIZED = -32001;
export const RATE_LIMITED = -32029;
@@ -27,126 +21,125 @@ const ok = (id: RpcRequest["id"], result: unknown) => ({ jsonrpc: "2.0", id: id
const fail = (id: RpcRequest["id"], code: number, message: string) =>
({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
-/** True for a JSON-RPC notification — no id, expects no response body. */
export function isNotification(body: unknown): boolean {
const b = body as RpcRequest | null;
return b?.id == null && String(b?.method ?? "").startsWith("notifications/");
}
-function toolList(scope: Scope) {
- // Only advertise what this token can actually call. A tool listed but refused
- // on use makes the model retry the same dead call; not listing it makes the
- // model route around it, which is the behaviour we want from a read-only token.
- return TOOLS.filter((t) => allows(scope, t.scope)).map((t) => ({
- name: t.name,
- description: t.description,
- inputSchema: t.inputSchema,
- ...(t.annotations ? { annotations: t.annotations } : {}),
- }));
+const visibleTools = (scope: Scope) => TOOLS.filter((tool) => allows(scope, tool.scope));
+const toolList = (scope: Scope) => visibleTools(scope).map((tool) => ({
+ name: tool.name,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ ...(tool.annotations ? { annotations: tool.annotations } : {}),
+}));
+
+function instructions(scope: Scope): string {
+ const startup = scope === "read"
+ ? "This token is read-only: use skills_search for capability discovery, then bounded read tools. Verify the answer without attempting workflow memory writes."
+ : "For any task needing two or more operational calls, call workflow_start directly as the ONE startup call; it already searches trusted skills and recipes, resolves the project, and reports the current toolset. Verify before workflow_finish.";
+ return `${startup} Prefer bounded tools for one or two direct operations. At exec scope, use one narrow exec_run batch for repository-wide search, git, tests, builds, or three or more related checks. Show concise progress using badges such as [Skills], [Files], [Terminal], [Git], [Build], [Verify], and [Screenshot]; never expose private chain-of-thought.`;
+}
+
+function flowFields(workflow: ActiveWorkflow | null | undefined) {
+ return workflow ? {
+ workflowId: workflow.id,
+ workflowIntent: workflow.intent,
+ workflowProject: workflow.project,
+ } : {};
+}
+
+function workflowFromResult(result: unknown): ActiveWorkflow | null {
+ if (!result || typeof result !== "object") return null;
+ const workflow = (result as { workflow?: unknown }).workflow;
+ if (!workflow || typeof workflow !== "object") return null;
+ const row = workflow as Partial<ActiveWorkflow>;
+ return typeof row.id === "string" && typeof row.intent === "string"
+ ? row as ActiveWorkflow
+ : null;
}
-/**
- * @param actor identifies WHICH token acted, as `mcp:<id>` — the same id the
- * Settings table and `mso mcp list` show, so a line in the trail maps back to a
- * revoke button. Never the raw bearer.
- */
export async function dispatch(req: RpcRequest, scope: Scope, actor?: string): Promise<Record<string, unknown>> {
const id = req.id ?? null;
switch (req.method) {
- case "initialize":
+ case "initialize": {
+ const toolset = toolsetInfo(visibleTools(scope), scope);
return ok(id, {
protocolVersion: req.params?.protocolVersion ?? PROTOCOL,
capabilities: { tools: { listChanged: false } },
- serverInfo: { name: "mso", version: "1.1.0" },
- instructions:
- "For a task likely to need two or more tool calls: call skills_search, then workflow_start before operational work, " +
- "reuse a relevant safe recipe, verify the result, and call workflow_finish so MSO retains the fastest successful path.",
+ serverInfo: { name: "mso", version: MCP_SERVER_VERSION },
+ instructions: instructions(scope),
+ _meta: { toolset },
});
+ }
case "notifications/initialized":
case "ping":
return ok(id, {});
- case "tools/list":
- return ok(id, { tools: toolList(scope) });
+ case "tools/list": {
+ const tools = visibleTools(scope);
+ return ok(id, { tools: toolList(scope), _meta: { toolset: toolsetInfo(tools, scope) } });
+ }
case "tools/call": {
const name = String(req.params?.name ?? "");
const args = req.params?.arguments ?? {};
const tool = TOOLS_BY_NAME.get(name);
if (!tool) return fail(id, -32602, `unknown tool: ${name}`);
const activeWorkflow = await activeWorkflowForActor(actor);
- const workflowId = activeWorkflow?.id;
- // Scope is re-checked HERE, not just at tools/list — a client can call any
- // name it likes, and the list is only a hint.
+ const initialFlow = flowFields(activeWorkflow);
if (!allows(scope, tool.scope)) {
- // Logged even though nothing happened: a `read` connector repeatedly
- // reaching for exec_run is what a prompt-injected model looks like from
- // the outside, and it is the only place that signal is visible.
void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: `scope ${scope} < ${tool.scope}` });
const deniedId = newActivityId();
- const deniedTarget = activityTarget(args);
- void recordMcpActivity({ id: deniedId, actor, tool: name, state: "denied", scope, workflowId, target: deniedTarget, detail: `scope ${scope} < ${tool.scope}` });
- await recordWorkflowStep(actor, workflowId, { id: deniedId, tool: name, state: "denied", target: deniedTarget, args, ts: new Date().toISOString() });
+ const target = activityTarget(args);
+ void recordMcpActivity({ id: deniedId, actor, tool: name, state: "denied", scope, ...initialFlow, target, detail: `scope ${scope} < ${tool.scope}` });
+ await recordWorkflowStep(actor, activeWorkflow?.id, { id: deniedId, tool: name, state: "denied", target, args, ts: new Date().toISOString() });
return ok(id, {
content: [{ type: "text", text: `error: this token holds scope "${scope}"; ${name} needs "${tool.scope}". Mint a new token in mso Settings → MCP.` }],
isError: true,
});
}
- for (const k of tool.inputSchema.required ?? []) {
- if (args[k] == null) return fail(id, -32602, `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`);
+ for (const key of tool.inputSchema.required ?? []) {
+ if (args[key] == null) return fail(id, -32602, `${name} needs { ${(tool.inputSchema.required ?? []).join(", ")} }`);
}
- // The per-token bucket in app/mcp/route.ts does not know which tool ran, so
- // without this an MCP client could restart a daemon 120x/min while the UI and
- // the CLI share a 12/min bucket for the same operation. Deliberately the SAME
- // key the route uses, so the two share one bucket instead of getting one each.
if (tool.limit) {
const suffix = tool.limit.keyArg ? String(args[tool.limit.keyArg] ?? "") : (actor ?? "mcp");
if (rateLimited(`${tool.limit.key}:${suffix}`, tool.limit.max, tool.limit.windowMs)) {
void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: "rate limited" });
const limitedId = newActivityId();
- const limitedTarget = activityTarget(args);
- void recordMcpActivity({ id: limitedId, actor, tool: name, state: "rate_limited", scope, workflowId, target: limitedTarget, detail: "rate limited" });
- await recordWorkflowStep(actor, workflowId, { id: limitedId, tool: name, state: "rate_limited", target: limitedTarget, args, ts: new Date().toISOString() });
+ const target = activityTarget(args);
+ void recordMcpActivity({ id: limitedId, actor, tool: name, state: "rate_limited", scope, ...initialFlow, target, detail: "rate limited" });
+ await recordWorkflowStep(actor, activeWorkflow?.id, { id: limitedId, tool: name, state: "rate_limited", target, args, ts: new Date().toISOString() });
return ok(id, {
content: [{ type: "text", text: `error: ${name} is rate limited (${tool.limit.max} per ${Math.round(tool.limit.windowMs / 1000)}s). Wait and retry.` }],
isError: true,
});
}
}
- // MCP tools call lib/host directly, so the ROUTE-level audit that covers
- // /api/v1 never runs for them. Without this, every write, delete and exec
- // that arrived over MCP would be missing from the one forensic trail there
- // is — and "revoke the token" is not much of a control if you cannot see
- // what it did first. Reads stay unaudited, same rule the routes follow.
+
const trail = tool.audit;
- const target = trail?.targetArg != null ? String(args[trail.targetArg] ?? "") : undefined;
+ const auditTarget = trail?.targetArg != null ? String(args[trail.targetArg] ?? "") : undefined;
const activityId = newActivityId();
- const activityStarted = Date.now();
- const activityTgt = activityTarget(args);
- void recordMcpActivity({ id: activityId, actor, tool: name, state: "started", scope, workflowId, target: activityTgt });
+ const startedAt = Date.now();
+ const target = activityTarget(args);
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "started", scope, ...initialFlow, target });
try {
- const result = await tool.run(args, { actor, scope, workflowId });
+ const result = await tool.run(args, { actor, scope, workflowId: activeWorkflow?.id });
if (trail) {
- // `ok: true` used to be unconditional here, which made the trail lie about
- // the one tool that matters most: runCommand REFUSES a destructive command
- // by RETURNING code 126, so a blocked `rm -rf /` was recorded as a
- // successful exec.run, and `exec.blocked` could never be emitted over MCP.
- const o = trail.outcome?.(result);
- void audit({ action: o?.action ?? trail.action, actor, target, ok: o?.ok ?? true, detail: o?.detail, meta: { via: "mcp", scope } });
+ const outcome = trail.outcome?.(result);
+ void audit({ action: outcome?.action ?? trail.action, actor, target: auditTarget, ok: outcome?.ok ?? true, detail: outcome?.detail, meta: { via: "mcp", scope } });
}
- const durationMs = Date.now() - activityStarted;
- void recordMcpActivity({ id: activityId, actor, tool: name, state: "completed", scope, workflowId, target: activityTgt, durationMs });
- await recordWorkflowStep(actor, workflowId, { id: activityId, tool: name, state: "completed", target: activityTgt, args, durationMs, ts: new Date().toISOString() });
+ const durationMs = Date.now() - startedAt;
+ const completedWorkflow = workflowFromResult(result) ?? activeWorkflow;
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "completed", scope, ...flowFields(completedWorkflow), target, durationMs });
+ await recordWorkflowStep(actor, completedWorkflow?.id, { id: activityId, tool: name, state: "completed", target, args, durationMs, ts: new Date().toISOString() });
if (isMcpDirectResult(result)) return ok(id, { content: result.content, ...(result.isError ? { isError: true } : {}) });
return ok(id, { content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }] });
- } catch (e) {
- // A handler failure stays INSIDE result with isError, never as a JSON-RPC
- // error object: ChatGPT hides protocol-level errors from the user, so the
- // person sees the model give up with no reason shown.
- const msg = e instanceof Error ? e.message : String(e);
- if (trail) void audit({ action: trail.action, actor, target, ok: false, detail: msg.slice(0, 200), meta: { via: "mcp", scope } });
- const durationMs = Date.now() - activityStarted;
- void recordMcpActivity({ id: activityId, actor, tool: name, state: "failed", scope, workflowId, target: activityTgt, durationMs, detail: msg.slice(0, 220) });
- await recordWorkflowStep(actor, workflowId, { id: activityId, tool: name, state: "failed", target: activityTgt, args, durationMs, ts: new Date().toISOString() });
- return ok(id, { content: [{ type: "text", text: "error: " + msg.slice(0, 500) }], isError: true });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (trail) void audit({ action: trail.action, actor, target: auditTarget, ok: false, detail: message.slice(0, 200), meta: { via: "mcp", scope } });
+ const durationMs = Date.now() - startedAt;
+ void recordMcpActivity({ id: activityId, actor, tool: name, state: "failed", scope, ...initialFlow, target, durationMs, detail: message.slice(0, 220) });
+ await recordWorkflowStep(actor, activeWorkflow?.id, { id: activityId, tool: name, state: "failed", target, args, durationMs, ts: new Date().toISOString() });
+ return ok(id, { content: [{ type: "text", text: "error: " + message.slice(0, 500) }], isError: true });
}
}
default:
diff --git a/lib/mcp/tools-learning.test.ts b/lib/mcp/tools-learning.test.ts
new file mode 100644
index 00000000..c66a51b2
--- /dev/null
+++ b/lib/mcp/tools-learning.test.ts
@@ -0,0 +1,74 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-workflow-bootstrap-"));
+const project = path.join(dir, "mso");
+await fs.mkdir(project);
+await fs.writeFile(path.join(project, "package.json"), JSON.stringify({
+ name: "mso", version: "9.9.9", scripts: { test: "vitest", build: "next build" },
+}));
+const previous = {
+ read: process.env.OS_FS_READ_ROOTS,
+ write: process.env.OS_FS_WRITE_ROOTS,
+ memory: process.env.OS_SKILL_MEMORY_STORE,
+};
+process.env.OS_FS_READ_ROOTS = dir;
+process.env.OS_FS_WRITE_ROOTS = dir;
+process.env.OS_SKILL_MEMORY_STORE = path.join(dir, "memory.json");
+const { resetSkillMemoryCache } = await import("@/lib/skills/memory");
+const { LEARNING_TOOLS } = await import("./tools-learning");
+
+describe("workflow_start bootstrap", () => {
+ afterAll(async () => {
+ if (previous.read === undefined) delete process.env.OS_FS_READ_ROOTS;
+ else process.env.OS_FS_READ_ROOTS = previous.read;
+ if (previous.write === undefined) delete process.env.OS_FS_WRITE_ROOTS;
+ else process.env.OS_FS_WRITE_ROOTS = previous.write;
+ if (previous.memory === undefined) delete process.env.OS_SKILL_MEMORY_STORE;
+ else process.env.OS_SKILL_MEMORY_STORE = previous.memory;
+ resetSkillMemoryCache();
+ await fs.rm(dir, { recursive: true, force: true });
+ });
+
+ it("returns project, toolset, skill search and an executable trace in one call", async () => {
+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start");
+ expect(start).toBeDefined();
+ const result = await start!.run({
+ intent: "inspect and safely update the MSO repository, then verify it",
+ project,
+ constraints: "no production downtime",
+ }, { actor: "mcp:test-bootstrap", scope: "write" }) as {
+ workflow: { project?: string };
+ bootstrap: {
+ ready: boolean;
+ project: { path: string; matchedBy: string };
+ repository: { package: { name?: string; version?: string; scripts: string[] }; git: { statusChecked: boolean } };
+ toolset: { toolCount: number; names: string[]; hash: string };
+ trace: string[];
+ };
+ search: { hits: Array<{ kind: string; name: string; trust?: string }> };
+ };
+
+ expect(result.workflow.project).toBe(project);
+ expect(result.bootstrap).toMatchObject({
+ ready: true,
+ project: { path: project, matchedBy: "path" },
+ repository: { package: { name: "mso", version: "9.9.9", scripts: ["test", "build"] }, git: { statusChecked: false } },
+ });
+ expect(result.bootstrap.toolset.toolCount).toBeGreaterThan(10);
+ expect(result.bootstrap.toolset.names).toContain("workflow_start");
+ expect(result.bootstrap.toolset.hash).toMatch(/^[a-f0-9]{16}$/);
+ expect(result.bootstrap.trace).toEqual(expect.arrayContaining([
+ expect.stringContaining("[MSO]"),
+ expect.stringContaining("[Project]"),
+ expect.stringContaining("[Plan]"),
+ ]));
+ expect(result.search.hits).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: "skill", name: "mso-repo-work", trust: "official" }),
+ ]));
+ });
+});
diff --git a/lib/mcp/tools-learning.ts b/lib/mcp/tools-learning.ts
index 66506ab7..b3a910ff 100644
--- a/lib/mcp/tools-learning.ts
+++ b/lib/mcp/tools-learning.ts
@@ -1,40 +1,74 @@
+import { inspectProject, resolveProjectHint } from "@/lib/host";
import { finishWorkflow, markRecipeUsed, startWorkflow } from "@/lib/skills/memory";
import { searchSkillMemory } from "@/lib/skills/search";
+import { allows } from "./scope";
import { type McpTool, str, opt, S } from "./tool-kit";
+import { toolsetInfo } from "./toolset";
-const toolDocs = async () => {
+const visibleTools = async (scope: "read" | "write" | "exec"): Promise<McpTool[]> => {
const { TOOLS } = await import("./tools");
- return TOOLS.map((t) => ({ name: t.name, description: t.description, scope: t.scope, inputSchema: t.inputSchema }));
+ return TOOLS.filter((tool) => allows(scope, tool.scope));
};
export const LEARNING_TOOLS: McpTool[] = [
{
name: "workflow_start",
description:
- "Start a learned workflow for a multi-step task. USE THIS before the first operational tool call when the task will likely need two or more calls. " +
- "MSO groups subsequent tool activity under this workflow and returns semantically similar skills, tools and the fastest successful recipe from prior runs.",
+ "The ONE startup call for a multi-step task. It starts the workflow, searches trusted skills and prior recipes, " +
+ "resolves project aliases, reports the current toolset/version, and inspects repository context when available. " +
+ "Do not call skills_search first for the same task; this already includes it.",
scope: "write",
annotations: { idempotentHint: false },
limit: { key: "workflow.memory", max: 30, windowMs: 60_000 },
audit: { action: "workflow.start" as const, targetArg: "project" },
inputSchema: S({
intent: { type: "string", description: "The user's task in one complete sentence." },
- project: { type: "string", description: "Optional project/workspace, e.g. projects/mso." },
+ project: { type: "string", description: "Optional project/workspace or alias, e.g. os-vps, mso, projects/mso." },
constraints: { type: "string", description: "Optional important constraints, such as no downtime or WebP only." },
}, ["intent"]),
run: async (a, context) => {
+ const intent = str(a, "intent");
+ const projectHint = opt(a, "project");
+ const project = projectHint ? await resolveProjectHint(projectHint).catch(() => null) : null;
+ const tools = await visibleTools(context.scope);
const started = await startWorkflow({
actor: context.actor,
- intent: str(a, "intent"),
- project: opt(a, "project"),
+ intent,
+ project: project?.path ?? projectHint,
constraints: opt(a, "constraints"),
});
- const search = await searchSkillMemory(str(a, "intent"), { topK: 8, toolDocs: await toolDocs() });
+ const search = await searchSkillMemory(intent, {
+ topK: 8,
+ toolDocs: tools.map((tool) => ({
+ name: tool.name, description: tool.description, scope: tool.scope, inputSchema: tool.inputSchema,
+ })),
+ });
if (search.recommendedRecipe) await markRecipeUsed(search.recommendedRecipe.id);
+ const repository = project
+ ? await inspectProject(project, { includeGitStatus: context.scope === "exec" }).catch(() => undefined)
+ : undefined;
+ const toolset = toolsetInfo(tools, context.scope);
return {
...started,
+ bootstrap: {
+ ready: true,
+ toolset,
+ project: project ?? (projectHint ? { hint: projectHint, matchedBy: "unresolved" } : undefined),
+ repository,
+ trace: [
+ `[MSO] connected · ${context.scope} scope · ${toolset.toolCount} tools · ${toolset.version}/${toolset.hash}`,
+ project ? `[Project] ${project.hint} → ${project.path} (${project.matchedBy})` : `[Project] ${projectHint ?? "not specified"}`,
+ "[Plan] inspect → change → test/build when needed → verify → workflow_finish",
+ ],
+ policy: {
+ simple: "Use bounded tools for one or two direct operations.",
+ repository: "For repository-wide search, git, tests, builds, or 3+ related checks, use one narrow exec_run batch when exec scope is available.",
+ progress: "Show only high-level feature/tool badges and outcomes; never private chain-of-thought.",
+ finish: "Call workflow_finish only after independent verification.",
+ },
+ },
search,
- instruction: "Reuse a relevant successful recipe when safe. After verification, call workflow_finish so MSO can keep the fastest successful path.",
+ instruction: "Use the returned project, trusted skill, and safe recipe directly. Verify the result, then call workflow_finish.",
};
},
},
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index 80c37f40..7e120ae3 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -1,4 +1,4 @@
-import { listDir, readFile, searchFs, usage, stats, processes, captureMsoScreen, createTempShare, tempShareUrl } from "@/lib/host";
+import { listDir, readFile, searchFs, usage, stats, processes, captureMsoScreen, createTempShare, tempShareUrl, sha256Text, utf8Bytes } from "@/lib/host";
import { camoufoxStatus } from "@/lib/camoufox/service";
import { listManagedApps, getManagedAppLogs } from "@/lib/managed-apps/manager";
import { searchSkillMemory } from "@/lib/skills/search";
@@ -24,12 +24,16 @@ export const READ_TOOLS: McpTool[] = [
{
name: "fs_read",
description:
- "Read a text file on the VPS and return its contents. For binary files this will be garbage — " +
+ "Read a text file on the VPS and return its contents plus UTF-8 byte count and SHA-256. " +
+ "Use that hash as fs_write.expected_sha256 to avoid overwriting a file changed since inspection. For binary files this will be garbage — " +
"check the extension from fs_list first. NOT for finding a file: use fs_search.",
scope: "read",
annotations: READ_ONLY,
inputSchema: S(PATH_P, ["path"]),
- run: async (a) => ({ path: a.path, content: await readFile(str(a, "path")) }),
+ run: async (a) => {
+ const content = await readFile(str(a, "path"));
+ return { path: a.path, content, bytes: utf8Bytes(content), sha256: sha256Text(content) };
+ },
},
{
name: "fs_search",
@@ -104,7 +108,7 @@ export const READ_TOOLS: McpTool[] = [
name: "skills_search",
description:
"Semantic search across trusted SKILL.md files, the live MCP tool catalog and learned successful workflows. " +
- "USE THIS FIRST for an unfamiliar or multi-step task so the fastest verified prior path is considered before rediscovering it. " +
+ "Use this alone for capability research or unfamiliar single-step work. For a multi-step task call workflow_start directly — it already performs this search and avoids a duplicate startup call. " +
"The embedding runs locally with no API cost; untrusted skill instructions are excluded unless explicitly requested.",
scope: "read",
annotations: READ_ONLY,
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index c8c53f1f..3759cc6d 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -1,4 +1,4 @@
-import { writeFile, makeDir, remove, move, copy, runCommand } from "@/lib/host";
+import { writeFileGuarded, makeDir, remove, move, copy, runCommand } from "@/lib/host";
import { setCamoufoxEnabled } from "@/lib/camoufox/service";
import { performManagedAppAction } from "@/lib/managed-apps/manager";
import { isManagedAppId } from "@/lib/managed-apps/catalog";
@@ -16,15 +16,21 @@ const MUTATE_TOOLS: McpTool[] = [
limit: { key: "fs.write", max: 120, windowMs: 60_000 },
audit: { action: "fs.write" as const, targetArg: "path" },
description:
- "Create or overwrite a text file on the VPS. Overwrites without warning — fs_read first if you need " +
- "the old contents. Bounded to OS_FS_WRITE_ROOTS (home + ~/projects by default).",
+ "Create or overwrite a text file on the VPS. Inspect with fs_read first and pass its SHA-256 as expected_sha256 " +
+ "to refuse a stale overwrite when another process changed the file. Omitting the hash keeps legacy overwrite behaviour. " +
+ "Bounded to OS_FS_WRITE_ROOTS (home + ~/projects by default).",
scope: "write",
annotations: { idempotentHint: true },
- inputSchema: S({ ...PATH_P, content: { type: "string" } }, ["path", "content"]),
- run: async (a) => {
- await writeFile(str(a, "path"), typeof a.content === "string" ? a.content : "");
- return { ok: true, path: a.path };
- },
+ inputSchema: S({
+ ...PATH_P,
+ content: { type: "string" },
+ expected_sha256: { type: "string", description: "Optional SHA-256 returned by fs_read; refuse if the current file no longer matches." },
+ }, ["path", "content"]),
+ run: async (a) => ({ ok: true, ...(await writeFileGuarded({
+ path: str(a, "path"),
+ content: typeof a.content === "string" ? a.content : "",
+ expectedSha256: opt(a, "expected_sha256"),
+ })) }),
},
{
name: "fs_mkdir",
diff --git a/lib/mcp/toolset.test.ts b/lib/mcp/toolset.test.ts
new file mode 100644
index 00000000..ac0d6918
--- /dev/null
+++ b/lib/mcp/toolset.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import type { McpTool } from "./tool-kit";
+import { toolsetInfo } from "./toolset";
+
+const tool = (name: string, description: string, scope: "read" | "write" | "exec" = "read"): McpTool => ({
+ name, description, scope, inputSchema: { type: "object", properties: {} }, run: async () => "ok",
+});
+
+describe("MCP toolset signature", () => {
+ it("is order-independent and reports exact scope counts", () => {
+ const first = toolsetInfo([tool("b", "two", "exec"), tool("a", "one")]);
+ const second = toolsetInfo([tool("a", "one"), tool("b", "two", "exec")]);
+ expect(first.hash).toBe(second.hash);
+ expect(first).toMatchObject({ toolCount: 2, byScope: { read: 1, write: 0, exec: 1 }, names: ["a", "b"] });
+ });
+
+ it("changes when a schema-relevant tool field changes", () => {
+ expect(toolsetInfo([tool("a", "one")]).hash).not.toBe(toolsetInfo([tool("a", "changed")]).hash);
+ });
+});
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
new file mode 100644
index 00000000..7f90b1f1
--- /dev/null
+++ b/lib/mcp/toolset.ts
@@ -0,0 +1,43 @@
+import { createHash } from "crypto";
+import type { Scope } from "./scope";
+import type { McpTool } from "./tool-kit";
+
+export const MCP_SERVER_VERSION = "1.2.0";
+export const MCP_TOOLSET_VERSION = "2026.08.19.1";
+export const MCP_TOOLSET_CHANGED_AT = "2026-08-19T13:55:00.000Z";
+
+export type McpToolsetInfo = {
+ serverVersion: string;
+ version: string;
+ hash: string;
+ changedAt: string;
+ scope?: Scope;
+ toolCount: number;
+ byScope: Record<Scope, number>;
+ names: string[];
+};
+
+export function toolsetInfo(tools: readonly McpTool[], scope?: Scope): McpToolsetInfo {
+ const rows = [...tools].sort((a, b) => a.name.localeCompare(b.name));
+ const hashInput = rows.map((tool) => ({
+ name: tool.name,
+ description: tool.description,
+ scope: tool.scope,
+ inputSchema: tool.inputSchema,
+ annotations: tool.annotations,
+ limit: tool.limit,
+ }));
+ const hash = createHash("sha256").update(JSON.stringify(hashInput)).digest("hex").slice(0, 16);
+ const byScope: Record<Scope, number> = { read: 0, write: 0, exec: 0 };
+ for (const tool of rows) byScope[tool.scope] += 1;
+ return {
+ serverVersion: MCP_SERVER_VERSION,
+ version: MCP_TOOLSET_VERSION,
+ hash,
+ changedAt: MCP_TOOLSET_CHANGED_AT,
+ ...(scope ? { scope } : {}),
+ toolCount: rows.length,
+ byScope,
+ names: rows.map((tool) => tool.name),
+ };
+}