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): complete Fresh 3 plugin contracts

Rahman0dc9830206ed
diff --git a/CLAUDE.md b/CLAUDE.md
index 1a2d275d..e7a70455 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -348,7 +348,7 @@ the real runtime and working analogue before changing a tool or skill contract.
it AND `tools/call` re-checks it — a client can call a name it was never shown.
- **Tool names are an MSO public API contract.** Keep global names MSO-owned and generic.
Project-owned MCP names are data behind `project_mcp_tools` / `project_mcp_call`; never copy them into the global catalog.
- <!-- mcp-toolset: server=1.8.0 version=2026.09.03.5 tools=85 read=41 write=25 exec=19 -->
+ <!-- mcp-toolset: server=1.8.1 version=2026.09.03.6 tools=85 read=41 write=25 exec=19 -->
The full MSO transport exposes **73 tools**: **72 model/operator tools** (34 read, 24 write, 14 exec) plus app-only `workflow_status`.
ChatGPT receives a deliberately smaller static profile; hidden full-catalog names are rejected at call time, not merely omitted from `tools/list`.
- Store is `~/.mso/mcp.json`, **sha256 only**, same atomic-write + fail-loud-on-corrupt
diff --git a/claude-skills/mso-camoufox/SKILL.md b/claude-skills/mso-camoufox/SKILL.md
index ac1816a9..7af48bd4 100644
--- a/claude-skills/mso-camoufox/SKILL.md
+++ b/claude-skills/mso-camoufox/SKILL.md
@@ -1,6 +1,6 @@
---
name: mso-camoufox
-description: Operate MSO's Camoufox browser safely: inspect status and power the session, while keeping VNC credentials, cookies, and logged-in profile data human-only.
+description: "Operate MSO's Camoufox browser safely: inspect status and power the session, while keeping VNC credentials, cookies, and logged-in profile data human-only."
metadata:
mso:
risk: high
diff --git a/claude-skills/mso-deploy/SKILL.md b/claude-skills/mso-deploy/SKILL.md
index 47b049cb..e5bddbbe 100644
--- a/claude-skills/mso-deploy/SKILL.md
+++ b/claude-skills/mso-deploy/SKILL.md
@@ -1,6 +1,6 @@
---
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.
+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
diff --git a/claude-skills/mso-list/SKILL.md b/claude-skills/mso-list/SKILL.md
index fd051beb..b3db9266 100644
--- a/claude-skills/mso-list/SKILL.md
+++ b/claude-skills/mso-list/SKILL.md
@@ -1,6 +1,6 @@
---
name: mso-list
-description: Audit MSO capabilities honestly: inventory every /api/v1 route, live-probe the safe core, report exact probe coverage, and distinguish PASS, FAIL, and UNPROBED.
+description: "Audit MSO capabilities honestly: inventory every /api/v1 route, live-probe the safe core, report exact probe coverage, and distinguish PASS, FAIL, and UNPROBED."
metadata:
mso:
risk: low
diff --git a/claude-skills/mso-repo-work/SKILL.md b/claude-skills/mso-repo-work/SKILL.md
index 669d867a..76a23451 100644
--- a/claude-skills/mso-repo-work/SKILL.md
+++ b/claude-skills/mso-repo-work/SKILL.md
@@ -1,6 +1,6 @@
---
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.
+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
diff --git a/claude-skills/mso-service-debug/SKILL.md b/claude-skills/mso-service-debug/SKILL.md
index 3ca515e4..48a6b9d7 100644
--- a/claude-skills/mso-service-debug/SKILL.md
+++ b/claude-skills/mso-service-debug/SKILL.md
@@ -1,6 +1,6 @@
---
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.
+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
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e8cdd023..b430f1de 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -160,7 +160,7 @@ park a visible Approve/Deny card. The complete semantic contract is
**MCP** is for external clients such as ChatGPT, Claude.ai and Cursor. Its catalog lives in
`lib/mcp/`; access is controlled by the OAuth token scope rather than Alfa approval cards.
-<!-- mcp-toolset: server=1.8.0 version=2026.09.03.5 tools=85 read=41 write=25 exec=19 -->
+<!-- mcp-toolset: server=1.8.1 version=2026.09.03.6 tools=85 read=41 write=25 exec=19 -->
The full transport exposes **73 tools**: **72 model/operator tools** (34 read, 24 write, 14 exec) plus app-only `workflow_status`. ChatGPT gets a compact client profile rather than the full set. Project function/MCP names remain data behind `project_capabilities`, `project_function_call`, `project_mcp_tools`, and `project_mcp_call`; they never rewrite the global tool prefix. `GET /mcp` reports both full and ChatGPT signatures.
See `docs/MCP.md` for protocol/security internals, `docs/A2A.md` for peer-agent delegation, and `docs/CHATGPT-PLUGIN.md` for the
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index dfd34d82..60c97f1e 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` complete Fresh 3 plugin contracts
- `mcp` maximize Fresh 3 operator capabilities
- `mcp` harden ChatGPT profile and project bridge
diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.md
index e688d4b1..a7795127 100644
--- a/docs/CHATGPT-PLUGIN.md
+++ b/docs/CHATGPT-PLUGIN.md
@@ -4,13 +4,13 @@
>
> ChatGPT's Developer Mode/App UI can change independently of MSO. Use the current OpenAI MCP/App documentation for exact menu labels, and use MSO Settings → MCP / `GET /mcp` for the live server/profile signatures.
-<!-- mcp-chatgpt-profile: server=1.8.0 version=2026.09.03.5 tools=61 read=32 write=17 exec=12 app-only=1 total=62 -->
+<!-- mcp-chatgpt-profile: server=1.8.1 version=2026.09.03.6 tools=61 read=32 write=17 exec=12 app-only=1 total=62 -->
-MSO server **1.8.0**, toolset **2026.09.03.5** exposes the full generic catalog for MCP clients, while a registered ChatGPT client receives **62 transport tools**: **61 model/operator tools** (32 read, 17 write, 12 exec) plus app-only `workflow_status`.
+MSO server **1.8.1**, toolset **2026.09.03.6** exposes the full generic catalog for MCP clients, while a registered ChatGPT client receives **62 transport tools**: **61 model/operator tools** (32 read, 17 write, 12 exec) plus app-only `workflow_status`.
Browser-hosted MCP probes from ChatGPT are allowed only when they target the configured public `OS_PUBLIC_ORIGIN`; arbitrary origins and ChatGPT-origin requests aimed at loopback remain denied. Additional trusted browser hosts can be added explicitly with comma-separated `OS_MCP_BROWSER_ORIGINS`. Public OAuth discovery and DCR responses carry CORS metadata; authenticated `/mcp` echoes only an approved exact origin.
-The compact descriptor regression currently measures **57,853 JSON bytes** for all 62 ChatGPT transport tool definitions (roughly 14.5k tokens at a 4-byte/token estimate), with the largest individual descriptor **2,504 bytes**. CI keeps the profile below 72 KiB and each descriptor below 8 KiB. Bytes are the deterministic contract; token estimates vary by tokenizer.
+The compact descriptor regression currently measures **64,180 JSON bytes** for all 62 ChatGPT transport tool definitions (roughly 16.0k tokens at a 4-byte/token estimate), with the largest individual descriptor **2,615 bytes**. CI keeps the profile below 72 KiB and each descriptor below 8 KiB. Bytes are the deterministic contract; token estimates vary by tokenizer.
## Why ChatGPT gets a compact profile
@@ -42,7 +42,7 @@ Every advertised MSO tool has:
- a stable machine `name` owned by MSO;
- a human-readable `title`;
- a concise action-oriented `description`;
-- bounded `inputSchema` (and `outputSchema` where structured output is used);
+- bounded `inputSchema` and an `outputSchema` for every ChatGPT action; UI/critical tools use typed schemas while dynamic tools share one exact `{ result }` envelope;
- explicit boolean `readOnlyHint`, `destructiveHint`, and `openWorldHint` annotations;
- optional `idempotentHint` where meaningful;
- matching top-level and `_meta.securitySchemes` OAuth metadata.
@@ -129,6 +129,14 @@ The restored Original MSO operator primitives (`sys_*`, `fs_usage` + full bounde
Project-owned MCP names and Convex's own dynamic schemas still load on demand through `project_mcp_tools` / `project_mcp_call` and `project_database_tools` / `project_database_call`. That is how MSO keeps a 61-action static model profile instead of copying every downstream provider/project action into ChatGPT.
+### Structured-result contract
+
+After the Fresh 3 rescan exposed `Output schema recommended` on non-UI actions, the ChatGPT profile now advertises an output schema on **all 62 transport actions** without duplicating dozens of provider/project result definitions. Tools with stable UI-critical shapes keep their explicit typed schemas. Every other ChatGPT action uses one exact outer `{ result: ... }` contract and returns the already-bounded JSON value inside `structuredContent.result`; its text `content` is a short acknowledgement so the same payload is not duplicated in the conversation transcript. Full/generic MCP clients keep the historical text-only contract unless a tool explicitly declares structured output. `screen_capture` keeps the image in MCP content and exposes only safe dimensions/URLs/expiry metadata in the structured envelope—never base64 image bytes.
+
+### Native MCP skill snapshot
+
+Fresh 3 also advertises the bounded `io.modelcontextprotocol/skills` extension. `skills/list`, `skills/get`, and `resources/read` publish a submission-time snapshot of exactly five general official MSO skills: `mso`, `mso-repo-work`, `mso-service-debug`, `mso-deploy`, and `mso-mcp-feature-engineering`. The manifest is generated from `claude-skills/`, includes complete resources plus `sha256:` digests, refuses symlinks/path normalization conflicts/oversize files, and never publishes operator, project, verified-third-party, or untrusted skill roots. The ordinary `skills_search/list/read` actions remain the live runtime catalog for the rest.
+
For the complete non-ChatGPT MSO catalog, scopes, limits, A2A, providers, Tool Forge and other generic capabilities, see [`MCP.md`](./MCP.md).
## Dynamic project capabilities without global project tools
diff --git a/docs/MCP.md b/docs/MCP.md
index 538a5fed..d624bd82 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -116,9 +116,9 @@ The catalog has a stable server version plus a schema-derived toolset signature.
Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.
-<!-- mcp-toolset: server=1.8.0 version=2026.09.03.5 tools=85 read=41 write=25 exec=19 -->
+<!-- mcp-toolset: server=1.8.1 version=2026.09.03.6 tools=85 read=41 write=25 exec=19 -->
-Current full transport catalog: **86 tools**, server `1.8.0` / toolset `2026.09.03.5`.
+Current full transport catalog: **86 tools**, server `1.8.1` / toolset `2026.09.03.6`.
The model/operator catalog is **85 tools** (41 read, 25 write, 19 exec); `workflow_status` is the one app-only MCP Apps bridge. ChatGPT receives a smaller client profile rather than this full set; see [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md).
`agent_memory_search` is the typed-memory retrieval surface. It resolves semantic/episodic/procedural claims at an optional point in time, returns confidence/provenance and competing effective claims, and can expose superseded/retracted history when explicitly requested. `agent_memory_remember` remains the write surface and now accepts typed metadata; raw ChatGPT conversation ids are never stored as provenance.
@@ -126,6 +126,8 @@ Session/memory tools add durable conversation context without creating dynamic p
### Advertised metadata and client profiles
+The ChatGPT client profile additionally supplies a DRY output contract for every scanned action. Stable UI/critical tools keep their explicit typed `outputSchema`; other ChatGPT actions use one exact `{ result }` envelope whose value is generated from the same bounded result text policy. This eliminates scanner `Output schema recommended` gaps without copying dozens of dynamic provider/project shapes or changing the generic MCP text contract. Direct binary output such as screenshots keeps binary bytes in MCP `content`, never in `structuredContent`.
+
`toolDescriptor()` is the SSOT normalization layer for every MCP host. It guarantees a human-readable `title`, complete `readOnlyHint` / `destructiveHint` / `openWorldHint` booleans, optional `idempotentHint`, and matching top-level plus `_meta.securitySchemes`. Individual tool declarations may override safety semantics; otherwise conservative MSO defaults are applied from scope/operation class.
The OAuth scope remains the permission boundary. A client profile may expose fewer MSO-owned generic names for compatibility/context budget, and the dispatcher rejects hidden names when called directly. ChatGPT is the first compact profile: it is derived from `CHATGPT_TOOL_NAMES`, independently hashed, and regression-tested for total/per-tool descriptor size. Full MCP clients keep the complete generic catalog.
@@ -387,6 +389,12 @@ Run `bun run bench:cognitive` for the reproducible provider-neutral routing/foot
Hermes is compared only where an equivalent offline `prompt-size` metric exists; OpenClaw is
reported but is not declared beaten on a non-comparable metric.
+## OpenAI/MCP static skill extension
+
+In addition to the live `skills_*` actions, MSO advertises `capabilities.extensions["io.modelcontextprotocol/skills"]` for ChatGPT/OpenAI plugin scans. The extension is intentionally **static and bounded**: it publishes at most five general official skills from `claude-skills/`, then serves the same complete entry through `skills/list` and `skills/get` and every declared `skill://mso/...` resource through `resources/read`. Each resource is read with `O_NOFOLLOW`, capped before allocation, path-normalized, included in the per-skill 100-file / 5 MiB budget, and hashed as `sha256:<hex>`.
+
+The published set is `mso`, `mso-repo-work`, `mso-service-debug`, `mso-deploy`, and `mso-mcp-feature-engineering`. This is deliberately separate from MSO's much larger live catalog: operator `~/.mso/skills`, per-project skills, local skills, and third-party/verified/untrusted roots can still be searched/read at runtime but never silently become plugin-submission instructions.
+
## Semantic skill search and learned workflows
MSO does not need to rediscover the same safe procedure on every conversation.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index a33bbae4..653f0d51 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,4 +1,5 @@
# mso — Progress Log
+- **Fresh 3 completion / scanner-clean contract (2026-09-03):** server `1.8.1` / toolset `2026.09.03.6` keeps the 62-action Fresh 3 surface unchanged while closing the post-refresh metadata gaps. Every ChatGPT action now advertises `outputSchema`; dynamic actions share one DRY bounded `{ result }` envelope instead of 57 duplicated hand schemas, keeping the profile at 64,180 bytes (~16.0k rough tokens). Four MCP Apps now declare the dedicated sibling widget origin `https://mso-ui.rahmanef.com` (Traefik config in `ops/traefik/mso-ui.yml`), and the OpenAI/MCP skills extension publishes five official, digest-verified `claude-skills/` snapshots through `skills/list`, `skills/get`, and `resources/read`. Generic MCP clients retain the prior text-only result behavior unless a tool already had explicit structured output.
- **Fresh 3 capability-max release (2026-09-03):** server `1.8.0` / toolset `2026.09.03.5` restores Original MSO bounded VPS/system/filesystem/app/browser/infra operations to the ChatGPT profile while preserving Fresh 3 workflow/session/Local Agent/read-pipeline/project-MCP orchestration. The ChatGPT transport profile is now 62 tools (61 model actions + app-only `workflow_status`) at 57,853 descriptor bytes (~14.5k rough tokens), while the full model/operator catalog grows to 85 tools. New Lovable-inspired surfaces add `project_get`, Git history/diff, `.mso/KNOWLEDGE.md`, safe connection inventory, private `project_agent_run`/`project_agent_status`, and MCP Apps project/diff/VPS cards. Convex is first-class through the project-installed official Convex MCP CLI with projectDir override stripping, cross-project selector refusal, dynamic schemas, and no automatic dangerous production flags.
- **MCP protocol-era correctness (2026-09-03):** server `1.7.3` stops claiming the stateless `2026-07-28` protocol while serving the legacy initialize/session wire shape. The supported ceiling is deliberately `2025-06-18` (matching the known-good CareerPack ChatGPT connector); a modern HTTP probe receives a 400 and can fall back to initialize. `server/discover` is no longer aliased to the legacy initialize payload. Browser CORS also permits `Mcp-Method`/`Mcp-Name` so a standards-aware probe can reach the server and receive the fallback signal. Toolset stays `2026.09.03.4`.
diff --git a/docs/integrations/CHATGPT-UI.md b/docs/integrations/CHATGPT-UI.md
index 065612d6..9b0e10a0 100644
--- a/docs/integrations/CHATGPT-UI.md
+++ b/docs/integrations/CHATGPT-UI.md
@@ -8,7 +8,7 @@ A normal tool result cannot create an inline application by returning arbitrary
1. `resources/list` / `resources/read` expose `ui://…` resources with `text/html;profile=mcp-app`.
2. Model-visible tools bind a resource with `_meta.ui.resourceUri` plus the OpenAI compatibility alias `_meta["openai/outputTemplate"]`.
-3. UI-capable tools declare `outputSchema` and return bounded `structuredContent`; ordinary `content` remains the model/client text fallback.
+3. Every ChatGPT action declares `outputSchema`. UI/critical tools use typed projections; other actions use the shared bounded `{ result }` structured envelope. Generic MCP clients keep their historical text fallback unless an explicit output schema exists.
4. Sandboxed widgets read `window.openai.toolOutput`, may call only explicitly app-visible MSO tools through `window.openai.callTool`, and use `window.openai.openExternal` for the full dashboard.
Official references:
@@ -65,7 +65,9 @@ Every entry tool also returns portable text/JSON for non-MCP-Apps clients.
## Dedicated UI origin
-For the current custom connector, MSO intentionally leaves `_meta.ui.domain` unset so ChatGPT uses its default sandbox origin. The main dashboard is not reused as widget origin. Before an app-directory submission, provision a dedicated reviewed HTTPS widget origin and add it to `_meta.ui.domain` (plus the compatibility alias required by the target client at that time).
+All four templates declare `_meta.ui.domain = https://mso-ui.rahmanef.com` and the ChatGPT compatibility alias `_meta["openai/widgetDomain"]` with the same origin. The sibling hostname is intentional: the cockpit may scope its session cookie to `mso.rahmanef.com`, while `mso-ui.rahmanef.com` is outside that cookie domain. The dedicated origin therefore satisfies the plugin UI identity requirement without reusing the authenticated dashboard origin.
+
+The reproducible Traefik route is stored in `ops/traefik/mso-ui.yml` and forwards only to the same local MSO service through the existing HTTPS/Let's Encrypt ingress. Widget CSP still allows no network/static-resource domains and only permits `Open in MSO` to redirect to `https://mso.rahmanef.com`.
## Deployment / refresh
@@ -74,8 +76,9 @@ After a UI/schema release:
1. run `bun run verify` and a production build;
2. deploy through the normal MSO release path;
3. refresh/re-scan the ChatGPT development app so `initialize`, `tools/list`, and `resources/list` are read again;
-4. verify each entry tool exposes `outputSchema` and `_meta.ui.resourceUri`;
+4. verify all 62 ChatGPT actions expose `outputSchema`; verify each UI entry tool also exposes `_meta.ui.resourceUri`;
5. verify each `resources/read` returns `text/html;profile=mcp-app`;
-6. verify refresh buttons work and `workflow_status` polling does not enter learned workflow steps.
+6. verify every UI resource reports `ui.domain=https://mso-ui.rahmanef.com`, refresh buttons work, and `workflow_status` polling does not enter learned workflow steps;
+7. verify `skills/list`, `skills/get`, and each declared `skill://` resource/digest before the final Scan Tools refresh.
If ChatGPT still renders text only after a verified deployment, treat a stale app/action snapshot as the first suspect before changing the server again.
diff --git a/lib/host/bounded-read.ts b/lib/host/bounded-read.ts
index 33573925..894593bc 100644
--- a/lib/host/bounded-read.ts
+++ b/lib/host/bounded-read.ts
@@ -28,7 +28,7 @@ export const BOUNDED_READ = {
projectMcpConfig: 256 * 1024,
} as const;
-export async function readBoundedRegularFile(file: string, maxBytes: number): Promise<string | null> {
+export async function readBoundedRegularBuffer(file: string, maxBytes: number): Promise<Buffer | null> {
let handle: Awaited<ReturnType<typeof fs.open>>;
try {
// O_NOFOLLOW: ELOOP if `file` itself is a symlink. Intermediate directories are
@@ -42,13 +42,18 @@ export async function readBoundedRegularFile(file: string, maxBytes: number): Pr
if (!stat.isFile()) return null;
if (stat.size > maxBytes) return null;
const size = Number(stat.size);
- if (size === 0) return "";
+ if (size === 0) return Buffer.alloc(0);
const buffer = Buffer.allocUnsafe(size);
const { bytesRead } = await handle.read(buffer, 0, size, 0);
- return buffer.subarray(0, bytesRead).toString("utf8");
+ return buffer.subarray(0, bytesRead);
} catch {
return null;
} finally {
await handle.close().catch(() => undefined);
}
}
+
+export async function readBoundedRegularFile(file: string, maxBytes: number): Promise<string | null> {
+ const buffer = await readBoundedRegularBuffer(file, maxBytes);
+ return buffer === null ? null : buffer.toString("utf8");
+}
diff --git a/lib/mcp/chatgpt-profile.test.ts b/lib/mcp/chatgpt-profile.test.ts
index a37a8b20..d19e005b 100644
--- a/lib/mcp/chatgpt-profile.test.ts
+++ b/lib/mcp/chatgpt-profile.test.ts
@@ -24,6 +24,7 @@ describe("ChatGPT compact MCP profile", () => {
expect(schemes?.[0]?.type, String(tool.name)).toBe("oauth2");
expect(Array.isArray(schemes?.[0]?.scopes), String(tool.name)).toBe(true);
expect((tool._meta as { securitySchemes?: unknown })?.securitySchemes, String(tool.name)).toEqual(schemes);
+ expect(tool.outputSchema, `${String(tool.name)}.outputSchema`).toBeDefined();
expect(Buffer.byteLength(JSON.stringify(tool)), String(tool.name)).toBeLessThan(8 * 1024);
}
diff --git a/lib/mcp/dispatch-tool-support.ts b/lib/mcp/dispatch-tool-support.ts
index 02befcc5..fe8178c3 100644
--- a/lib/mcp/dispatch-tool-support.ts
+++ b/lib/mcp/dispatch-tool-support.ts
@@ -4,6 +4,7 @@ import { isMcpDirectResult } from "./tool-kit";
import { boundedResultText } from "./result-budget";
import { TOOLS_BY_NAME } from "./tools";
import type { McpAgentContext } from "./dispatch-types";
+import type { McpToolProfile } from "./tool-contract";
export function sessionDetail(name: string, args: Record<string, unknown>, target?: string): string | undefined {
if (name === "workflow_start") {
@@ -43,14 +44,38 @@ export function workflowFromResult(result: unknown): ActiveWorkflow | null {
return typeof row.id === "string" && typeof row.intent === "string" ? row as ActiveWorkflow : null;
}
-export function structuredResult(toolName: string, result: unknown) {
+function boundedStructuredValue(result: unknown, policy?: { maxTextBytes?: number; overflowHint?: string }): unknown {
+ const text = boundedResultText(result, policy);
+ try { return JSON.parse(text); } catch { return text; }
+}
+
+export function structuredResult(toolName: string, result: unknown, profile: McpToolProfile = "full") {
const tool = TOOLS_BY_NAME.get(toolName);
- const content = [{ type: "text" as const, text: boundedResultText(result, tool?.result) }];
- const structured = tool?.toStructuredContent
- ? tool.toStructuredContent(result)
- : result !== null && typeof result === "object" && !Array.isArray(result)
- ? result as Record<string, unknown>
- : undefined;
- if (isMcpDirectResult(result)) return { content: result.content, ...(result.isError ? { isError: true } : {}) };
- return tool?.outputSchema && structured ? { structuredContent: structured, content } : { content };
+ if (isMcpDirectResult(result)) {
+ return {
+ content: result.content,
+ ...(profile === "chatgpt" && result.structuredContent ? { structuredContent: result.structuredContent } : {}),
+ ...(result.isError ? { isError: true } : {}),
+ };
+ }
+
+ const text = boundedResultText(result, tool?.result);
+ if (tool?.outputSchema) {
+ const structured = tool.toStructuredContent
+ ? tool.toStructuredContent(result)
+ : result !== null && typeof result === "object" && !Array.isArray(result)
+ ? result as Record<string, unknown>
+ : undefined;
+ return structured ? { structuredContent: structured, content: [{ type: "text" as const, text }] } : { content: [{ type: "text" as const, text }] };
+ }
+
+ if (profile === "chatgpt") {
+ return {
+ structuredContent: { result: boundedStructuredValue(result, tool?.result) },
+ // Do not duplicate the full JSON in ChatGPT's transcript: the structured
+ // result already contains it. Generic MCP clients keep the old text-only form.
+ content: [{ type: "text" as const, text: `Structured result returned by ${toolName}.` }],
+ };
+ }
+ return { content: [{ type: "text" as const, text }] };
}
diff --git a/lib/mcp/dispatch-tools.ts b/lib/mcp/dispatch-tools.ts
index ada32f10..b823ec30 100644
--- a/lib/mcp/dispatch-tools.ts
+++ b/lib/mcp/dispatch-tools.ts
@@ -99,7 +99,7 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st
}
if (mcpPresence)
await touchLocalAgentPresence(mcpPresence.principal, mcpPresence.sessionId, "idle", mcpPresence.instanceId).catch(() => undefined);
- return rpcOk(id, structuredResult(name, result));
+ return rpcOk(id, structuredResult(name, result, context?.toolProfile ?? "full"));
} catch (error) {
const message = error instanceof Error ? error.message : String(error), durationMs = Date.now() - startedAt;
if (trail) void audit({ action: trail.action, actor, target: auditTarget, ok: false, detail: message.slice(0, 200), meta: { via: "mcp", scope } });
diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.ts
index 9d7c6cbe..49119c78 100644
--- a/lib/mcp/dispatch-types.ts
+++ b/lib/mcp/dispatch-types.ts
@@ -10,6 +10,7 @@ export interface RpcRequest {
arguments?: Record<string, unknown>;
protocolVersion?: string;
uri?: string;
+ cursor?: string;
_meta?: Record<string, unknown>;
};
}
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
index a496e3ca..59384fbc 100644
--- a/lib/mcp/dispatch.ts
+++ b/lib/mcp/dispatch.ts
@@ -2,6 +2,7 @@ import type { Scope } from "./scope";
import { MCP_SERVER_VERSION, toolsetInfo } from "./toolset";
import { TOOLS } from "./tools";
import { listUiResources, readUiResource } from "./ui-resources";
+import { MCP_SKILLS_EXTENSION, getMcpSkill, listMcpSkills, readMcpSkillResource } from "./skills-extension";
import { dispatchToolCall } from "./dispatch-tools";
import { toolDescriptor, visibleToolsForProfile, type McpToolProfile } from "./tool-contract";
import { negotiateMcpProtocol } from "./protocol";
@@ -35,7 +36,7 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, ag
const tools = visibleTools(scope, profile), toolset = toolsetInfo(tools, scope, profile);
return rpcOk(id, {
protocolVersion: negotiateMcpProtocol(req.params?.protocolVersion),
- capabilities: { tools: { listChanged: false }, resources: { listChanged: false } },
+ capabilities: { tools: { listChanged: false }, resources: { listChanged: false }, extensions: { [MCP_SKILLS_EXTENSION]: {} } },
serverInfo: { name: "mso", version: MCP_SERVER_VERSION }, instructions: instructions(scope, profile),
_meta: { toolset, ...(agentContext?.sessionId ? { agentSessionId: agentContext.sessionId } : {}) },
});
@@ -52,8 +53,22 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, ag
const uri = String(req.params?.uri ?? "");
if (!uri) return rpcFail(id, -32602, "resources/read needs { uri }");
const resource = readUiResource(uri);
- if (!resource) return rpcFail(id, -32602, `unknown resource: ${uri}`);
- return rpcOk(id, { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: resource.text, _meta: resource._meta }] });
+ if (resource) return rpcOk(id, { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: resource.text, _meta: resource._meta }] });
+ try {
+ const skillResource = await readMcpSkillResource(uri);
+ if (skillResource) return rpcOk(id, { contents: [skillResource] });
+ } catch (error) { return rpcFail(id, -32602, error instanceof Error ? error.message : String(error)); }
+ return rpcFail(id, -32602, `unknown resource: ${uri}`);
+ }
+ case "skills/list": {
+ try { return rpcOk(id, await listMcpSkills(typeof req.params?.cursor === "string" ? req.params.cursor : undefined)); }
+ catch (error) { return rpcFail(id, -32602, error instanceof Error ? error.message : String(error)); }
+ }
+ case "skills/get": {
+ const uri = String(req.params?.uri ?? "");
+ if (!uri) return rpcFail(id, -32602, "skills/get needs { uri }");
+ try { return rpcOk(id, await getMcpSkill(uri)); }
+ catch (error) { return rpcFail(id, -32602, error instanceof Error ? error.message : String(error)); }
}
case "tools/call": return dispatchToolCall(req, scope, actor, agentContext);
default: return rpcFail(id, -32601, `unknown method: ${req.method}`);
diff --git a/lib/mcp/result-budget.ts b/lib/mcp/result-budget.ts
index 0328e120..b1477c85 100644
--- a/lib/mcp/result-budget.ts
+++ b/lib/mcp/result-budget.ts
@@ -36,8 +36,10 @@ export type McpResultBudget = {
*/
export function boundedResultText(result: unknown, policy?: McpResultBudget): string {
let raw: string;
- try { raw = typeof result === "string" ? result : JSON.stringify(result); }
- catch { raw = String(result); }
+ try {
+ const encoded = typeof result === "string" ? result : JSON.stringify(result);
+ raw = encoded === undefined ? "null" : encoded;
+ } catch { raw = String(result); }
const max = clampBudget(policy?.maxTextBytes);
const bytes = utf8Bytes(raw);
if (bytes <= max) return raw;
diff --git a/lib/mcp/skills-extension.test.ts b/lib/mcp/skills-extension.test.ts
new file mode 100644
index 00000000..f6894e8e
--- /dev/null
+++ b/lib/mcp/skills-extension.test.ts
@@ -0,0 +1,47 @@
+import { createHash } from "node:crypto";
+import { describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+const { dispatch } = await import("./dispatch");
+const { CHATGPT_PUBLISHED_SKILLS, MCP_SKILLS_EXTENSION } = await import("./skills-extension");
+
+describe("MCP Skills extension", () => {
+ it("advertises the skills extension and exactly five official MSO skills", async () => {
+ const initialized = await dispatch({ id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, "read", "skills-test");
+ expect(initialized.result).toMatchObject({ capabilities: { extensions: { [MCP_SKILLS_EXTENSION]: {} } } });
+ const listed = await dispatch({ id: 2, method: "skills/list", params: {} }, "read", "skills-test");
+ const skills = (listed.result as { skills: Array<{ uri: string; frontmatter: Record<string, unknown>; resources: Array<{ uri: string; digest: string }> }>; nextCursor?: string }).skills;
+ expect(skills).toHaveLength(5);
+ expect(skills.map((skill) => skill.frontmatter.name)).toEqual([...CHATGPT_PUBLISHED_SKILLS]);
+ expect((listed.result as { nextCursor?: string }).nextCursor).toBeUndefined();
+ for (const skill of skills) {
+ expect(skill.uri).toMatch(/^skill:\/\/mso\/[a-z0-9-]+\/SKILL\.md$/);
+ expect(skill.frontmatter.description).toEqual(expect.any(String));
+ expect(skill.resources.length).toBeGreaterThan(0);
+ expect(skill.resources[0].uri).toBe(skill.uri);
+ for (const resource of skill.resources) expect(resource.digest).toMatch(/^sha256:[a-f0-9]{64}$/);
+ }
+ });
+
+ it("returns exact entries and resources whose bytes match their digests", async () => {
+ const listed = await dispatch({ id: 3, method: "skills/list", params: {} }, "read", "skills-test");
+ const skill = (listed.result as { skills: Array<{ uri: string; resources: Array<{ uri: string; digest: string }> }> }).skills[0];
+ const got = await dispatch({ id: 4, method: "skills/get", params: { uri: skill.uri } }, "read", "skills-test");
+ expect((got.result as { skill: unknown }).skill).toEqual(skill);
+ for (const resource of skill.resources) {
+ const read = await dispatch({ id: 5, method: "resources/read", params: { uri: resource.uri } }, "read", "skills-test");
+ const content = (read.result as { contents: Array<{ uri: string; text?: string; blob?: string }> }).contents[0];
+ expect(content.uri).toBe(resource.uri);
+ const bytes = content.text !== undefined ? Buffer.from(content.text, "utf8") : Buffer.from(content.blob ?? "", "base64");
+ expect(`sha256:${createHash("sha256").update(bytes).digest("hex")}`).toBe(resource.digest);
+ }
+ });
+
+ it("fails closed for unpublished skills, unsafe resources and invented pagination", async () => {
+ const unpublished = await dispatch({ id: 6, method: "skills/get", params: { uri: "skill://mso/anti-ai-slop-product-ui/SKILL.md" } }, "read", "skills-test");
+ expect(unpublished.error).toMatchObject({ code: -32602 });
+ const unsafe = await dispatch({ id: 7, method: "resources/read", params: { uri: "skill://mso/mso/%2e%2e/package.json" } }, "read", "skills-test");
+ expect(unsafe.error).toMatchObject({ code: -32602 });
+ const cursor = await dispatch({ id: 8, method: "skills/list", params: { cursor: "invented" } }, "read", "skills-test");
+ expect(cursor.error).toMatchObject({ code: -32602 });
+ });
+});
diff --git a/lib/mcp/skills-extension.ts b/lib/mcp/skills-extension.ts
new file mode 100644
index 00000000..7df1f333
--- /dev/null
+++ b/lib/mcp/skills-extension.ts
@@ -0,0 +1,160 @@
+import { createHash } from "node:crypto";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { parse as parseYaml } from "yaml";
+import { readBoundedRegularBuffer } from "@/lib/host/bounded-read";
+
+export const MCP_SKILLS_EXTENSION = "io.modelcontextprotocol/skills";
+export const MCP_SKILL_SCHEME = "skill:";
+
+// OpenAI currently imports at most five skills. Keep this as a deliberately small
+// operator syllabus rather than exposing project/local/untrusted instructions.
+export const CHATGPT_PUBLISHED_SKILLS = [
+ "mso",
+ "mso-repo-work",
+ "mso-service-debug",
+ "mso-deploy",
+ "mso-mcp-feature-engineering",
+] as const;
+
+const SERVER_NAMESPACE = "mso";
+const MAX_SKILLS = 5;
+const MAX_FILES_PER_SKILL = 100;
+const MAX_SKILL_MD_BYTES = 256 * 1024;
+const MAX_SUPPORTING_FILE_BYTES = 1024 * 1024;
+const MAX_SKILL_TOTAL_BYTES = 5 * 1024 * 1024;
+const MAX_SCAN_ARCHIVE_BYTES = 8 * 1024 * 1024;
+const TEXT_EXTENSIONS = new Set([".md", ".txt", ".json", ".yaml", ".yml", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".sh", ".py", ".toml", ".ini", ".csv", ".html", ".css", ".xml"]);
+
+type SkillResource = { uri: string; digest: string };
+type SkillEntry = { uri: string; frontmatter: Record<string, unknown>; resources: SkillResource[] };
+type ReadSkillResource = { uri: string; mimeType: string; text?: string; blob?: string };
+type SkillFile = { relative: string; absolute: string; data: Buffer; uri: string; digest: string };
+type LoadedSkill = { name: string; entry: SkillEntry; files: SkillFile[] };
+
+function sha256(data: Buffer): string {
+ return `sha256:${createHash("sha256").update(data).digest("hex")}`;
+}
+
+function skillUri(name: string, relative: string): string {
+ return `skill://${SERVER_NAMESPACE}/${name}/${relative.split(path.sep).map(encodeURIComponent).join("/")}`;
+}
+
+function safeRelative(value: string): boolean {
+ const normalized = path.posix.normalize(value.replaceAll("\\", "/"));
+ return Boolean(value) && normalized === value.replaceAll("\\", "/") && !normalized.startsWith("../") && normalized !== ".." && !normalized.startsWith("/");
+}
+
+function parseFrontmatter(md: string, expectedName: string): Record<string, unknown> {
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(md);
+ if (!match) throw new Error(`published skill ${expectedName} is missing YAML frontmatter`);
+ const parsed = parseYaml(match[1]);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`published skill ${expectedName} frontmatter must be an object`);
+ const frontmatter = parsed as Record<string, unknown>;
+ if (frontmatter.name !== expectedName) throw new Error(`published skill directory/name mismatch: ${expectedName}`);
+ if (typeof frontmatter.description !== "string" || !frontmatter.description.trim()) throw new Error(`published skill ${expectedName} needs description frontmatter`);
+ return frontmatter;
+}
+
+function mimeType(relative: string): string {
+ const ext = path.extname(relative).toLowerCase();
+ if (ext === ".json") return "application/json; charset=utf-8";
+ if (ext === ".html") return "text/html; charset=utf-8";
+ if (ext === ".css") return "text/css; charset=utf-8";
+ if (ext === ".js" || ext === ".mjs" || ext === ".cjs") return "text/javascript; charset=utf-8";
+ if (ext === ".yaml" || ext === ".yml") return "application/yaml; charset=utf-8";
+ if (TEXT_EXTENSIONS.has(ext) || path.basename(relative) === "SKILL.md") return "text/plain; charset=utf-8";
+ return "application/octet-stream";
+}
+
+function shouldReturnText(relative: string, data: Buffer): boolean {
+ if (path.basename(relative) === "SKILL.md" || TEXT_EXTENSIONS.has(path.extname(relative).toLowerCase())) return !data.includes(0);
+ return false;
+}
+
+async function skillRoot(): Promise<string> {
+ return fs.realpath(path.join(process.cwd(), "claude-skills"));
+}
+
+async function collectFiles(root: string, name: string): Promise<SkillFile[]> {
+ const dir = path.join(root, name);
+ const canonical = await fs.realpath(dir).catch(() => "");
+ if (!canonical || path.dirname(canonical) !== root || path.basename(canonical) !== name) throw new Error(`published skill ${name} is not a direct regular directory`);
+ const rootStat = await fs.lstat(dir);
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error(`published skill ${name} directory must not be a symlink`);
+
+ const files: SkillFile[] = [];
+ const queue: Array<{ absolute: string; relative: string }> = [{ absolute: dir, relative: "" }];
+ let totalBytes = 0;
+ while (queue.length) {
+ const current = queue.shift()!;
+ const entries = await fs.readdir(current.absolute, { withFileTypes: true });
+ entries.sort((a, b) => a.name.localeCompare(b.name));
+ for (const entry of entries) {
+ if (entry.isSymbolicLink()) throw new Error(`published skill ${name} contains symlink ${entry.name}`);
+ const relative = current.relative ? `${current.relative}/${entry.name}` : entry.name;
+ if (!safeRelative(relative)) throw new Error(`unsafe published skill path: ${relative}`);
+ const absolute = path.join(current.absolute, entry.name);
+ if (entry.isDirectory()) { queue.push({ absolute, relative }); continue; }
+ if (!entry.isFile()) throw new Error(`published skill ${name} contains unsupported filesystem entry ${relative}`);
+ if (files.length >= MAX_FILES_PER_SKILL) throw new Error(`published skill ${name} exceeds ${MAX_FILES_PER_SKILL} files`);
+ const max = relative === "SKILL.md" ? MAX_SKILL_MD_BYTES : MAX_SUPPORTING_FILE_BYTES;
+ const data = await readBoundedRegularBuffer(absolute, max);
+ if (!data) throw new Error(`published skill resource ${relative} is unreadable or exceeds its size limit`);
+ totalBytes += data.length;
+ if (totalBytes > MAX_SKILL_TOTAL_BYTES) throw new Error(`published skill ${name} exceeds ${MAX_SKILL_TOTAL_BYTES} total bytes`);
+ files.push({ relative, absolute, data, uri: skillUri(name, relative), digest: sha256(data) });
+ }
+ }
+ const skillMd = files.find((file) => file.relative === "SKILL.md");
+ if (!skillMd) throw new Error(`published skill ${name} is missing SKILL.md`);
+ return [skillMd, ...files.filter((file) => file !== skillMd).sort((a, b) => a.relative.localeCompare(b.relative))];
+}
+
+async function loadSkill(name: string): Promise<LoadedSkill> {
+ if (!(CHATGPT_PUBLISHED_SKILLS as readonly string[]).includes(name)) throw new Error(`unknown published skill: ${name}`);
+ const root = await skillRoot();
+ const files = await collectFiles(root, name);
+ const skillMd = files[0];
+ const frontmatter = parseFrontmatter(skillMd.data.toString("utf8"), name);
+ return { name, files, entry: { uri: skillMd.uri, frontmatter, resources: files.map(({ uri, digest }) => ({ uri, digest })) } };
+}
+
+export async function listMcpSkills(cursor?: string): Promise<{ skills: SkillEntry[]; nextCursor?: string }> {
+ if (cursor) throw new Error("MSO publishes one bounded skills page; nextCursor is never issued");
+ const loaded = await Promise.all(CHATGPT_PUBLISHED_SKILLS.slice(0, MAX_SKILLS).map(loadSkill));
+ const total = loaded.reduce((sum, skill) => sum + skill.files.reduce((bytes, file) => bytes + file.data.length, 0), 0);
+ if (total > MAX_SCAN_ARCHIVE_BYTES) throw new Error(`published skill snapshot exceeds ${MAX_SCAN_ARCHIVE_BYTES} bytes`);
+ return { skills: loaded.map((skill) => skill.entry) };
+}
+
+export async function getMcpSkill(uri: string): Promise<{ skill: SkillEntry }> {
+ const parsed = parseSkillUri(uri);
+ if (parsed.relative !== "SKILL.md") throw new Error("skills/get requires a published SKILL.md URI");
+ const skill = await loadSkill(parsed.name);
+ if (skill.entry.uri !== uri) throw new Error("skill URI normalization mismatch");
+ return { skill: skill.entry };
+}
+
+function parseSkillUri(uri: string): { name: string; relative: string } {
+ let parsed: URL;
+ try { parsed = new URL(uri); } catch { throw new Error("invalid skill URI"); }
+ if (parsed.protocol !== MCP_SKILL_SCHEME || parsed.hostname !== SERVER_NAMESPACE || parsed.search || parsed.hash || parsed.username || parsed.password || parsed.port) throw new Error("invalid MSO skill URI");
+ const parts = parsed.pathname.split("/").filter(Boolean).map((part) => decodeURIComponent(part));
+ const [name, ...rest] = parts;
+ const relative = rest.join("/");
+ if (!name || !safeRelative(relative) || !(CHATGPT_PUBLISHED_SKILLS as readonly string[]).includes(name)) throw new Error("unknown or unsafe MSO skill URI");
+ return { name, relative };
+}
+
+export async function readMcpSkillResource(uri: string): Promise<ReadSkillResource | undefined> {
+ if (!uri.startsWith(`${MCP_SKILL_SCHEME}//${SERVER_NAMESPACE}/`)) return undefined;
+ const { name, relative } = parseSkillUri(uri);
+ const skill = await loadSkill(name);
+ const file = skill.files.find((candidate) => candidate.relative === relative && candidate.uri === uri);
+ if (!file) throw new Error(`unknown skill resource: ${uri}`);
+ const type = mimeType(relative);
+ return shouldReturnText(relative, file.data)
+ ? { uri, mimeType: type, text: file.data.toString("utf8") }
+ : { uri, mimeType: type, blob: file.data.toString("base64") };
+}
diff --git a/lib/mcp/structured-result.test.ts b/lib/mcp/structured-result.test.ts
new file mode 100644
index 00000000..39d87432
--- /dev/null
+++ b/lib/mcp/structured-result.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+const { structuredResult } = await import("./dispatch-tool-support");
+const { mcpDirect } = await import("./tool-kit");
+
+describe("profile-aware MCP structured results", () => {
+ it("wraps dynamic ChatGPT results once while preserving generic MCP text", () => {
+ const raw = { entries: [{ name: "a", type: "file" }] };
+ const chat = structuredResult("fs_list", raw, "chatgpt") as { structuredContent?: unknown; content: Array<{ text: string }> };
+ expect(chat.structuredContent).toEqual({ result: raw });
+ expect(chat.content[0].text).toBe("Structured result returned by fs_list.");
+ const full = structuredResult("fs_list", raw, "full") as { structuredContent?: unknown; content: Array<{ text: string }> };
+ expect(full.structuredContent).toBeUndefined();
+ expect(JSON.parse(full.content[0].text)).toEqual(raw);
+ });
+
+ it("normalizes undefined handler output to JSON null", () => {
+ const chat = structuredResult("fs_list", undefined, "chatgpt") as { structuredContent?: unknown };
+ expect(chat.structuredContent).toEqual({ result: null });
+ const full = structuredResult("fs_list", undefined, "full") as { content: Array<{ text: string }> };
+ expect(full.content[0].text).toBe("null");
+ });
+
+ it("keeps direct binary content outside structuredContent", () => {
+ const direct = mcpDirect([{ type: "image", data: "base64-image-data", mimeType: "image/png" }], false, { result: { width: 10, height: 20 } });
+ const chat = structuredResult("screen_capture", direct, "chatgpt") as { structuredContent?: unknown; content: Array<Record<string, unknown>> };
+ expect(chat.structuredContent).toEqual({ result: { width: 10, height: 20 } });
+ expect(JSON.stringify(chat.structuredContent)).not.toContain("base64-image-data");
+ expect(chat.content[0]).toMatchObject({ type: "image", data: "base64-image-data" });
+ });
+});
diff --git a/lib/mcp/tool-contract.test.ts b/lib/mcp/tool-contract.test.ts
index b4d457d1..be8058c7 100644
--- a/lib/mcp/tool-contract.test.ts
+++ b/lib/mcp/tool-contract.test.ts
@@ -22,4 +22,12 @@ describe("MCP advertised tool contract", () => {
expect(names).toContain("project_mcp_call");
expect(names.some((name) => name === "private_echo" || name.startsWith("project_fixture_"))).toBe(false);
});
+
+ it("adds the generic output envelope only to the compact ChatGPT profile", () => {
+ const fileList = TOOLS.find((tool) => tool.name === "fs_list");
+ expect(fileList).toBeDefined();
+ expect(toolDescriptor(fileList!, "full")).not.toHaveProperty("outputSchema");
+ expect(toolDescriptor(fileList!, "chatgpt").outputSchema).toEqual({ type: "object", properties: { result: {} }, required: ["result"], additionalProperties: false });
+ });
+
});
diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.ts
index 2550d9fe..fe5c9197 100644
--- a/lib/mcp/tool-contract.ts
+++ b/lib/mcp/tool-contract.ts
@@ -10,6 +10,26 @@ export type McpToolAnnotations = {
};
export type McpSecurityScheme = { type: "oauth2"; scopes: string[] } | { type: "noauth" };
+/**
+ * ChatGPT's scanner recommends output schemas for every tool that returns
+ * structured data. Most MSO tools intentionally keep provider/project-specific
+ * result shapes dynamic, so duplicating dozens of hand-maintained schemas would
+ * create drift. The compact profile therefore uses one exact outer envelope for
+ * tools without a richer explicit contract. `result` is the bounded JSON value
+ * already produced by the tool. Full/generic MCP clients keep the historical
+ * descriptor unless a tool declares its own outputSchema.
+ */
+export const CHATGPT_RESULT_OUTPUT_SCHEMA = {
+ type: "object",
+ properties: { result: {} },
+ required: ["result"],
+ additionalProperties: false,
+} as const;
+
+export function outputSchemaForProfile(tool: McpTool, profile: McpToolProfile = "full"): Record<string, unknown> | undefined {
+ return tool.outputSchema ?? (profile === "chatgpt" ? CHATGPT_RESULT_OUTPUT_SCHEMA : undefined);
+}
+
// ChatGPT scans a frozen descriptor snapshot. Keep that public snapshot deliberately
// small; every name here is an MSO-owned generic primitive. Project-owned MCP tool
// names are discovered/called dynamically through project_mcp_* and NEVER appended
@@ -117,12 +137,13 @@ export function toolDescriptor(tool: McpTool, profile: McpToolProfile = "full")
const securitySchemes = toolSecuritySchemes(tool);
const meta = { ...(tool.meta ?? {}), securitySchemes };
const compact = profile === "chatgpt";
+ const outputSchema = outputSchemaForProfile(tool, profile);
return {
name: tool.name,
title: tool.title ?? toolTitle(tool.name),
description: compact ? compactText(tool.chatgptDescription ?? tool.description) : tool.description,
inputSchema: compact ? compactSchema(tool.inputSchema) : tool.inputSchema,
- ...(tool.outputSchema ? { outputSchema: compact ? compactSchema(tool.outputSchema) : tool.outputSchema } : {}),
+ ...(outputSchema ? { outputSchema: compact ? compactSchema(outputSchema) : outputSchema } : {}),
securitySchemes,
annotations: completeToolAnnotations(tool),
_meta: meta,
diff --git a/lib/mcp/tool-kit.ts b/lib/mcp/tool-kit.ts
index 474d870a..f254d15e 100644
--- a/lib/mcp/tool-kit.ts
+++ b/lib/mcp/tool-kit.ts
@@ -17,10 +17,17 @@ export interface McpDirectResult {
__mcpDirect: true;
content: McpContent[];
isError?: boolean;
+ /** Optional safe structured projection for clients that advertise outputSchema.
+ * Never put binary/base64 payloads or secrets here. */
+ structuredContent?: Record<string, unknown>;
}
-export function mcpDirect(content: McpContent[], isError = false): McpDirectResult {
- return { __mcpDirect: true, content, ...(isError ? { isError: true } : {}) };
+export function mcpDirect(
+ content: McpContent[],
+ isError = false,
+ structuredContent?: Record<string, unknown>,
+): McpDirectResult {
+ return { __mcpDirect: true, content, ...(isError ? { isError: true } : {}), ...(structuredContent ? { structuredContent } : {}) };
}
export function isMcpDirectResult(value: unknown): value is McpDirectResult {
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index 5aba3c48..fd0ecbd1 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -175,7 +175,9 @@ export const READ_TOOLS: McpTool[] = [
`Direct download: ${downloadUrl}\n` +
`Expires ${new Date(share.expiresAt).toISOString()} · ${share.downloadsLeft} authenticated downloads`,
},
- ]);
+ ], false, {
+ result: { shell: shot.shell, width: shot.width, height: shot.height, mimeType: shot.mimeType, previewUrl, downloadUrl, expiresAt: share.expiresAt, downloadsLeft: share.downloadsLeft },
+ });
},
},
{
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 1366cc6a..14cb7bbf 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -3,9 +3,9 @@ import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
import { toolDescriptor, type McpToolProfile } from "./tool-contract";
-export const MCP_SERVER_VERSION = "1.8.0";
-export const MCP_TOOLSET_VERSION = "2026.09.03.5";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-03T13:14:26Z";
+export const MCP_SERVER_VERSION = "1.8.1";
+export const MCP_TOOLSET_VERSION = "2026.09.03.6";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-03T14:04:10Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/mcp/ui-config.ts b/lib/mcp/ui-config.ts
new file mode 100644
index 00000000..2c3ee972
--- /dev/null
+++ b/lib/mcp/ui-config.ts
@@ -0,0 +1,14 @@
+export const MSO_ORIGIN = "https://mso.rahmanef.com";
+// Dedicated sibling origin for ChatGPT MCP Apps. It intentionally does NOT sit
+// below mso.rahmanef.com, whose session cookie may be scoped to that hostname.
+export const MCP_UI_DOMAIN = "https://mso-ui.rahmanef.com";
+
+export function widgetResourceMeta(description: string): Record<string, unknown> {
+ return {
+ ui: { domain: MCP_UI_DOMAIN, prefersBorder: true, csp: { connectDomains: [], resourceDomains: [] } },
+ "openai/widgetDescription": description,
+ "openai/widgetPrefersBorder": true,
+ "openai/widgetDomain": MCP_UI_DOMAIN,
+ "openai/widgetCSP": { connect_domains: [], resource_domains: [], redirect_domains: [MSO_ORIGIN] },
+ };
+}
diff --git a/lib/mcp/ui-operator-resources.ts b/lib/mcp/ui-operator-resources.ts
index 8e1ab44c..07c02220 100644
--- a/lib/mcp/ui-operator-resources.ts
+++ b/lib/mcp/ui-operator-resources.ts
@@ -1,8 +1,9 @@
+import { MSO_ORIGIN, widgetResourceMeta } from "./ui-config";
+
export const PROJECT_STATUS_URI = "ui://mso/project-status-v1.html";
export const DIFF_VIEW_URI = "ui://mso/project-diff-v1.html";
export const VPS_STATUS_URI = "ui://mso/vps-status-v1.html";
-const ORIGIN = "https://mso.rahmanef.com";
const MIME = "text/html;profile=mcp-app";
function shell(title: string, body: string, script: string) {
@@ -12,7 +13,7 @@ function shell(title: string, body: string, script: string) {
}
const sharedScript = String.raw`
-const MSO_URL="https://mso.rahmanef.com";const $=id=>document.getElementById(id);let last=null;
+const MSO_URL="${MSO_ORIGIN}";const $=id=>document.getElementById(id);let last=null;
const txt=(v,f="—")=>v===undefined||v===null||v===""?f:String(v);const esc=v=>txt(v);
function output(){return window.openai&&window.openai.toolOutput?window.openai.toolOutput:null}
async function openMso(){if(window.openai&&typeof window.openai.openExternal==="function")await window.openai.openExternal({href:MSO_URL,redirectUrl:false});else window.open(MSO_URL,"_blank","noopener,noreferrer")}
@@ -37,12 +38,7 @@ $("refresh").addEventListener("click",async()=>{if(!window.openai||typeof window
`;
function meta(description: string) {
- return {
- ui: { prefersBorder: true, csp: { connectDomains: [], resourceDomains: [] } },
- "openai/widgetDescription": description,
- "openai/widgetPrefersBorder": true,
- "openai/widgetCSP": { connect_domains: [], resource_domains: [], redirect_domains: [ORIGIN] },
- };
+ return widgetResourceMeta(description);
}
export const OPERATOR_UI_RESOURCES = [
diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.ts
index 1ebd8b5d..bd1715b1 100644
--- a/lib/mcp/ui-resources.test.ts
+++ b/lib/mcp/ui-resources.test.ts
@@ -4,6 +4,7 @@ vi.mock("server-only", () => ({}));
const { dispatch } = await import("./dispatch");
const { MCP_APP_MIME_TYPE, WORKFLOW_PROGRESS_URI, PROJECT_STATUS_URI, DIFF_VIEW_URI, VPS_STATUS_URI } = await import("./ui-resources");
+const { MCP_UI_DOMAIN } = await import("./ui-config");
const { activeWorkflowForActor } = await import("@/lib/skills/memory");
const call = (name: string, args: Record<string, unknown> = {}) =>
@@ -62,7 +63,8 @@ describe("MCP Apps workflow progress UI", () => {
expect(content.text).toContain("Open in MSO");
expect(content.text).not.toContain("fetch(");
expect(content._meta).toMatchObject({
- ui: { prefersBorder: true },
+ ui: { domain: MCP_UI_DOMAIN, prefersBorder: true },
+ "openai/widgetDomain": MCP_UI_DOMAIN,
"openai/widgetPrefersBorder": true,
});
});
@@ -125,7 +127,7 @@ describe("MCP Apps workflow progress UI", () => {
expect(content.mimeType).toBe(MCP_APP_MIME_TYPE);
expect(content.text).toContain(marker);
expect(content.text).not.toContain("fetch(");
- expect(content._meta).toMatchObject({ ui: { prefersBorder: true }, "openai/widgetPrefersBorder": true });
+ expect(content._meta).toMatchObject({ ui: { domain: MCP_UI_DOMAIN, prefersBorder: true }, "openai/widgetDomain": MCP_UI_DOMAIN, "openai/widgetPrefersBorder": true });
}
});
it("rejects unknown UI resource URIs", async () => {
diff --git a/lib/mcp/ui-resources.ts b/lib/mcp/ui-resources.ts
index d3a4d533..0a72335a 100644
--- a/lib/mcp/ui-resources.ts
+++ b/lib/mcp/ui-resources.ts
@@ -1,8 +1,8 @@
import { OPERATOR_UI_RESOURCES } from "./ui-operator-resources";
+import { MSO_ORIGIN, widgetResourceMeta } from "./ui-config";
export { PROJECT_STATUS_URI, DIFF_VIEW_URI, VPS_STATUS_URI } from "./ui-operator-resources";
export const WORKFLOW_PROGRESS_URI = "ui://mso/workflow-progress-v1.html";
export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
-const MSO_ORIGIN = "https://mso.rahmanef.com";
const workflowProgressHtml = String.raw`<main class="mso-workflow" aria-live="polite">
<style>
@@ -216,19 +216,7 @@ export type McpUiResource = {
};
function workflowResourceMeta(): Record<string, unknown> {
- return {
- ui: {
- prefersBorder: true,
- csp: { connectDomains: [], resourceDomains: [] },
- },
- "openai/widgetDescription": "Authoritative MSO workflow progress card. It shows only high-level workflow state and recent tool outcomes; do not repeat the card contents verbatim.",
- "openai/widgetPrefersBorder": true,
- "openai/widgetCSP": {
- connect_domains: [],
- resource_domains: [],
- redirect_domains: [MSO_ORIGIN],
- },
- };
+ return widgetResourceMeta("Authoritative MSO workflow progress card. It shows only high-level workflow state and recent tool outcomes; do not repeat the card contents verbatim.");
}
const RESOURCES: readonly McpUiResource[] = [
diff --git a/ops/traefik/mso-ui.yml b/ops/traefik/mso-ui.yml
new file mode 100644
index 00000000..f4b60e43
--- /dev/null
+++ b/ops/traefik/mso-ui.yml
@@ -0,0 +1,26 @@
+# Dedicated MCP Apps sandbox origin for ChatGPT/OpenAI plugin UI.
+# This hostname is deliberately a sibling of mso.rahmanef.com so the cockpit's
+# OS_SESSION_COOKIE_DOMAIN=mso.rahmanef.com cookie is not sent to the widget origin.
+http:
+ routers:
+ mso-ui-router:
+ rule: Host(`mso-ui.rahmanef.com`)
+ service: mso-ui-service
+ middlewares:
+ - redirect-to-https
+ entryPoints:
+ - web
+ mso-ui-router-websecure:
+ rule: Host(`mso-ui.rahmanef.com`)
+ service: mso-ui-service
+ middlewares: []
+ entryPoints:
+ - websecure
+ tls:
+ certResolver: letsencrypt
+ services:
+ mso-ui-service:
+ loadBalancer:
+ servers:
+ - url: http://172.17.0.1:4005
+ passHostHeader: true