Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(mcp): harden ChatGPT profile and project bridge
Rahmanf5e440b4c518
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0fc29a4b..d20a804f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -89,7 +89,7 @@ Deleted 2026-07-28 as dead: `SHELL-INTEGRATION-PLAN.md` and `SYNC-PLAN.md` (bothsibling repos that do not exist on this machine), `browser-agent-plan.md` (the retiredPlaywright sidecar), `SIXFIX-PLAN.md` (a finished dated fix list). Nothing linked to anyof them. Deleted 2026-07-30 in the same spirit: `PLAN.md` (the "master plan" — every-section contradicted by shipped code, and its one unique asset, a Control-Room-vs-MSO+section contradicted by shipped code, and its one unique asset, a legacy-dashboard-vs-MSOtable, is descriptive rather than decision-carrying) and `MULTISHELL-PLAN.md` (its siblingrepo is gone, all six phases are checked off, and PROGRESS.md:574 reverses its one uniquedecision). Both recoverable with `git show bccd0b1:docs/<name>`. Deleted 2026-08-10@@ -346,17 +346,11 @@ the real runtime and working analogue before changing a tool or skill contract.`OS_MCP_MAX_SCOPE`. The default ceiling is `exec`, and consent preselects the highestpermitted tier; set the env to `read` or `write` to opt down. `tools/list` filters byit 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 historically pinned a subset of the MCP names as- literal `x-upstream` strings.- <!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->- MSO currently exposes **71 transport tools**: **70 model/operator tools** (34 read, 24 write,- 12 exec) plus the app-only `workflow_status` bridge; `GET /mcp` plus `_meta.toolset` expose- the current version/hash/name manifest.- Treat the gateway mapping as a separate cross-repo contract and verify it before renaming. 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.+- **Tool names are an MSO public API contract.** Keep global names MSO-owned and generic.+ Project-owned MCP names are data behind `project_mcp_tools` / `project_mcp_call`; never copy them into the global catalog.+ <!-- mcp-toolset: server=1.7.0 version=2026.09.03.3 tools=72 read=34 write=24 exec=14 -->+ 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-corruptrule as `lib/auth/device-store.ts`. Codes are single-use, 60 s, deleted BEFORE thetoken is minted. `browser_status` must never return the VNC password — that profilediff --git a/README.md b/README.mdindex eb16f417..de758875 100644--- a/README.md+++ b/README.md@@ -75,7 +75,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).-- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — Settings → MCP now provides client-specific numbered setup, copy-ready remote configs, live MCP/OAuth discovery checks, tunnel/domain guidance, and the same OAuth 2.1 + PKCE `read → write → exec` permission ladder enforced server-side. See the [ChatGPT Plugin / custom MCP app guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).+- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — MSO exposes one generic OAuth MCP server. ChatGPT gets a compact 29-tool scan profile with complete title/safety/security metadata, resource-bound OAuth + rotating refresh tokens, while other MCP clients can use the full catalog. Project-owned MCP tool names never enter the global list: discover/call them dynamically through the generic `project_mcp_tools` / `project_mcp_call` seam. See the [ChatGPT custom MCP guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).- **Message live local sessions by a short name** — every durable same-principal MSO session gets a unique familiar handle such as `@milo`, `@luna`, or `@nara`, independent from its longer auto-generated session title. `/rename <name>` changes that handle, while `/title <text>` changes the session description. `@milo …` resolves only agents with a current lease **and** a live receiver subscription, then creates an explicitly correlated request; replies relay deterministically into the originating conversation while notify-only events remain passive. Presence lease (`idle`/`busy`/`offline`) and receiver subscription (`consumerConnected`) are reported separately so an idle-but-unsubscribed target is diagnosable. For ChatGPT/MCP sessions, `local_agent_inbox(wait_ms=...)` temporarily turns the foreground MCP call into that live receiver for up to 20 seconds, enabling direct two-way session messaging without a worker, DB, webhook, or broker. See [Local Agents](./docs/LOCAL-AGENTS.md).- **Spawn focused same-session subagents** — `/spawn` and `agent_subagent_run` create bounded foreground workers with isolated context, explicit delegated scope, turn/timeout caps, no recursive spawn, and final-result-only return. They are not Local Agent peers and do not run autonomously after the parent call returns. See [Subagents](./docs/SUBAGENTS.md).- **Delegate between remote agents with standard A2A v1** — register public HTTPS peers, attach private API-key/Bearer/OAuth access-token profiles, stream remote tasks over SSE, or expose MSO's authenticated inbound Agent Card when a public HTTPS origin is configured. Inbound credentials are owner-minted `read | write | exec` capabilities and run in a memory-isolated task context. See [A2A](./docs/A2A.md).diff --git a/app/.well-known/oauth-authorization-server/route.ts b/app/.well-known/oauth-authorization-server/route.tsindex 1ea33e71..018f4942 100644--- a/app/.well-known/oauth-authorization-server/route.ts+++ b/app/.well-known/oauth-authorization-server/route.ts@@ -2,7 +2,7 @@ import { publicOrigin } from "@/lib/mcp/origin";import { mcpEnabled } from "@/lib/mcp/scope";// RFC 8414 — authorization-server metadata. Public clients only (no secret),-// PKCE S256 only, authorization_code only. Dynamic Client Registration is+// PKCE S256 only; authorization_code + rotating refresh_token grants. Dynamic Client Registration is// advertised because Claude.ai, Cursor and mcp-remote all expect it; ChatGPT// uses a user-defined client and never touches /oauth/register.export const runtime = "nodejs";@@ -17,10 +17,11 @@ export async function GET(req: Request) {token_endpoint: `${origin}/oauth/token`,registration_endpoint: `${origin}/oauth/register`,response_types_supported: ["code"],- grant_types_supported: ["authorization_code"],+ grant_types_supported: ["authorization_code", "refresh_token"],code_challenge_methods_supported: ["S256"],token_endpoint_auth_methods_supported: ["none"],- scopes_supported: ["read", "write", "exec"],+ scopes_supported: ["read", "write", "exec", "offline_access"],+ authorization_response_iss_parameter_supported: true,},{ headers: { "cache-control": "public, max-age=3600" } },);diff --git a/app/.well-known/oauth-protected-resource/route.ts b/app/.well-known/oauth-protected-resource/route.tsindex 39937bee..a3315f49 100644--- a/app/.well-known/oauth-protected-resource/route.ts+++ b/app/.well-known/oauth-protected-resource/route.ts@@ -14,7 +14,7 @@ export async function GET(req: Request) {{resource: `${origin}/mcp`,authorization_servers: [origin],- scopes_supported: ["read", "write", "exec"],+ scopes_supported: ["read", "write", "exec", "offline_access"],bearer_methods_supported: ["header"],},{ headers: { "cache-control": "public, max-age=3600" } },diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.tsindex 47eee666..71f691f6 100644--- a/app/api/auth/login/route.ts+++ b/app/api/auth/login/route.ts@@ -9,7 +9,7 @@ import { IS_DEMO } from "@/lib/demo";export const runtime = "nodejs";export const dynamic = "force-dynamic";-// Password + device-approval login, ported from the VPS Control Room.+// Password + device-approval login, implemented for the VPS control plane.// gate 1 = shared password (OS_LOGIN_PASSWORD)// gate 2 = device id pre-approved in the device store// Correct password on an un-approved device → recorded pending, 403, NO cookie.diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.tsindex dd1d2412..41b155b4 100644--- a/app/mcp/route.test.ts+++ b/app/mcp/route.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({validateToken: vi.fn(),touchToken: vi.fn(async () => {}),+ getClient: vi.fn(),dispatch: vi.fn(async () => ({ jsonrpc: "2.0", id: 1, result: {} })),clampScope: vi.fn((scope: "read" | "write" | "exec") => scope),rateLimited: vi.fn(() => false),@@ -14,6 +15,7 @@ const mocks = vi.hoisted(() => ({vi.mock("@/lib/mcp/store", () => ({validateToken: mocks.validateToken,touchToken: mocks.touchToken,+ getClient: mocks.getClient,}));vi.mock("@/lib/mcp/dispatch", () => ({dispatch: mocks.dispatch,@@ -40,6 +42,10 @@ vi.mock("@/lib/host", () => ({}));vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({}) }));+vi.mock("@/lib/mcp/client-profile", () => ({ detectMcpToolProfile: ({ name }: { name?: string }) => name === "ChatGPT" ? "chatgpt" : "full" }));+vi.mock("@/lib/mcp/protocol", () => ({ supportedMcpProtocol: (v: string) => ["2026-07-28", "2025-11-25", "2024-11-05"].includes(v) }));+vi.mock("@/lib/mcp/tool-contract", () => ({ visibleToolsForProfile: () => [] }));+vi.mock("@/lib/agent/session-store", () => ({findOrCreateAgentSessionForConversation: mocks.findOrCreateAgentSessionForConversation,}));@@ -58,6 +64,7 @@ describe("/mcp request boundary", () => {beforeEach(() => {mocks.validateToken.mockReset();mocks.touchToken.mockClear();+ mocks.getClient.mockReset().mockResolvedValue(null);mocks.dispatch.mockClear();mocks.clampScope.mockClear();mocks.rateLimited.mockClear().mockReturnValue(false);@@ -141,13 +148,14 @@ describe("/mcp request boundary", () => {body,"read",`mcp:${token.hash.slice(0, 16)}`,- undefined,+ { principal: `mcp-client:${token.clientId}`, toolProfile: "full" },);});it("binds tools/call to a hashed ChatGPT conversation session without forwarding the raw conversation id", async () => {const token = { hash: "e".repeat(64), scope: "read" as const, clientId: "client-session", label: "Session test" };mocks.validateToken.mockResolvedValue(token);+ mocks.getClient.mockResolvedValue({ name: "ChatGPT", redirectUris: ["https://chatgpt.com/connector/oauth/test"] });const { POST } = await import("./route");const rawConversation = "chatgpt-conversation-raw-secret-id";const body = { jsonrpc: "2.0", id: 7, method: "tools/call", params: {@@ -161,10 +169,33 @@ describe("/mcp request boundary", () => {expect(hash).toMatch(/^[a-f0-9]{64}$/);expect(hash).not.toContain(rawConversation);expect(mocks.dispatch).toHaveBeenCalledWith(body, "read", `mcp:${token.hash.slice(0, 16)}`, {- principal: `mcp-client:${token.clientId}`, sessionId: "20260901_100000_aabbccdd",+ principal: `mcp-client:${token.clientId}`, sessionId: "20260901_100000_aabbccdd", toolProfile: "chatgpt",});});+ it("rejects a resource-bound token minted for another MCP server", async () => {+ mocks.validateToken.mockResolvedValueOnce({ hash: "f".repeat(64), scope: "read", clientId: "client-resource", label: "Resource", resource: "https://other.example/mcp" });+ const { POST } = await import("./route");+ const res = await POST(request(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })));+ expect(res.status).toBe(401);+ expect(mocks.dispatch).not.toHaveBeenCalled();+ });++ it("rejects an unsupported MCP-Protocol-Version before dispatch", async () => {+ mocks.validateToken.mockResolvedValueOnce({ hash: "1".repeat(64), scope: "read", clientId: "client-protocol", label: "Protocol" });+ const { POST } = await import("./route");+ const res = await POST(request(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), { "MCP-Protocol-Version": "2099-01-01" }));+ expect(res.status).toBe(400);+ expect(mocks.dispatch).not.toHaveBeenCalled();+ });++ it("returns 405 for the optional Streamable HTTP SSE listener when MSO does not expose one", async () => {+ const { GET } = await import("./route");+ const res = await GET(new Request("https://mso.example.test/mcp", { headers: { accept: "text/event-stream" } }));+ expect(res.status).toBe(405);+ expect(res.headers.get("allow")).toBe("POST");+ });+it("applies the 50,000-call daily token limit", async () => {const token = { hash: "d".repeat(64), scope: "read" as const, clientId: "client-daily", label: "Daily test" };mocks.validateToken.mockResolvedValueOnce(token);diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex 223ef114..e2a8f455 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -1,10 +1,13 @@import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED, type RpcRequest } from "@/lib/mcp/dispatch";-import { validateToken, touchToken } from "@/lib/mcp/store";+import { getClient, validateToken, touchToken } from "@/lib/mcp/store";import { clampScope, mcpEnabled } from "@/lib/mcp/scope";import { publicOrigin, clientIp, mcpRequestOriginAllowed } from "@/lib/mcp/origin";import { rateLimited, rateLimitedUntrusted } from "@/lib/host";import { TOOLS } from "@/lib/mcp/tools";import { toolsetInfo } from "@/lib/mcp/toolset";+import { detectMcpToolProfile } from "@/lib/mcp/client-profile";+import { supportedMcpProtocol } from "@/lib/mcp/protocol";+import { visibleToolsForProfile } from "@/lib/mcp/tool-contract";import { mcpSessionHeaders, resolveMcpSession } from "@/lib/mcp/session-context";export const runtime = "nodejs";@@ -68,7 +71,15 @@ export async function POST(req: Request) {}const rpc = body as RpcRequest;+ const protocolHeader = (req.headers.get("mcp-protocol-version") ?? "").trim();+ if (rpc.method !== "initialize" && protocolHeader && !supportedMcpProtocol(protocolHeader)) {+ return Response.json({ jsonrpc: "2.0", id: rpc.id ?? null, error: { code: -32600, message: "unsupported MCP-Protocol-Version" } }, { status: 400, headers: { "Cache-Control": "no-store" } });+ }const principal = token.clientId ? `mcp-client:${token.clientId}` : `mcp-token:${token.hash}`;+ const expectedResource = `${origin}/mcp`;+ if (token.resource && token.resource !== expectedResource) return unauthorized("token was minted for a different MCP resource");+ const client = token.clientId ? await getClient(token.clientId).catch(() => null) : null;+ const toolProfile = token.profile ?? client?.profile ?? detectMcpToolProfile({ clientId: token.clientId, name: client?.name, redirectUris: client?.redirectUris });const resolved = await resolveMcpSession(req, rpc, principal, token.label);if ("response" in resolved) return resolved.response;const headers = mcpSessionHeaders(resolved.responseSessionId);@@ -76,7 +87,7 @@ export async function POST(req: Request) {void touchToken(token.hash).catch(() => {});const actor = `mcp:${token.hash.slice(0, 16)}`;- const agentContext = resolved.agentSessionId ? { principal, sessionId: resolved.agentSessionId } : undefined;+ const agentContext = { principal, ...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}), toolProfile };const result = await dispatch(rpc, effectiveScope, actor, agentContext);return Response.json(result, { status: 200, headers });}@@ -84,10 +95,21 @@ export async function POST(req: Request) {export async function GET(req: Request) {if (!mcpEnabled()) return new Response("Not Found", { status: 404 });if (!mcpRequestOriginAllowed(req)) return Response.json({ error: "forbidden_origin" }, { status: 403, headers: { "Cache-Control": "no-store" } });+ // Streamable HTTP: a client GET is an optional SSE listener. MSO does not need+ // one for its bounded request/response model, so the standards-compliant answer+ // is 405 rather than a JSON diagnostics document masquerading as SSE.+ if ((req.headers.get("accept") ?? "").toLowerCase().includes("text/event-stream")) {+ return new Response(null, { status: 405, headers: { Allow: "POST", "Cache-Control": "no-store" } });+ }+ const full = toolsetInfo(TOOLS, undefined, "full");+ const chatgptTools = visibleToolsForProfile(TOOLS, "exec", "chatgpt");return Response.json({- name: "mso MCP", transport: "streamable-http (JSON-RPC over POST)",- auth: "Bearer <mcp token> — obtain via OAuth 2.1 + PKCE",+ name: "mso MCP", transport: "streamable-http", auth: "OAuth 2.1 + PKCE + resource binding",sessions: "ChatGPT conversations bind through hashed _meta[openai/session]; Mcp-Session-Id is legacy transport compatibility only",- authorization_servers: [publicOrigin(req)], toolset: toolsetInfo(TOOLS),- });+ authorization_servers: [publicOrigin(req)], toolset: full, chatgptToolset: toolsetInfo(chatgptTools, "exec", "chatgpt"),+ }, { headers: { "Cache-Control": "no-store" } });+}++export async function DELETE() {+ return new Response(null, { status: 405, headers: { Allow: "POST, GET", "Cache-Control": "no-store" } });}diff --git a/app/oauth/authorize/actions.test.ts b/app/oauth/authorize/actions.test.tsindex a934c937..d512854f 100644--- a/app/oauth/authorize/actions.test.ts+++ b/app/oauth/authorize/actions.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mocks = vi.hoisted(() => ({requireSession: vi.fn(),@@ -36,28 +36,37 @@ const form = (redirectUri = "https://chatgpt.com/connector/oauth/test") => {data.set("code_challenge_method", "S256");data.set("state", "state-1");data.set("scope", "exec");+ data.set("resource", "https://mso.example.test/mcp");+ data.set("issuer", "https://mso.example.test");+ data.set("offline_access", "1");return data;};describe("OAuth consent approval", () => {beforeEach(() => {vi.clearAllMocks();+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test");mocks.requireSession.mockResolvedValue(true);mocks.randomToken.mockReturnValue("mso_code_test");- mocks.getClient.mockResolvedValue({ redirectUris: ["https://chatgpt.com/connector/oauth/test"] });+ mocks.getClient.mockResolvedValue({ name: "ChatGPT", profile: "chatgpt", redirectUris: ["https://chatgpt.com/connector/oauth/test"] });});+ afterEach(() => vi.unstubAllEnvs());+it("returns the validated callback for explicit top-level navigation", async () => {const before = Date.now();await expect(approve(form())).resolves.toEqual({ok: true,- redirectTo: "https://chatgpt.com/connector/oauth/test?code=mso_code_test&state=state-1",+ redirectTo: "https://chatgpt.com/connector/oauth/test?code=mso_code_test&state=state-1&iss=https%3A%2F%2Fmso.example.test",});expect(mocks.storeCode).toHaveBeenCalledWith("mso_code_test", expect.objectContaining({clientId: "chatgpt-client",redirectUri: "https://chatgpt.com/connector/oauth/test",codeChallenge: "challenge",scope: "exec",+ resource: "https://mso.example.test/mcp",+ profile: "chatgpt",+ offlineAccess: true,expiresAt: expect.any(Number),}));expect(mocks.storeCode.mock.calls[0][1].expiresAt).toBeGreaterThanOrEqual(before + 59_000);diff --git a/app/oauth/authorize/actions.ts b/app/oauth/authorize/actions.tsindex 0df31bf6..708e02d5 100644--- a/app/oauth/authorize/actions.ts+++ b/app/oauth/authorize/actions.ts@@ -1,9 +1,11 @@"use server";import { requireSession } from "@/lib/auth/require-session";+import { headers } from "next/headers";import { getClient, storeCode, CODE_TTL_MS } from "@/lib/mcp/store";import { randomToken, isAllowedRedirect } from "@/lib/mcp/pkce";import { parseScope, clampScope, mcpEnabled, type Scope } from "@/lib/mcp/scope";+import { detectMcpToolProfile } from "@/lib/mcp/client-profile";export type ApprovalResult =| { ok: false; error: string }@@ -26,10 +28,21 @@ export async function approve(form: FormData): Promise<ApprovalResult> {const challenge = String(form.get("code_challenge") ?? "");const method = String(form.get("code_challenge_method") ?? "");const state = String(form.get("state") ?? "");+ const resource = String(form.get("resource") ?? "");+ const issuer = String(form.get("issuer") ?? "");+ const offlineAccess = String(form.get("offline_access") ?? "") === "1";const scope: Scope = clampScope(parseScope(String(form.get("scope") ?? "read")));if (method !== "S256" || !challenge) return { ok: false, error: "This client did not use PKCE S256, which mso requires." };if (!isAllowedRedirect(redirectUri)) return { ok: false, error: "The redirect target is not https (or localhost)." };+ const configured = process.env.OS_PUBLIC_ORIGIN?.trim();+ let expectedIssuer = "";+ if (configured) { try { expectedIssuer = new URL(configured).origin; } catch {} }+ if (!expectedIssuer) {+ const h = await headers(), proto = h.get("x-forwarded-proto")?.split(",")[0].trim() || "https", host = h.get("host") ?? h.get("x-forwarded-host") ?? "";+ try { expectedIssuer = new URL(`${proto}://${host}`).origin; } catch {}+ }+ if (!expectedIssuer || issuer !== expectedIssuer || resource !== `${expectedIssuer}/mcp`) return { ok: false, error: "OAuth resource/issuer mismatch." };const client = await getClient(clientId);// A user-defined client (ChatGPT's flow) never registers, so it has no record@@ -46,11 +59,15 @@ export async function approve(form: FormData): Promise<ApprovalResult> {redirectUri,codeChallenge: challenge,scope,+ resource,+ profile: client?.profile ?? detectMcpToolProfile({ clientId, name: client?.name, redirectUris: client?.redirectUris ?? [redirectUri] }),+ offlineAccess,expiresAt: Date.now() + CODE_TTL_MS,});const dest = new URL(redirectUri);dest.searchParams.set("code", code);if (state) dest.searchParams.set("state", state);+ dest.searchParams.set("iss", issuer);return { ok: true, redirectTo: dest.toString() };}diff --git a/app/oauth/authorize/page.tsx b/app/oauth/authorize/page.tsxindex 64d9d70b..0b2f986d 100644--- a/app/oauth/authorize/page.tsx+++ b/app/oauth/authorize/page.tsx@@ -1,5 +1,6 @@import Link from "next/link";import { notFound } from "next/navigation";+import { headers } from "next/headers";import { requireSession } from "@/lib/auth/require-session";import { getClient } from "@/lib/mcp/store";import { isAllowedRedirect } from "@/lib/mcp/pkce";@@ -29,6 +30,14 @@ export default async function AuthorizePage({const one = (k: string) => (Array.isArray(q[k]) ? q[k][0] : q[k]) ?? "";const clientId = one("client_id");+ const h = await headers();+ const configured = process.env.OS_PUBLIC_ORIGIN?.trim();+ const proto = h.get("x-forwarded-proto")?.split(",")[0].trim() || "https";+ const host = h.get("host") ?? h.get("x-forwarded-host") ?? "";+ const issuer = (() => { try { return configured ? new URL(configured).origin : new URL(`${proto}://${host}`).origin; } catch { return ""; } })();+ const expectedResource = issuer ? `${issuer}/mcp` : "";+ const resource = one("resource") || expectedResource;+ const offlineAccess = one("scope").split(/\s+/).includes("offline_access");const redirectUri = one("redirect_uri");const challenge = one("code_challenge");const method = one("code_challenge_method");@@ -72,6 +81,7 @@ export default async function AuthorizePage({!clientId ? "The client did not send a client_id.": !isAllowedRedirect(redirectUri) ? "The client's redirect target is missing, or is not https (or localhost).": method !== "S256" || !challenge ? "The client did not use PKCE with S256, which mso requires."+ : !issuer || resource !== expectedResource ? "The OAuth resource does not match this MSO MCP endpoint.": null;if (problem) {@@ -95,7 +105,7 @@ export default async function AuthorizePage({// sees a spinner rather than "you declined". RFC 6749 §4.1.2.1 — and `state`// rides along, because a client that cannot match the response to its own// request is required to discard it.- const deny = denyUrl(redirectUri, one("state"));+ const deny = denyUrl(redirectUri, one("state"), issuer);return (<Shell>@@ -110,6 +120,9 @@ export default async function AuthorizePage({code_challenge: challenge,code_challenge_method: method,state: one("state"),+ resource,+ issuer,+ offline_access: offlineAccess ? "1" : "0",}}/></Shell>diff --git a/app/oauth/register/route.ts b/app/oauth/register/route.tsindex 5dfbd5c2..4f4eecf8 100644--- a/app/oauth/register/route.ts+++ b/app/oauth/register/route.ts@@ -43,7 +43,7 @@ export async function POST(req: Request) {redirect_uris: uris,client_name: name.slice(0, 80),token_endpoint_auth_method: "none",- grant_types: ["authorization_code"],+ grant_types: ["authorization_code", "refresh_token"],response_types: ["code"],},{ status: 201, headers: { "Cache-Control": "no-store" } },diff --git a/app/oauth/token/route.test.ts b/app/oauth/token/route.test.tsnew file mode 100644index 00000000..0e19e511--- /dev/null+++ b/app/oauth/token/route.test.ts@@ -0,0 +1,31 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({ consumeCode: vi.fn(), storeGrant: vi.fn(), rotate: vi.fn(), random: vi.fn(), verify: vi.fn(() => true), limited: vi.fn(() => false) }));+vi.mock("@/lib/mcp/store", () => ({ consumeCode: mocks.consumeCode, storeOAuthGrant: mocks.storeGrant, rotateOAuthGrant: mocks.rotate, OAUTH_ACCESS_TOKEN_TTL_MS: 3_600_000 }));+vi.mock("@/lib/mcp/pkce", () => ({ verifyPkce: mocks.verify, randomToken: mocks.random }));+vi.mock("@/lib/mcp/scope", () => ({ mcpEnabled: () => true, oauthScopeString: (scope: string, offline = false) => `${scope}${offline ? " offline_access" : ""}` }));+vi.mock("@/lib/mcp/origin", () => ({ clientIp: () => "127.0.0.1", publicOrigin: () => "https://mso.example.test" }));+vi.mock("@/lib/host", () => ({ rateLimitedUntrusted: mocks.limited }));+const { POST } = await import("./route");+const post = (body: Record<string, string>) => new Request("https://mso.example.test/oauth/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body) });++describe("OAuth token endpoint", () => {+ beforeEach(() => { vi.clearAllMocks(); mocks.random.mockImplementation((prefix: string) => `${prefix}${mocks.random.mock.calls.length}`); mocks.verify.mockReturnValue(true); });++ it("exchanges an authorization code into resource-bound access + refresh credentials", async () => {+ mocks.consumeCode.mockResolvedValue({ clientId: "chatgpt", redirectUri: "https://chatgpt.com/cb", codeChallenge: "challenge", scope: "exec", resource: "https://mso.example.test/mcp", profile: "chatgpt", offlineAccess: true });+ const res = await POST(post({ grant_type: "authorization_code", code: "code", code_verifier: "v".repeat(43), client_id: "chatgpt", redirect_uri: "https://chatgpt.com/cb", resource: "https://mso.example.test/mcp" }));+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body).toMatchObject({ token_type: "Bearer", expires_in: 3600, scope: "exec offline_access" });+ expect(body.access_token).toMatch(/^mso_mcp_/); expect(body.refresh_token).toMatch(/^mso_refresh_/);+ expect(mocks.storeGrant).toHaveBeenCalledWith(expect.objectContaining({ clientId: "chatgpt", resource: "https://mso.example.test/mcp", profile: "chatgpt", offlineAccess: true }));+ });++ it("rotates a refresh credential and rejects a wrong resource", async () => {+ mocks.rotate.mockResolvedValue({ clientId: "chatgpt", scope: "exec", resource: "https://mso.example.test/mcp", profile: "chatgpt", offlineAccess: true, grantId: "g" });+ const ok = await POST(post({ grant_type: "refresh_token", refresh_token: "r1", client_id: "chatgpt", resource: "https://mso.example.test/mcp" }));+ expect(ok.status).toBe(200); expect((await ok.json()).refresh_token).toMatch(/^mso_refresh_/);+ const bad = await POST(post({ grant_type: "refresh_token", refresh_token: "r1", client_id: "chatgpt", resource: "https://other.example/mcp" }));+ expect(bad.status).toBe(400); expect(await bad.json()).toMatchObject({ error: "invalid_target" });+ });+});diff --git a/app/oauth/token/route.ts b/app/oauth/token/route.tsindex e309295b..59e15356 100644--- a/app/oauth/token/route.ts+++ b/app/oauth/token/route.ts@@ -1,52 +1,44 @@-import { consumeCode, storeToken, TOKEN_TTL_MS } from "@/lib/mcp/store";+import { consumeCode, OAUTH_ACCESS_TOKEN_TTL_MS, rotateOAuthGrant, storeOAuthGrant } from "@/lib/mcp/store";import { verifyPkce, randomToken } from "@/lib/mcp/pkce";-import { mcpEnabled } from "@/lib/mcp/scope";-import { clientIp } from "@/lib/mcp/origin";+import { mcpEnabled, oauthScopeString } from "@/lib/mcp/scope";+import { clientIp, publicOrigin } from "@/lib/mcp/origin";import { rateLimitedUntrusted } from "@/lib/host";-// OAuth token endpoint. authorization_code only, PKCE mandatory.export const runtime = "nodejs";export const dynamic = "force-dynamic";+const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });-const json = (body: unknown, status: number) =>- Response.json(body, { status, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } });+async function params(req: Request): Promise<Record<string, string>> {+ const p: Record<string, string> = {}, ct = req.headers.get("content-type") ?? "";+ if (ct.includes("application/json")) Object.assign(p, await req.json().catch(() => ({})));+ else { const form = await req.formData().catch(() => null); if (form) for (const [k, v] of form.entries()) p[k] = String(v); }+ return p;+}export async function POST(req: Request) {if (!mcpEnabled()) return new Response("Not Found", { status: 404 });- if (rateLimitedUntrusted(`mcp:token:${clientIp(req)}`, 30, 60_000)) {- return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "60" } });- }+ if (rateLimitedUntrusted(`mcp:token:${clientIp(req)}`, 30, 60_000)) return json({ error: "rate_limited" }, 429);+ const p = await params(req), expectedResource = `${publicOrigin(req)}/mcp`;- // ChatGPT posts form-encoded; some clients post JSON. Accept both.- const p: Record<string, string> = {};- const ct = req.headers.get("content-type") ?? "";- if (ct.includes("application/json")) {- Object.assign(p, await req.json().catch(() => ({})));- } else {- const form = await req.formData().catch(() => null);- if (form) for (const [k, v] of form.entries()) p[k] = String(v);+ if (p.grant_type === "refresh_token") {+ if (!p.refresh_token || !p.client_id) return json({ error: "invalid_request" }, 400);+ const resource = p.resource || expectedResource;+ if (resource !== expectedResource) return json({ error: "invalid_target" }, 400);+ const access = randomToken("mso_mcp_"), refresh = randomToken("mso_refresh_");+ const rec = await rotateOAuthGrant({ oldRefreshToken: p.refresh_token, accessToken: access, refreshToken: refresh, label: `oauth · ${p.client_id.slice(0, 14)}`, clientId: p.client_id, resource });+ if (!rec) return json({ error: "invalid_grant" }, 400);+ return json({ access_token: access, token_type: "Bearer", refresh_token: refresh, expires_in: Math.floor(OAUTH_ACCESS_TOKEN_TTL_MS / 1000), scope: oauthScopeString(rec.scope, rec.offlineAccess === true) });}if (p.grant_type !== "authorization_code") return json({ error: "unsupported_grant_type" }, 400);if (!p.code || !p.code_verifier || !p.client_id || !p.redirect_uri) return json({ error: "invalid_request" }, 400);-- // Consume FIRST: the row is gone before anything is minted, so a replay (or two- // racing retries) finds nothing and gets invalid_grant rather than a second token.const rec = await consumeCode(p.code);- // Every failure below is the same opaque invalid_grant — telling a caller which- // check failed tells an attacker which half of the guess was right.if (!rec) return json({ error: "invalid_grant" }, 400);- if (rec.clientId !== p.client_id || rec.redirectUri !== p.redirect_uri) return json({ error: "invalid_grant" }, 400);+ const resource = p.resource || rec.resource || expectedResource;+ if (rec.clientId !== p.client_id || rec.redirectUri !== p.redirect_uri || resource !== (rec.resource || expectedResource) || resource !== expectedResource) return json({ error: "invalid_grant" }, 400);if (!verifyPkce(p.code_verifier, rec.codeChallenge, "S256")) return json({ error: "invalid_grant" }, 400);- const token = randomToken("mso_mcp_");- await storeToken(token, {- label: `oauth · ${rec.clientId.slice(0, 14)}`,- clientId: rec.clientId,- scope: rec.scope,- });- return json(- { access_token: token, token_type: "Bearer", scope: rec.scope, expires_in: Math.floor(TOKEN_TTL_MS / 1000) },- 200,- );+ const access = randomToken("mso_mcp_"), refresh = randomToken("mso_refresh_"), grantId = randomToken("grant_", 16);+ await storeOAuthGrant({ accessToken: access, refreshToken: refresh, label: `oauth · ${rec.clientId.slice(0, 14)}`, clientId: rec.clientId, scope: rec.scope, resource, profile: rec.profile, offlineAccess: rec.offlineAccess, grantId });+ return json({ access_token: access, token_type: "Bearer", refresh_token: refresh, expires_in: Math.floor(OAUTH_ACCESS_TOKEN_TTL_MS / 1000), scope: oauthScopeString(rec.scope, rec.offlineAccess === true) });}diff --git a/claude-skills/mso-mcp-feature-engineering/SKILL.md b/claude-skills/mso-mcp-feature-engineering/SKILL.mdindex 55711075..58cb58bd 100644--- a/claude-skills/mso-mcp-feature-engineering/SKILL.md+++ b/claude-skills/mso-mcp-feature-engineering/SKILL.md@@ -51,11 +51,10 @@ For a public MCP tool, inspect and update all affected surfaces:- rate, size, timeout, path, pagination and continuation limits;- Alfa/MCP parity or an explicit documented MCP-only reason;- toolset version/hash/count and public descriptor;-- connectors-gateway literals and other external action mappings;+- downstream cached action mappings and other external client snapshots;- current docs, progress rationale and client-rescan instructions.-Never create a parallel raw `fs`/`child_process` path inside a tool. Never rename a public tool-without checking the external mapping contract.+Never create a parallel raw `fs`/`child_process` path inside a tool. Never rename a public tool without treating its MSO name/schema as a public compatibility contract.## Skill contractdiff --git a/claude-skills/mso-project-deploy/SKILL.md b/claude-skills/mso-project-deploy/SKILL.mdindex 43ea8bec..38fb8625 100644--- a/claude-skills/mso-project-deploy/SKILL.md+++ b/claude-skills/mso-project-deploy/SKILL.md@@ -9,7 +9,7 @@ metadata:# /mso-project-deploy — provider-aware project deployment-Use this flow when the owner asks MSO Agent to publish, redeploy, attach a domain, or finish infrastructure setup for an application. It is adapted from the proven provider separation in `rahmanef63/si-coder-agent`, but the MSO implementation uses its own private provider store and MCP approval boundary.+Use this flow when the owner asks MSO Agent to publish, redeploy, attach a domain, or finish infrastructure setup for an application. MSO uses its own private provider store and MCP approval boundary; it has no runtime dependency on another repository.## Credential boundarydiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 2f9ccad1..55d308e3 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -160,10 +160,8 @@ 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.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->-At the current toolset it exposes **71 transport tools**: **70 model/operator tools** (34 read, 24 write, 12 exec) plus the app-only `workflow_status` progress bridge. Project-specific-function names remain data behind `project_capabilities` / `project_function_call`, so one-project cannot dynamically rewrite the global MCP tool prefix. `GET /mcp` remains the live count/hash authority.+<!-- mcp-toolset: server=1.7.0 version=2026.09.03.3 tools=72 read=34 write=24 exec=14 -->+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 theChatGPT-facing setup and diagrams.@@ -175,7 +173,7 @@ MSO can discover projects across configured containers instead of assuming a sinare bounded, and return truthful truncation + continuation metadata when a scan cannotfinish in one pass.-A project can opt into two additional declarations:+A project can opt into two additional declarations without changing MSO global tool names:- `.mcp.json` — presence only is reported; MSO never exposes its contents or automaticallyconnects to arbitrary project MCP servers.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 73169890..50234a88 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.## 2026-09-03+**Added**++- `mcp` harden ChatGPT profile and project bridge+**Faster**- `agent` expand objective repo corpus@@ -377,7 +381,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Docs**- `progress` record the codebase audit — what was duplicated, drifted, undefended-- record that connectors-gateway now consumes this MCP surface+- record external MCP consumer compatibility- `readme` the update button, and what Preview actually opens- plain http to an IP cannot complete a login — say so where it mattersdiff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.mdindex 948602fa..99058fa4 100644--- a/docs/CHATGPT-PLUGIN.md+++ b/docs/CHATGPT-PLUGIN.md@@ -1,504 +1,204 @@-# ChatGPT plugin / custom MCP app for MSO+# ChatGPT custom MCP app for MSO-> **Current reference.** OpenAI currently exposes custom MCP setup through more than one product-> surface: the official Developer Mode guide uses **Apps → Create**, while ChatGPT Work and some-> plugin surfaces expose **Plugins → MCP / New Plugin**. The underlying MSO connection is the same-> remote MCP app/server. This is not a legacy ChatGPT Plugin manifest, browser extension, or a-> plugin installed inside Hermes/OpenClaw.+> **Current ChatGPT-facing reference.** MSO is one open-source MCP server. ChatGPT receives a deliberately compact static projection of MSO-owned generic tools; project-owned MCP tool names are never copied into the global catalog or ChatGPT scan snapshot.>-> ChatGPT's Developer Mode UI and permissions are controlled by OpenAI and can change during-> the MCP beta. Settings → MCP in MSO therefore shows the live endpoint, OAuth metadata and a-> guided setup instead of freezing one menu layout. Current OpenAI references:-> <https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>-> and <https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex>.--<!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->--MSO currently exposes MCP server **1.6.0**, toolset **2026.09.03.2**: **71 transport tools** total; **70 model/operator tools**-(34 read, 24 write, 12 exec) plus app-only `workflow_status` for the progress widget. Use `GET /mcp` or Settings → MCP as the live authority if-this document and a deployed instance ever disagree.--### Local-agent and subagent tools--The current catalog exposes `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, `local_agent_request_wait`, `local_agent_inbox`, and `local_agent_request` for same-principal session collaboration, plus `agent_subagent_run` for one bounded foreground isolated worker. `local_agents_list` separates lease status from receiver subscription. `local_agent_inbox` accepts optional `wait_ms` (0-20000): zero preserves the old immediate read, while a positive value holds only that foreground MCP call and returns early when a peer message arrives. During that wait the session is a real Local Agent receiver (`consumerConnected=true`), so another ChatGPT conversation on the same MCP client can deliver directly without spawning a worker. `local_agent_request_wait` remains the bounded no-resend wait for one exact outbound request; `local_agent_request` remains an exec-gated fresh worker from a durable session context and never claims to wake/control the original ChatGPT/terminal process. The local tools do not turn an MCP connection into a remote A2A peer, and the subagent tool does not create another durable session or background process. A client should use `local_agent_reply` for an exact inbox request instead of reconstructing correlation from text.--## 1. What this connection does--The ChatGPT app lets ChatGPT call the MSO tool catalog on your server. OAuth controls which-tier the bearer token can use; MSO then applies the same host path, project, managed-app-and process guards used by its other surfaces.--```mermaid-flowchart LR- U[Owner in ChatGPT] --> CG[ChatGPT custom MCP app]- CG -->|OAuth 2.1 + PKCE| OA[MSO /oauth/*]- OA -->|bearer token: read/write/exec| CG- CG -->|MCP JSON-RPC| M[MSO /mcp]- M --> D[scope + rate limit + audit dispatcher]- D --> H[lib/host]- D --> PR[project discovery/functions]- D --> SK[skills + workflow memory]- D --> INF[Dokploy / Cloudflare / Hostinger]- H --> FS[filesystem roots]- H --> SYS[system / PTY / exec]- H --> AP[Hermes / OpenClaw]-```--The MCP client does **not** get a Linux credential or SSH key. It gets an MSO bearer token-whose scope is re-checked on every tool call.--## 2. Before connecting ChatGPT--You need:+> 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.-1. a real owner MSO deployment over HTTPS;-2. an approved browser device that can open the MSO OAuth consent page;-3. `OS_MCP_ENABLED=1` on the running MSO service;-4. an intentional server ceiling, `OS_MCP_MAX_SCOPE=read|write|exec` (default is `exec`);-5. a ChatGPT plan/workspace that currently permits the MCP capability you need.+<!-- mcp-chatgpt-profile: server=1.7.0 version=2026.09.03.3 tools=28 read=14 write=8 exec=6 app-only=1 total=29 -->-ChatGPT connects to a **remote** MCP server. A private-only MSO endpoint therefore needs a-reachable HTTPS path rather than an unreachable `localhost` URL. MSO's supported laptop path-is `mso gateway start` (temporary preview URL) or a named/custom-domain tunnel; the Next app-itself remains loopback-only instead of publishing port 4005 directly.+MSO server **1.7.0**, toolset **2026.09.03.3** exposes a full generic catalog for MCP clients, but a registered ChatGPT client receives only **29 transport tools**: **28 model/operator tools** (14 read, 8 write, 6 exec) plus app-only `workflow_status`.-After changing MSO environment configuration, use the normal MSO update/rebuild path; do-not treat a Git push as deployment.+The compact descriptor regression currently measures **31,811 JSON bytes** for all 29 ChatGPT tool definitions (roughly 8k tokens at a 4-byte/token estimate), with the largest individual descriptor **2,507 bytes**. CI keeps the profile below 40 KiB and each descriptor below 8 KiB. Bytes are the deterministic contract; token estimates vary by tokenizer.-### Current ChatGPT availability (external, checked 2026-08-31)+## Why ChatGPT gets a compact profile-OpenAI's current Developer Mode documentation says full MCP, including write/modify actions,-is rolling out in beta for Business, Enterprise and Edu workspaces and remains subject to-workspace/admin controls. The Plugin/App UI and entitlements are OpenAI product decisions and-can change independently of MSO, so Settings → MCP intentionally does not hard-code a plan-matrix. Check the current OpenAI article before treating any plan as entitled:-<https://help.openai.com/en/articles/12584461-developer-mode-and-mcp-apps-in-chatgpt-beta>.+The full MSO catalog remains available to generic MCP clients. ChatGPT action scanning is different: it freezes names, titles, descriptions, JSON Schemas, safety annotations and security metadata into a cached action snapshot. Sending every internal MSO capability wastes scan/model context and makes refreshes more fragile.-MSO itself does not special-case ChatGPT plans. It publishes the same scoped MCP server; the-client decides which actions it will expose/allow.+MSO therefore applies a **client profile** after OAuth identity is known:-## 3. MSO endpoint values+```text+full MCP client+ └─ full MSO catalog++ChatGPT+ └─ compact MSO catalog+ ├─ workflow / skill discovery+ ├─ files / visual proof+ ├─ bounded shell lifecycle+ ├─ durable session + Local Agents+ └─ generic dynamic project seams+```-For an MSO origin such as `https://mso.example.com`:+The profile is fail-closed at both `tools/list` and `tools/call`: guessing a hidden full-catalog name returns `unknown tool`. This profile is a compatibility/context boundary, not a privilege escalation mechanism; the OAuth `read < write < exec` scope is still enforced independently.-| Purpose | Value |-|---|---|-| MCP server | `https://mso.example.com/mcp` |-| OAuth authorization | `https://mso.example.com/oauth/authorize` |-| OAuth token | `https://mso.example.com/oauth/token` |-| Dynamic client registration | `https://mso.example.com/oauth/register` |-| Authorization-server metadata | `https://mso.example.com/.well-known/oauth-authorization-server` |-| Protected-resource metadata | `https://mso.example.com/.well-known/oauth-protected-resource` |+## Tool metadata contract-MSO supports public OAuth clients with PKCE S256 and token-endpoint authentication method-`none`. ChatGPT can use the predefined public client id `chatgpt-mso`; a client secret is-not required. Other MCP clients can use Dynamic Client Registration where supported.--The exact ChatGPT form labels can change during the beta. The current MSO Settings → MCP-guide mirrors the common flow shown by OpenAI's Plugin/App UI:--1. enable Developer Mode for the account/workspace if required;-2. open Plugins or Apps and choose **New Plugin / Create**;-3. choose **Server URL** and paste the live MCP Server URL shown by MSO;-4. choose **OAuth**. MSO publishes the two `.well-known` documents automatically, uses PKCE- S256, requires no client secret, and advertises token endpoint authentication `none`;-5. complete authorization in the browser, choose the lowest useful MSO scope, then return to- ChatGPT and **Scan Tools / Create**;-6. enable the resulting MSO app/plugin from the tools or `+` menu in the chat before using it.--If ChatGPT shows the custom-server risk acknowledgement, review it rather than treating it as-an error. When the authorization browser opens, sign into MSO on an approved device and Allow-only the tier you intend.--## 4. OAuth lifecycle--```mermaid-sequenceDiagram- actor Owner- participant ChatGPT- participant Auth as MSO OAuth- participant Store as MSO token store- participant MCP as MSO /mcp-- Owner->>ChatGPT: Create/enable MSO custom MCP app- ChatGPT->>Auth: authorization request + PKCE challenge- Auth->>Owner: signed-in consent page- Owner->>Auth: choose allowed scope and Allow- Auth-->>ChatGPT: one-time authorization code- ChatGPT->>Auth: exchange code + PKCE verifier- Auth->>Store: store hash of bearer token- Auth-->>ChatGPT: bearer token- ChatGPT->>MCP: initialize / tools.list / tools.call- MCP->>Store: validate token + scope on every call- MCP-->>ChatGPT: tool results-```+Every advertised MSO tool has:-Authorization codes live for 60 seconds and are consumed once. MCP bearer tokens expire-after 90 days unless revoked earlier. MSO stores token/code hashes, not reusable plaintext-bearers. The current authorization metadata advertises only `authorization_code`; MSO does-**not** issue refresh tokens. After a bearer expires (or is revoked), authorize the MCP app-again rather than expecting an offline refresh grant.+- 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);+- explicit boolean `readOnlyHint`, `destructiveHint`, and `openWorldHint` annotations;+- optional `idempotentHint` where meaningful;+- matching top-level and `_meta.securitySchemes` OAuth metadata.-## 5. Scope ladder and exact tool catalog+The ChatGPT projection compacts verbose descriptions/schema descriptions without changing names, required arguments, enum/range constraints, scopes, or safety semantics.-A token sees a scope prefix; there is no per-project or per-agent hidden tool filter.-`tools/list` filters the catalog and `tools/call` independently re-checks the required-scope.+## Exact ChatGPT model tool profile-### `read` — 34 model/operator tools+### `read` — 14 ChatGPT model tools-- `a2a_agent_discover`-- `a2a_agents_list`-- `a2a_task_get`-- `agent_memory_read`-- `agent_memory_search`- `agent_session_current`-- `agent_session_resume`-- `agent_sessions_list`-- `apps_list`-- `apps_logs`-- `browser_status`-- `cloudflare_zones_list`-- `dokploy_projects_list`- `exec_job_status`- `fs_list`- `fs_read`- `fs_search`-- `fs_usage`-- `infra_provider_doctor`-- `infra_providers_list`- `local_agent_inbox`- `local_agent_request_wait`- `local_agents_list`- `project_capabilities`-- `project_memory_search`- `projects_list`- `read_pipeline`- `screen_capture`-- `skills_list`- `skills_read`- `skills_search`-- `sys_processes`-- `sys_stats`-- `tool_forge_candidates`-### `write` — read + 24 tools+### `write` — + 8 ChatGPT model tools-- `a2a_agent_register`-- `a2a_agent_remove`-- `agent_memory_forget`-- `agent_memory_remember`-- `agent_session_note`- `agent_session_rename`-- `apps_power`-- `cloudflare_dns_upsert`-- `dokploy_project_ensure`-- `fs_copy`-- `fs_delete`-- `fs_mkdir`-- `fs_move`- `fs_upload_file`- `fs_write`-- `hostinger_dns_upsert`- `local_agent_message_send`- `local_agent_reply`-- `project_memory_upsert`-- `project_script_run`-- `tool_forge_propose`- `workflow_cancel`- `workflow_finish`- `workflow_start`-### `exec` — write + 12 tools+### `exec` — + 6 ChatGPT model tools-- `a2a_handoff`-- `a2a_message_send`-- `a2a_task_cancel`-- `agent_subagent_run`-- `browser_power`- `exec_job_cancel`- `exec_job_start`- `exec_run`-- `local_agent_request`- `project_function_call`-- `tool_forge_evaluate`-- `tool_forge_promote`--RASMIC's `project_memory_search`, `project_memory_upsert`, and `project_script_run` keep compact redacted orchestration memory/evidence and deterministic automation portable under a managed repo's `.agent/` directory. `project_memory_search` uses one schema for ranked `search`, deterministic `related`, and compact `timeline` views instead of adding more tool names. They do not grant access to another repo or external memory service.+- `project_mcp_call`+- `project_mcp_tools`-`exec_run` is full host shell power as the MSO service user. The command filter is an-accident tripwire, not a sandbox. Grant `exec` only to a ChatGPT app/workspace you trust-with the same care as a remote shell.+### App-only ChatGPT bridge+`workflow_status` is available to the MCP Apps progress UI but is not counted as a model/operator action.+For the complete non-ChatGPT MSO catalog, scopes, limits, A2A, providers, Tool Forge and other generic capabilities, see [`MCP.md`](./MCP.md).-### Read pipeline for lower latency and context+## Dynamic project capabilities without global project tools-Use `read_pipeline` when several independent reads can be batched or when a large read result should be filtered/projected/aggregated before ChatGPT sees it. The pipeline is **read scope only**: child calls reuse the original tool's host guards and rate limits, inherit the current session/workflow, and are forced to read scope even if the OAuth bearer is `exec`.+MSO is generic and must not publish another project's MCP tool names.-The transform language is deliberately data-only: simple dotted paths, scalar comparisons, field projection, sorting, de-duplication, limiting, and numeric/count aggregates. There is no shell, JavaScript, arbitrary expression, nested pipeline, child `workflow_id`, or write/exec capability. A total 15-second response deadline and bounded intermediate/final results keep the orchestration predictable. P3's deterministic fixture measured 4 → 1 model round-trip and 99.2% lower model-visible bytes with exact answers.+`project_capabilities(project)` returns only safe project capability metadata. For a project `.mcp.json`, it exposes **server aliases, transport kind and auth class only** — never config contents, env values, headers, tokens or project MCP tool names.-### Tool Forge approval model--`tool_forge_propose` creates only inert candidates from repeated verified workflow recipes. Skill candidates are guidance only; a project-function candidate must point to an existing project-owned Node script and must come from an exec-scope verified recipe. Generated shell/code, credential-like fixture data, and implicit scope escalation are rejected.--`tool_forge_evaluate` runs executable fixtures only in the labelled local MSO Forge Docker sandbox. `tool_forge_promote` requires exact `PROMOTE <candidate_id>` confirmation and a fresh passing evaluation immediately before mutation. Candidate hash, target manifest, current toolset, project source SHA-256 and exact sandbox image evidence are checked again, and existing Skills/functions are never overwritten. Provision the local sandbox explicitly with `bun run forge:sandbox`; evaluation never auto-pulls an image.--### Infrastructure-provider actions--The infrastructure tools never accept API tokens as arguments. ChatGPT sees masked provider-status, then MSO loads Dokploy/Cloudflare/Hostinger credentials server-side for the approved-call. `cloudflare_dns_upsert` changes one exact record and defaults proxying off.-`hostinger_dns_upsert` uses Hostinger's scoped overwrite semantics: MSO sends one exact name/type RR-set rather than a full-zone-snapshot; unrelated rows are never included in the mutation payload and ambiguous/conflicting records are refused, but the action-still deserves the same scrutiny as any external infrastructure mutation. Configure providers-locally with `mso provider set <id>` rather than pasting credentials into a ChatGPT message.---### A2A peer delegation--ChatGPT can use `a2a_agent_discover`/`a2a_agents_list` to find peers, then the exec-scope-`a2a_message_send` or `a2a_handoff` to delegate explicit work. `a2a_task_get` reads a remote-task and `a2a_task_cancel` requests cancellation; register/remove mutate only MSO's sanitized peer-registry. Outbound peers may be anonymous or use a private API-key/Bearer/OAuth2 credential profile-configured by the owner outside the message payload. MSO can also expose an authenticated inbound A2A-server when an explicit public HTTPS origin exists, but that inbound bearer/task lifecycle is separate from-this ChatGPT MCP token. MSO never auto-forwards this ChatGPT conversation, private agent memory, or raw-MSO session/workflow ids to a peer. See [`A2A.md`](./A2A.md).--## 6. Tool-snapshot refresh: the part most often missed--ChatGPT scans and caches the MCP action definitions. If MSO adds/removes/changes tools, a-running ChatGPT app may continue using its previous snapshot until you refresh/recreate the-app according to the current ChatGPT workspace controls.--MSO exposes a schema-derived signature in `GET /mcp`, MCP `initialize`, `tools/list`, and-Settings → MCP:+Then:```text-server: 1.6.0-toolset: 2026.09.02.7-hash: <live schema hash>-count: 70 model/operator tools (+ 1 app-only bridge)-```--Toolset `2026.09.03.2` changes the `local_agent_inbox` input schema by adding optional `wait_ms`. ChatGPT keeps a frozen action snapshot, so refresh/re-scan the MSO app actions before expecting the model to see this parameter. Existing omitted/`wait_ms=0` calls remain backward compatible.--Use this sequence after an MSO MCP change:--```mermaid-flowchart LR- C[Deploy new MSO] --> S[Check Settings → MCP signature]- S --> R[Refresh/recreate ChatGPT MCP app and Scan Tools]- R --> V[Verify expected actions in ChatGPT]- V --> A[Mark ChatGPT refreshed in MSO Settings]+projects_list+ ↓+project_capabilities+ ↓+project_mcp_tools(project, server) # exec: initializing project MCP executes project code+ ↓+project_mcp_call(project, server, tool, arguments)```-**Mark ChatGPT refreshed** is only an operator acknowledgement stored by MSO. It does not-reach into ChatGPT and refresh anything by itself.--OpenAI's current beta controls differ by plan: a published Business custom app must be-recreated/republished to change tools or metadata, while Enterprise/Edu admins can use the-workspace **Refresh** / action-control flow to pull new or changed definitions. New actions-are not automatically enabled. Always follow the current workspace UI if OpenAI changes-this behaviour.--## 7. Conversation identity, durable context, and `workflow_id`--ChatGPT conversation state is not the OAuth token and is not the HTTP transport session.-For `tools/call`, MSO reads the host-provided `_meta["openai/session"]` when present, derives-a privacy-safe SHA-256 correlation value with the stable MCP client principal, and stores only-that digest. The raw opaque ChatGPT conversation id is never persisted or written to audit.-`Mcp-Session-Id` remains a compatibility fallback for older/generic clients; transport-id-rotation does not split a ChatGPT conversation when `openai/session` is available.--Each conversation receives its own durable MSO Agent session and therefore its own active-workflow/job ownership boundary. Learned successful recipes remain client-principal scoped, so-conversation B may benefit from a verified recipe learned in conversation A without being able-to finish/cancel A's live workflow. `agent_session_current`, `agent_sessions_list`,-`agent_session_resume`, `agent_session_note`, and `agent_session_rename` expose only safe MSO-operational context; they cannot recover ChatGPT's hidden transcript. Persistent `USER.md` /-`MEMORY.md` are frozen into each new session.--Durable session context has a provider-neutral estimated-token counter. The default compaction-threshold is **700,000 tokens**; compaction preserves a structured summary plus about **140,000-recent tokens**, and first writes a recursively redacted gzip backup. Archives default to-**30-day retention** and are pruned both after archival and at MSO boot. The CLI can continue a-ChatGPT/MCP session via `mso --resume <id-or-title>`; continuation is copy-on-resume rather than-two surfaces mutating one session file.--### Multi-step work and `workflow_id`--For a task needing several operational calls, ChatGPT should call `workflow_start` once.-The returned exact `workflow_id` is then included on later operational calls. Missing id =-a standalone call; an unknown id is refused.--```mermaid-flowchart TD- Q[User task] --> M{More than one operational call?}- M -->|No| O[Use smallest bounded tool]- M -->|Yes| W[workflow_start]- W --> I[carry exact workflow_id]- I --> T[bounded tools or one scoped exec batch]- T --> V[verify result independently]- V --> F{Completed?}- F -->|Yes| X[workflow_finish]- F -->|Abandoned/interrupted| C[workflow_cancel]-```--Successful runs can become redacted local recipes. MSO never stores raw file bodies,-`fs_write.content`, bearer tokens, browser credentials or secret-looking command payloads-in workflow memory.--## 8. ChatGPT file/image → VPS bridge--`fs_upload_file` is intentionally ChatGPT-aware through MCP metadata-`openai/fileParams`. The normal flow is:--```mermaid-flowchart LR- G[ChatGPT creates/receives image or file] --> F[ChatGPT file reference]- F --> U[fs_upload_file]- U --> D[download temporary OpenAI HTTPS URL]- D --> V[revalidate host + redirects + MIME + size]- V --> J[OS_FS_WRITE_ROOTS + credential/path jail]- J --> W[write file]- W --> R[return path + bytes + SHA-256]-```--Current guardrails:--- write scope is required;-- maximum 20 MiB, enforced while streaming even without a trustworthy `Content-Length`;-- PNG, WebP, JPEG or generic octet-stream only;-- response MIME is allowlisted; PNG/JPEG/WebP bytes must match their declared signature;-- temporary URL must be from an allowed OpenAI content/storage host;-- up to three redirects, and each redirect target is revalidated;-- destination still has to be inside `OS_FS_WRITE_ROOTS` and pass the credential/path jail;-- filename is sanitized and the write uses an exclusive random temporary file plus atomic rename;-- transferred bytes are never executed automatically by MSO;-- an existing same-name file can be replaced, so treat this as a write/destructive action;-- result includes byte count and SHA-256.--MSO does **not** provide a second image generator. Generate with ChatGPT's native image-capability, then use this bridge to move the result into the VPS when needed.--## 9. Visual proof without arbitrary browser access--`screen_capture` captures only the authenticated MSO UI. It cannot be pointed at an-arbitrary URL. It supports macOS, Windows or Dashboard shells, 900–1920 px width and-600–1200 px height.--The call returns the MCP image directly plus a session-gated temporary preview/download-link. The link expires after 15 minutes or 5 authenticated downloads, whichever comes-first. This is intended for visual verification while avoiding a general read-token web-exfiltration primitive.--Camoufox is a separate capability. `browser_status` reveals only installed/running/autostart-state. The VNC password, logged-in profile and cookies are deliberately never returned to-an MCP client.--## 10. Project-aware tools+`project_mcp_tools` starts/connects only the explicitly selected project server and returns its tool schemas on demand. `project_mcp_call` executes one exact dynamic tool. Those dynamic names remain data and never change MSO's global toolset hash or ChatGPT scan snapshot.-`projects_list` discovers validated projects across configured containers. Scans are-bounded and may return a continuation cursor; never interpret a truncated scan as "the-project does not exist".+Supported KISS bridge modes:-`project_capabilities` can report:+- **stdio project MCP** — fixed command/argv from the project's `.mcp.json`, no shell; cwd must stay inside the selected project; child environment starts from MSO's credential-scrubbed environment plus only project-declared env;+- **remote HTTP MCP** — guarded HTTPS transport with DNS-rebinding/SSRF checks and bounded responses; static project-config headers stay server-side;+- **project OAuth MCP** — reported as `auth=oauth` but fails closed unless that project has an explicit server-side authorization configuration. MSO never copies, invents or exposes another project's OAuth credential implicitly.-- `.mcp.json` **presence only** — contents may contain credential wiring and are never- returned; MSO does not auto-connect arbitrary project MCP servers;-- `.mso/functions.json` — public schemas for a version-1 project function manifest.+Project `.mso/functions.json` remains a separate generic seam: `project_capabilities` returns public function schemas and `project_function_call` executes one fixed-argv function at exec scope.-A function manifest can declare at most 32 functions. Functions use fixed argv (at most 16-strings), a maximum 30-second timeout, and receive caller JSON on stdin. User values are not-interpolated into a shell command. `project_function_call` always requires `exec` scope,-even when a project function is named "read".+## Local Agent two-way ChatGPT sessions-## 11. Four credentials people commonly confuse+Each ChatGPT conversation is bound to a separate durable MSO AgentSession using a privacy-safe hash of the host conversation id. Raw ChatGPT conversation ids are not persisted.-```mermaid-flowchart TB- S[MSO browser session cookie] -->|human UI| UI[MSO web app]- B[MCP bearer token] -->|ChatGPT permission to MSO tools| MCP[/mcp]- K[BYOK API key] -->|Alfa model inference| API[Model provider API]- C[Alfa openai-codex OAuth] -->|Alfa model inference| COD[ChatGPT Codex backend]-```--| Credential | Purpose | Does not grant |-|---|---|---|-| MSO session cookie | human browser access | MCP access by itself |-| MCP bearer | external client access to scoped MSO tools | an Alfa model credential |-| BYOK provider API key | Alfa inference | permission for ChatGPT to operate MSO |-| Alfa `openai-codex` OAuth | Alfa inference via ChatGPT subscription backend | MSO MCP scope |+The compact profile includes:-Authorizing the ChatGPT MCP app therefore does **not** automatically configure Alfa, and-"Sign in with OpenAI" under Alfa provider settings is not the ChatGPT plugin setup.--## 12. Security model+- `local_agents_list`+- `local_agent_message_send`+- `local_agent_inbox`+- `local_agent_reply`+- `local_agent_request_wait`-- Connect only an MSO server you own and trust.-- Start with `read` unless the workflow actually needs host changes.-- `write` can change/delete files and control bounded managed apps.-- `exec` is effectively a remote shell as the MSO Linux user.-- Prompt injection still matters: data read from files/logs can influence the model. Scope- is the server-side boundary that prevents a read-only token from turning that influence- into a write/exec.-- Tool inputs/results used in a ChatGPT conversation are processed by ChatGPT according to- the user's/workspace's OpenAI data controls; do not assume an MCP call stays on the VPS.-- Revoke old tokens from Settings → MCP. Tokens also expire after 90 days.-- Do not publish the MSO bearer, OAuth store, browser profile or `~/.mso` contents.+`local_agent_inbox(wait_ms=1..20000)` keeps only the current foreground MCP request open, registers the existing in-process Local Agent receiver, and returns early when another same-principal session sends a message. Durable file-backed mailbox state remains authoritative and closes the read→subscribe race. There is no DB, webhook, broker, WebSocket or spawned worker in this path.-OpenAI may additionally ask for confirmation or block some write actions based on the-ChatGPT app/workspace permission model. That is an additional client control; it does not-replace MSO's own scope checks.+A completely idle ChatGPT conversation still cannot be awakened by a remote MCP server. Its durable mail is delivered on its next MCP call. `local_agent_request` and `agent_subagent_run` remain full-catalog worker primitives and are intentionally not part of the compact ChatGPT profile.-## 13. Troubleshooting+## OAuth contract-### ChatGPT cannot discover the server+For origin `https://mso.example.com`:-- the endpoint must be remote/reachable from ChatGPT;-- use HTTPS;-- verify `OS_MCP_ENABLED=1` is present in the **running** service;-- `GET /mcp` should return the public descriptor instead of 404.+| Purpose | URL |+|---|---|+| MCP server/resource | `https://mso.example.com/mcp` |+| OAuth authorization | `https://mso.example.com/oauth/authorize` |+| OAuth token | `https://mso.example.com/oauth/token` |+| Dynamic client registration | `https://mso.example.com/oauth/register` |+| Authorization-server metadata | `https://mso.example.com/.well-known/oauth-authorization-server` |+| Protected-resource metadata | `https://mso.example.com/.well-known/oauth-protected-resource` |-### OAuth page opens but cannot authorize+MSO OAuth uses authorization code + PKCE S256 for public clients and supports rotating refresh tokens. New OAuth grants are bound to the exact `resource=https://<origin>/mcp` throughout authorization, code exchange, refresh and MCP bearer validation.-The authorization page is a real MSO browser page. Log into MSO from an approved device,-then retry the connector authorization. Check the requested scope against-`OS_MCP_MAX_SCOPE`.+New OAuth access tokens are short-lived (1 hour); refresh credentials rotate and expire after 90 days. Authorization codes are single-use and expire after 60 seconds. Access tokens, refresh tokens and authorization codes are stored only as SHA-256 hashes. Revoking one access token revokes its OAuth grant family, including refresh credentials.-### ChatGPT sees old/missing tools after a deploy+Legacy MSO bearers minted before resource binding remain accepted during migration until they expire/revoke. A fresh ChatGPT reauthorization receives the new resource-bound/refreshable contract.-Compare the toolset signature in Settings → MCP or `GET /mcp`, then refresh/recreate the-ChatGPT app and run **Scan Tools**. Only after ChatGPT shows the new actions should you mark-it refreshed in MSO Settings.+## Streamable HTTP contract-### A tool is visible but returns a scope error+MSO uses Streamable HTTP JSON-RPC over `POST /mcp`.-The token was authorized at a lower tier than that action requires. Reauthorize deliberately-at the needed scope; do not raise the whole server ceiling only to silence the error.+- `initialize` negotiates a supported MCP protocol version;+- subsequent requests may send `MCP-Protocol-Version`; unsupported versions fail before dispatch;+- the optional `GET /mcp` SSE listener is **not implemented**, so `Accept: text/event-stream` returns `405 Method Not Allowed`, as required when a Streamable HTTP server does not provide that listener;+- non-SSE `GET /mcp` remains an operator diagnostics endpoint showing the full and ChatGPT toolset signatures;+- browser `Origin` validation remains enabled to prevent DNS-rebinding access to local MCP listeners.-### `fs_upload_file` fails+## Setup / refresh sequence-Check destination write roots, file size/type, and whether ChatGPT supplied a current file-reference. Temporary OpenAI URLs expire; retry from the actual attached/generated file-rather than pasting an arbitrary public URL.+1. Deploy MSO over reachable HTTPS and enable MCP (`OS_MCP_ENABLED=1`).+2. Set the maximum bearer scope intentionally with `OS_MCP_MAX_SCOPE=read|write|exec`.+3. In ChatGPT Developer Mode / Apps, create or edit the MSO custom MCP app using the `/mcp` URL.+4. Choose OAuth and complete the MSO consent flow on an approved owner device.+5. Select the lowest useful MSO tier.+6. Run **Scan Tools / Refresh** in ChatGPT.+7. Verify that the action snapshot corresponds to the 29-tool compact profile above.+8. Start a new chat when testing a newly scanned draft/action snapshot.-### Project/skill seems missing+After a schema/profile change, changing production code alone does not replace ChatGPT's frozen action snapshot. Refresh/re-scan (or recreate/republish where the workspace UI requires it) after deployment.-Inspect the returned scan report. If `truncated:true`, follow its continuation cursor.-Project and skill discovery are deliberately bounded.+## Troubleshooting Scan Tools-## 14. Deeper reference+If Scan Tools fails, validate in this order:-- `docs/MCP.md` — protocol, OAuth store, tool internals, project/skill discovery, rate limits-- `docs/ARCHITECTURE.md` — whole-system boundaries-- `docs/CONNECTORS-GATEWAY-INTEGRATION.md` — cross-repo action-name contract-- `docs/MODELS-INTEGRATION.md` — Alfa model credentials and the separate Codex OAuth flow-- `SECURITY.md` — deployment/security posture+1. both OAuth `.well-known` documents return `200` over public HTTPS;+2. authorization redirects back with matching `state` and `iss`;+3. authorization/token requests preserve the exact `/mcp` `resource`;+4. the access token is accepted by `POST /mcp`;+5. `initialize` and scoped `tools/list` succeed;+6. every tool has title + required safety annotations + matching security schemes;+7. the ChatGPT descriptor set stays under the in-repo budget gate;+8. `GET /mcp` with `Accept:text/event-stream` returns 405 rather than JSON pretending to be an SSE stream;+9. the ChatGPT app was actually refreshed/re-scanned after the latest toolset signature changed.+The live diagnostic `GET /mcp` returns both `toolset` (full MSO) and `chatgptToolset` signatures so profile drift is visible without exposing credentials.-### Bounded asynchronous execution+## Security boundaries-`exec_job_start` starts a client/workflow-bound command that may run up to 20 minutes; `exec_job_status` reads its bounded output and final exit state; `exec_job_cancel` stops a still-running job. Use this trio for test/build pipelines instead of wrapping `exec_run` in host-specific background-process plumbing.+- MCP tokens never grant SSH/Linux credentials; they authorize MSO tools only.+- `exec_run`, project functions and dynamic project MCP calls require exec scope.+- Project MCP config/env/header values are never model-visible.+- MSO credentials are scrubbed before child project processes; project-declared env is a project-owned boundary.+- File operations retain MSO path-root and credential-path guards.+- Remote HTTP project MCP calls retain MSO's public-address / SSRF / DNS-rebinding guard.+- Tool hiding is not a substitute for scope checks; list-time and call-time scope enforcement both remain mandatory.+- Hidden ChatGPT transcript, private chain-of-thought and credentials are never copied into Local Agent/project MCP messages.diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.mddeleted file mode 100644index d1135f44..00000000--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md+++ /dev/null@@ -1,134 +0,0 @@-# MSO ↔ Connectors Gateway contract--> **Current MSO-side reference.** This file pins what **MSO** exposes. A gateway repository-> can evolve independently, so do not claim its mapping count is current without checking-> that repository at the time of the change.--<!-- mcp-toolset: server=1.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->--MSO currently exposes MCP server **1.6.0**, toolset **2026.09.03.2**: **71 transport tools** total; **70 model/operator tools**-(34 read, 24 write, 12 exec) plus app-only `workflow_status`. `GET /mcp` exposes the live names, version/hash and scoped-manifest and is the machine-readable parity source.--## Local collaboration additions--Toolset `2026.09.02.7` tracks `local_agents_list`, `local_agent_message_send`, `local_agent_reply`, `local_agent_request_wait`, `local_agent_inbox`, `local_agent_request`, and `agent_subagent_run`. A gateway should preserve these literal names if it chooses to expose them. The six `local_agent_*`/`local_agents_list` tools address durable same-principal MSO sessions; `agent_subagent_run` is a foreground same-session worker and must not be modeled as a remote A2A registration or long-lived peer.--Toolset `2026.09.02.8` introduced RASMIC's `project_memory_search`, `project_memory_upsert`, and `project_script_run`; toolset `2026.09.02.9` keeps those three names stable while extending `project_memory_search` with `search | related | timeline` views and the catalog-first runtime. A gateway may expose these literal names, but must preserve their MSO scopes and must not reinterpret repo-local `.agent` records as gateway-owned/global memory.--Toolset `2026.09.03.2` keeps Local Agent names/scopes stable and extends only `local_agent_inbox` with optional `wait_ms` (0-20000). A positive wait is a bounded foreground receive operation on the existing MCP request; it is not a webhook, background subscriber, remote agent spawn, or new transport.--## Why this contract matters--Connector/gateway manifests commonly bind an action to an MSO tool with a literal upstream-name such as:--```json-{ "id": "mso.fs.delete", "x-upstream": "fs_delete" }-```--Renaming/removing an MSO tool can therefore break a gateway without a TypeScript error in-either repository. `lib/mcp/parity.test.ts` covers MSO MCP ↔ Alfa intent, not an external-gateway's literal strings.--Before changing an MCP tool name:--1. inspect the live `GET /mcp` manifest;-2. search the gateway's connector manifest for the exact upstream string;-3. decide whether the external action is renamed, migrated or intentionally dropped;-4. update both repos in a coordinated release if necessary;-5. refresh/re-scan connected ChatGPT/custom apps because action definitions are cached.--## Current MSO catalog--### Read (34 model/operator)--`a2a_agent_discover`, `a2a_agents_list`, `a2a_task_get`, `agent_memory_read`, `agent_memory_search`, `agent_session_current`, `agent_session_resume`, `agent_sessions_list`, `apps_list`, `apps_logs`, `browser_status`, `cloudflare_zones_list`, `dokploy_projects_list`, `exec_job_status`, `fs_list`, `fs_read`, `fs_search`, `fs_usage`, `infra_provider_doctor`, `infra_providers_list`, `local_agent_inbox`, `local_agent_request_wait`, `local_agents_list`, `project_capabilities`, `project_memory_search`, `projects_list`, `read_pipeline`, `screen_capture`, `skills_list`, `skills_read`, `skills_search`, `sys_processes`, `sys_stats`, `tool_forge_candidates`.--### Write (24 beyond read)--`a2a_agent_register`, `a2a_agent_remove`, `agent_memory_forget`, `agent_memory_remember`, `agent_session_note`, `agent_session_rename`, `apps_power`, `cloudflare_dns_upsert`, `dokploy_project_ensure`, `fs_copy`, `fs_delete`, `fs_mkdir`, `fs_move`, `fs_upload_file`, `fs_write`, `hostinger_dns_upsert`, `local_agent_message_send`, `local_agent_reply`, `project_memory_upsert`, `project_script_run`, `tool_forge_propose`, `workflow_cancel`, `workflow_finish`, `workflow_start`.--### Exec (12 beyond write)--`a2a_handoff`, `a2a_message_send`, `a2a_task_cancel`, `agent_subagent_run`, `browser_power`, `exec_job_cancel`, `exec_job_start`, `exec_run`, `local_agent_request`, `project_function_call`, `tool_forge_evaluate`, `tool_forge_promote`.--### App-only bridge (1)--`workflow_status` is exposed for the MCP Apps progress widget and is not part of the model/operator action catalog.--A2A adds eight stable generic MCP action names rather than one action per peer. A gateway should pass-the registered alias/id or public Agent Card URL as the `target`; it must not synthesize hidden-conversation context. Current MSO supports anonymous outbound peers plus private API-key/Bearer/OAuth2-credential profiles, streaming task operations, and an optional authenticated inbound A2A server when an-explicit public HTTPS origin exists. Full trust/credential semantics live in [`A2A.md`](./A2A.md).--## Scope and workflow compatibility--The MSO scope ladder (`read < write < exec`) is the server permission boundary. A gateway-may add stricter approvals/policy, but it must not assume that hiding an action changes the-MSO bearer scope.--Operational MCP tools also accept optional `workflow_id`. A gateway that does not expose-that field can still call the tools, but those calls are standalone and will not join an-MSO learned workflow. For multi-step orchestration, expose the workflow trio and propagate-the exact id returned by `workflow_start`.---`read_pipeline` is one stable global read action rather than a gateway-generated action per child call. Gateways should forward its declarative JSON contract unchanged: the server permits only eligible read-only tools, inherits the caller session/workflow, keeps each child's normal rate limit and host guard, and returns bounded transformed evidence. It must never be translated into arbitrary script execution or used as a proxy for write/exec actions.--Tool Forge remains a stable global action family as well: gateways should expose the four generic `tool_forge_*` names, never synthesize one action per generated candidate. Candidate ids are data. Executable evaluation is server-side in the dedicated local Docker sandbox, and promotion remains exec-scope with exact confirmation.--## Project functions are data, not dynamic MCP names--A project may publish `.mso/functions.json`. The gateway does not need a new MSO action for-each project function: it calls `project_capabilities` to see validated public schemas and-`project_function_call` to run one at exec scope. This is intentional so switching projects-does not change the global MCP tool prefix.--`.mcp.json` is different: MSO reports presence only and never returns its contents or-implicitly connects to an arbitrary project's MCP server.--## ChatGPT file parameters--`fs_upload_file` uses OpenAI MCP metadata `openai/fileParams` on its top-level `file`-parameter. A generic gateway that cannot preserve that metadata may still proxy ordinary-MSO JSON actions, but it cannot manufacture the ChatGPT-provided temporary file object from-a string path. Preserve metadata if file import parity is required.--## Security-sensitive mapped actions--Treat these as particularly important in any external approval layer:--- `fs_delete` / `fs_write` / `fs_upload_file` — host data mutation;-- `apps_power` — bounded daemon control and state backup;-- `exec_run` — host shell as the MSO user;-- `browser_power` — starts a browser profile with live logged-in sessions;-- `project_function_call` — executes project-owned fixed argv and is always exec-scope;-- `tool_forge_evaluate` / `tool_forge_promote` — sandbox-evaluate and explicitly promote inert learned-workflow candidates; promotion requires a fresh passing evaluation and literal confirmation;-- `dokploy_project_ensure` / `cloudflare_dns_upsert` / `hostinger_dns_upsert` — mutate external infrastructure with provider credentials kept server-side; Hostinger receives only the requested name/type RR-set (`overwrite:true`), never an MSO-generated full-zone snapshot.--External policy supplements MSO's own scope/path/audit/rate-limit checks; it does not replace-them.--## Removed names--Provider-backed MSO image generation was removed on 2026-08-20. Do not map-`image_generation_status` or `image_generate`. A GPT/ChatGPT client should use its native-image capability and, when needed, transfer the resulting file through `fs_upload_file`.--## Verification--For an integration update, compare the gateway's literal upstream names with:--```text-GET https://<mso-origin>/mcp-```--Then run MSO's MCP parity/global-tool tests and the gateway's own connector-contract tests.-Do not infer external-gateway parity merely because MSO's internal tests are green.---### Bounded asynchronous execution--`exec_job_start` starts a client/workflow-bound command that may run up to 20 minutes; `exec_job_status` reads its bounded output and final exit state; `exec_job_cancel` stops a still-running job. Use this trio for test/build pipelines instead of wrapping `exec_run` in host-specific background-process plumbing.diff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.mdindex ffdafda6..2dd07f0c 100644--- a/docs/INFRASTRUCTURE-PROVIDERS.md+++ b/docs/INFRASTRUCTURE-PROVIDERS.md@@ -5,9 +5,9 @@> never part of the model prompt or MCP tool arguments.MSO now owns the deployment-assistance pattern that previously lived separately in-`rahmanef63/si-coder-agent`: provider discovery, live API verification, bounded Dokploy+a prior standalone provider tool: provider discovery, live API verification, bounded Dokployoperations, and DNS automation. The implementation is native MSO code rather than a nested-`si-coder-agent` runtime, so the browser features, CLI, terminal agent and MCP surface share+another runtime, so the browser features, CLI, terminal agent and MCP surface shareone catalog and one security/audit model.## 1. Terminal entry points@@ -160,7 +160,7 @@ DNS automation is deliberately per-record:- Cloudflare proxying defaults **off** and is enabled only when `proxied=true` was explicitlyrequested.-This preserves the safest part of the `si-coder-agent` Cloudflare pattern while putting it+This preserves the safest part of the standalone Cloudflare automation pattern while putting itbehind MSO scope, approval, audit and workflow controls.## 6. Hostingerdiff --git a/docs/MCP-FEATURE-IMPLEMENTATION.md b/docs/MCP-FEATURE-IMPLEMENTATION.mdindex c31df679..20f309b7 100644--- a/docs/MCP-FEATURE-IMPLEMENTATION.md+++ b/docs/MCP-FEATURE-IMPLEMENTATION.md@@ -67,7 +67,7 @@ A public tool is not only a function. Its release contract spans all of these su| Limits | Timeouts, rate/size caps, allowed roots, pagination, and continuation semantics || Parity | Alfa/MCP coverage or an explicit documented reason for MCP-only behavior || Toolset | Schema-derived version/hash/count visible in descriptor, initialize, list, and Settings |-| External clients | connectors-gateway literals and cached ChatGPT/Claude/Cursor actions |+| External clients | cached ChatGPT/Claude/Cursor/downstream client actions || Documentation | `MCP.md`, relevant runbook, progress rationale, and refresh instructions |Implementation sequence:@@ -79,7 +79,7 @@ Implementation sequence:changes deliberately.4. Test schema validation, scope visibility, call-time refusal, limits, handler response, audit,and failure shape.-5. Run Alfa/MCP parity tests and inspect connectors-gateway before changing a public name.+5. Run Alfa/MCP parity tests and treat every public MSO tool name/schema as a compatibility contract before changing it.6. Advance toolset metadata when the public schema/description/scope/annotation changes. Verifythe live `GET /mcp` signature rather than relying on a source constant alone.7. Refresh or recreate the external MCP client action snapshot. Marking MSO's local@@ -107,15 +107,17 @@ A `SKILL.md` is routing and reusable workflow policy, not executable code and no## 5. Project-specific function capabilities-Project function names remain **data**, not dynamic additions to the MCP catalog. Preserve the-stable pair:+Project function and project MCP tool names remain **data**, not dynamic additions to the MSO global catalog. Preserve the stable generic seams:-- `project_capabilities` discovers the project's declared functions and constraints;-- `project_function_call` executes one declared function at `exec` scope.+- `project_capabilities` discovers safe function schemas and project MCP server aliases;+- `project_function_call` executes one declared fixed-argv function at `exec` scope;+- `project_mcp_tools` initializes one explicitly selected project MCP and discovers its dynamic tools at `exec` scope;+- `project_mcp_call` executes one exact dynamic project MCP tool at `exec` scope.++Never expose `.mcp.json` contents/env/headers/credentials or synthesize one MSO global tool per project MCP tool.When adding a project capability, validate the project's `.mso/functions.json`, keep execution-inside its declared working directory/argument contract, and test discovery plus refusal. Do not-create one global MCP tool per project function; that destabilizes the cached catalog and tool+inside its declared working directory/argument contract, and test discovery plus refusal. Do not create one global MCP tool per project function or project MCP tool; that destabilizes cached client catalogs and toolprefix for every client.## 6. Limits that commonly masquerade as code bugsdiff --git a/docs/MCP.md b/docs/MCP.mdindex b4353d45..203afa30 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -48,12 +48,10 @@ required by the MCP transport security guidance to prevent DNS rebinding. Servernormally omit `Origin`; browser-origin traffic is accepted only from the configured public origin orfrom a loopback browser talking to the loopback cockpit.-MSO supports OAuth 2.1-style authorization-code flow with PKCE S256 and public clients-(token endpoint auth `none`). The current authorization metadata advertises only-`authorization_code`; there is no refresh-token grant. The authorization page is a normal-signed-in MSO page: an approved human browser session converts into a scoped MCP bearer; the-consent page is not a second login mechanism. Expired/revoked bearers therefore require a-new authorization flow.++MSO uses Streamable HTTP JSON-RPC on `POST /mcp`. `initialize` negotiates supported protocol versions and subsequent `MCP-Protocol-Version` headers are validated. MSO does not expose an SSE listener; therefore `GET /mcp` with `Accept: text/event-stream` returns **405** instead of a JSON response pretending to be an event stream. A non-SSE GET remains a bounded operator diagnostic containing full/profile toolset signatures.++MSO supports OAuth 2.1-style authorization-code flow with PKCE S256 and public clients (token endpoint auth `none`) plus rotating `refresh_token` grants. New OAuth codes/access/refresh grants are bound to the exact MCP `resource=https://<origin>/mcp`; the authorization response also returns `iss`. Access tokens default to one hour, refresh credentials rotate and expire after 90 days, and raw codes/tokens are never stored. Legacy pre-resource bearers remain accepted only as a migration path until expiry/revocation.For ChatGPT, the connection is a **custom MCP app** created in Developer Mode. OpenAI currentlyshows more than one setup surface: its Developer Mode guide uses Apps → Create, while ChatGPT Work@@ -77,7 +75,7 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe|---|---|| `read` | `a2a_agent_discover` `a2a_agents_list` `a2a_task_get` `agent_memory_read` `agent_memory_search` `agent_session_current` `agent_session_resume` `agent_sessions_list` `apps_list` `apps_logs` `browser_status` `cloudflare_zones_list` `dokploy_projects_list` `exec_job_status` `fs_list` `fs_read` `fs_search` `fs_usage` `infra_provider_doctor` `infra_providers_list` `local_agent_inbox` `local_agent_request_wait` `local_agents_list` `project_capabilities` `project_memory_search` `projects_list` `read_pipeline` `screen_capture` `skills_list` `skills_read` `skills_search` `sys_processes` `sys_stats` `tool_forge_candidates` || `write` | + `a2a_agent_register` `a2a_agent_remove` `agent_memory_forget` `agent_memory_remember` `agent_session_note` `agent_session_rename` `apps_power` `cloudflare_dns_upsert` `dokploy_project_ensure` `fs_copy` `fs_delete` `fs_mkdir` `fs_move` `fs_upload_file` `fs_write` `hostinger_dns_upsert` `local_agent_message_send` `local_agent_reply` `project_memory_upsert` `project_script_run` `tool_forge_propose` `workflow_cancel` `workflow_finish` `workflow_start` |-| `exec` | + `a2a_handoff` `a2a_message_send` `a2a_task_cancel` `agent_subagent_run` `browser_power` `exec_job_cancel` `exec_job_start` `exec_run` `local_agent_request` `project_function_call` `tool_forge_evaluate` `tool_forge_promote` |+| `exec` | + `a2a_handoff` `a2a_message_send` `a2a_task_cancel` `agent_subagent_run` `browser_power` `exec_job_cancel` `exec_job_start` `exec_run` `local_agent_request` `project_function_call` `project_mcp_call` `project_mcp_tools` `tool_forge_evaluate` `tool_forge_promote` |Alfa — the in-app assistant — overlaps the same host capabilities under dot.case names,and `lib/mcp/parity.test.ts` fails if one surface gains a tool the other lacks@@ -97,11 +95,7 @@ global by design, and withholding it from the connector was scoping nobody chosetwo catalogs stay separate on purpose (different transport and guard) but may notdrift by accident.-**These tool names are also a cross-repo contract.** `rahmanef63/connectors-gateway`-registered mso as a connector on 2026-08-17 and historically pinned a subset of these names as literal strings; a-rename here can break that mapping with no error in either repo, and `parity.test.ts` does not cover-that axis. Verify the gateway repository before changing a tool name. See [`CONNECTORS-GATEWAY-INTEGRATION.md`](./CONNECTORS-GATEWAY-INTEGRATION.md)-before renaming or removing a tool.+**Global MCP names belong to MSO only.** Project-specific functions and project MCP tools are discovered as data through the generic `project_capabilities`, `project_mcp_tools`, `project_mcp_call`, and `project_function_call` seams. A project may add or remove its own MCP tools without changing MSO's global tool list or ChatGPT scan snapshot.The tiering is about blast radius, not about which layer the call lands in.`apps_logs` reads a daemon's journal, so "why is hermes down?" is answerable from@@ -112,11 +106,7 @@ 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 — aclient that calls a tool it was never shown still gets refused.-**The scope ladder is the ONLY thing that narrows the catalog.** An `exec` token sees-and can call every public tool; `read` and `write` are strict prefixes of it. There is-no per-project, per-agent, per-workflow or per-client tool filter, and there must not-be one — which tools EXIST is not a security control here, the ladder plus `lib/host`'s-path jail and command filter are. Every operational tool carries an OPTIONAL+**Scope remains the permission boundary, while a client profile may advertise a smaller static catalog for compatibility/context budget.** The ChatGPT profile is fail-closed at both list and call time; it never grants anything the token scope does not already allow. Project-specific capabilities remain dynamic data rather than global names. `lib/host` path/command guards remain authoritative for every operation. Every operational tool carries an OPTIONAL`workflow_id`: it correlates steps, it never gates a capability. `lib/mcp/global-tools.test.ts`pins all of this, including that a token's visible list matches its callable set exactly.@@ -126,16 +116,19 @@ 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.6.0 version=2026.09.03.2 tools=70 read=34 write=24 exec=12 -->+<!-- mcp-toolset: server=1.7.0 version=2026.09.03.3 tools=72 read=34 write=24 exec=14 -->-Current transport catalog: **71 tools**, server `1.6.0` / toolset `2026.09.03.2`.-The model/operator catalog is **69 tools** (33 read, 24 write, 12 exec); `workflow_status` is the-one app-only MCP Apps bridge used by the progress widget and is documented separately.+Current full transport catalog: **73 tools**, server `1.7.0` / toolset `2026.09.03.3`.+The model/operator catalog is **72 tools** (34 read, 24 write, 14 exec); `workflow_status` is the one app-only MCP Apps bridge. ChatGPT receives a smaller client profile rather than this full set; see [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md).`agent_memory_search` is the typed-memory retrieval surface. It resolves semantic/episodic/procedural claims at an optional point in time, returns confidence/provenance and competing effective claims, and can expose superseded/retracted history when explicitly requested. `agent_memory_remember` remains the write surface and now accepts typed metadata; raw ChatGPT conversation ids are never stored as provenance.-Session/memory tools add durable conversation context without creating-dynamic per-project tool names; `project_capabilities` and `project_function_call` remain the-stable project-automation seam.+Session/memory tools add durable conversation context without creating dynamic per-project global names. Project functions use `project_capabilities` / `project_function_call`; project MCP servers use `project_capabilities` / `project_mcp_tools` / `project_mcp_call`. In both cases project-specific names remain data, not entries in MSO `tools/list`.++### Advertised metadata and client profiles++`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.### RASMIC repo-local orchestration memory@@ -178,13 +171,12 @@ Skill candidates contain only deterministic redacted tool guidance. Project-func## Opt-in project MCP/function capabilities-MSO itself stays generic. A project opts into extra automation by placing files inside-its own validated project directory:+MSO itself stays generic. A project may opt into capabilities inside its own validated directory:++- `.mcp.json` — parsed privately and exposed only as sanitized server alias / transport / auth-class metadata. `project_mcp_tools` initializes one explicitly selected server and returns its dynamic tool schemas; `project_mcp_call` invokes one exact dynamic tool. Config contents, env values, headers, OAuth details and credentials are never returned, and project tool names never join the global MSO catalog.+- `.mso/functions.json` — a bounded manifest of project-owned fixed-argv functions executed only through `project_function_call`.-- `.mcp.json` — MSO reports only that the MCP config exists. It never returns the file- contents because MCP configs commonly contain env/credential wiring. MSO does not- automatically connect to arbitrary project MCP servers.-- `.mso/functions.json` — a bounded manifest of project-owned functions.+`project_mcp_tools` is exec scope even though it returns schemas because starting a stdio project MCP executes project code. Stdio uses no shell, enforces cwd containment, starts from MSO's credential-scrubbed child environment, and adds only project-declared env. Remote HTTP uses the existing HTTPS/SSRF/DNS-rebinding guard and bounded responses. A project MCP that declares OAuth but lacks explicit server-side authorization fails closed; MSO never imports or mints another project's credential implicitly.The manifest is versioned and intentionally uses **fixed argv**, not a shell template:@@ -213,10 +205,7 @@ into command arguments. The child receives the existing scrubbed environment, socredentials and provider tokens are not inherited. Projects without either file gain nonew behavior.-This shape preserves the global-tool invariant: MCP clients always see the same two MSO-tool names, while the project-specific function names are data returned after project-resolution. It also means adding a function to a project does not change MSO's toolset-hash or force a cold prompt-cache prefix.+This shape preserves the global-tool invariant: project-specific function and MCP tool names stay data behind stable generic MSO primitives. Adding/removing a project capability therefore does not rewrite the global MSO tool prefix or ChatGPT scan snapshot.For project callbacks that must enter a managed app (for example a signed webhook into aloopback-only agent), deployments may opt into `OS_PROJECT_INGRESS_ROUTES`. It defaultsdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex db897bf2..fc542844 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -2,6 +2,15 @@Running log of what shipped each phase. Newest at top.+## 2026-09-03 — MCP 1.7 ChatGPT compact profile + dynamic project MCP++- **ChatGPT scanner contract:** full MSO remains 73 transport tools / 72 model tools (34 read / 24 write / 14 exec + app-only `workflow_status`), while ChatGPT is client-profiled to **29 transport tools = 28 model tools (14 read / 8 write / 6 exec) + app-only bridge**. The profile is fail-closed at list and direct-call time, keeps only MSO-owned generic names, and regression-measures **31,811 descriptor bytes (~8k rough tokens)** with a 40 KiB total / 8 KiB per-tool guard.+- **Metadata SSOT:** every advertised tool is normalized through one descriptor layer with a human title, explicit `readOnlyHint` / `destructiveHint` / `openWorldHint`, optional idempotency, and matching top-level + `_meta.securitySchemes`. ChatGPT gets compact descriptions/schema descriptions without changing behavior or constraints.+- **Project MCP stays dynamic:** added generic exec-scope `project_mcp_tools` and `project_mcp_call`. `.mcp.json` stays private; `project_capabilities` exposes only server alias/transport/auth class, stdio runs without shell inside project cwd from a credential-scrubbed environment, remote HTTP uses SSRF/DNS-rebinding guards, and another project's OAuth is never copied/minted implicitly. Project-specific tool names never enter MSO `tools/list`.+- **OAuth/transport refresh hardening:** new OAuth grants bind `resource=<origin>/mcp`, return `iss`, issue one-hour access tokens plus rotating hashed refresh credentials, and revoke by grant family. Legacy bearers remain a migration path. Streamable HTTP validates `MCP-Protocol-Version`; the unsupported optional SSE GET listener now returns 405.+- **Open-source independence:** removed the cross-repository MCP contract document, sibling-repo CI fallback and current private-project examples. MSO's push gate always uses its own `bun run verify`; downstream integrations consume MSO's public contract, not vice versa.+- **Release verification:** targeted MCP/auth/project regression, TypeScript, docs and the full repository verify gate pass; lint remains 0 errors / 8 baseline max-lines warnings. Trivy high/critical, OSV dependencies, Gitleaks history, Semgrep OWASP/SAST and ShellCheck all pass on the staged candidate. The optional Codex Security AI component scan is recorded as **incomplete**, not PASS: the full-repo run hit the 20-minute executor cap and two high-effort targeted attempts hit their $3/$5 cost guards; both targeted partial reports contained 0 findings. Live ZAP remains a post-deploy check because scanning the previous production build would not validate this candidate.+## 2026-09-03 — Cognitive Runtime P6 expanded repo/recovery corpus- **Nine-scenario v2 corpus:** `bench:corpus` now adds objective `repo-debug`, `repo-migration`, and transactional `rollback` fixtures to the six P4/P5 scenarios. Each agent still receives semantically identical seeded state in a separate private 0700 tree; immutable issue/spec/test/validator files plus exact final-tree verification remain authority, and `policyObservationScope=scenario-tree` explicitly avoids whole-host sandbox claims.@@ -47,7 +56,7 @@ Running log of what shipped each phase. Newest at top.- **Full Markdown audit:** reviewed all 71 authored Markdown files in the repository, preserving dated release/audit/design evidence while correcting current-reference drift. Structural validation reports zero malformed fence/heading issues and all 125 relative Markdown links resolve.- **Current Agent docs:** synchronized `TESTING-HANDOFF`, Local Agents, install/provider guidance, troubleshooting, architecture and the documentation map with the shipped 1.12 identity-first composer, sectioned transcript, compact exact approval and recoverable `not_started | completed | uncertain` mutation semantics. Historical 1.8–1.11 release notes remain intact rather than being rewritten as if they were current instructions.- **MCP/A2A drift fixed:** at that 1.12 documentation checkpoint, references agreed on server `1.6.0`, toolset `2026.09.02.7`, 67 transport tools = 66 model/operator tools (32 read / 22 write / 12 exec) + app-only `workflow_status`. Stale 31/29/59/56-tool claims and obsolete anonymous-only A2A wording were removed from current docs; historical benchmark snapshots were relabeled as snapshots instead of live metrics.-- **Docs gate strengthened:** `check-docs.mjs` now verifies the MCP marker in architecture/operator docs and exact scope membership in `docs/MCP.md`, `docs/CHATGPT-PLUGIN.md`, and `docs/CONNECTORS-GATEWAY-INTEGRATION.md`, so a future tool addition cannot leave one human catalog silently stale.+- **Docs gate strengthened:** `check-docs.mjs` now verifies the MCP marker in architecture/operator docs and exact scope membership in `docs/MCP.md` and `docs/CHATGPT-PLUGIN.md`, so a future tool addition cannot leave one human catalog silently stale.- **Unused surface cleanup:** removed the dead `coreToolNames()` helper and stopped exporting Agent constants/helpers that are private implementation details while retaining every internally used behavior. No compatibility placeholder or public CLI/MCP capability was removed.## 2026-09-02 — MSO 1.12.0 sectioned Agent TUI + recoverable API failures@@ -240,7 +249,7 @@ at the same time: `~/projects/mso`/`origin/main` remains the release SSOT and pa## 2026-08-31 — MSO terminal agent + provider-backed deployment setup — SHIPPED-**Shipped milestone.** The release passed the repository/security gates and the live health endpoint returned the release build SHA before this status was promoted. The standalone deployment-assistance pattern from `rahmanef63/si-coder-agent` is now absorbed into MSO's own architecture instead of spawning a second agent runtime. Installed Hermes and its public CLI were used as interaction references only; MSO has original terminal artwork, its own tool catalog, and its existing auth/audit model.+**Shipped milestone.** The release passed the repository/security gates and the live health endpoint returned the release build SHA before this status was promoted. A previously standalone deployment-assistance pattern is now absorbed into MSO's own architecture instead of spawning a second agent runtime. Installed Hermes and its public CLI were used as interaction references only; MSO has original terminal artwork, its own tool catalog, and its existing auth/audit model.What changed:@@ -435,7 +444,7 @@ audit, isolated production build, an isolated clean-HOME/PATH install, and proteCodeQL/dependency/Gitleaks/Trivy/OSV/Semgrep checks.> **How to read this log:** it is the source of truth for **why/when work shipped**, not-> today's API/runbook. Phases 0–14 were built on **Convex self-hosted + a Control-Room+> today's API/runbook. Phases 0–14 were built on **Convex self-hosted + a legacy control-service> host-agent bridge**; that stack was removed in Phase 15 and later entries describe the> self-contained Next.js/`lib/host` architecture. For the current implementation start at> [`docs/README.md`](./README.md) and [`docs/ARCHITECTURE.md`](./ARCHITECTURE.md); keep old@@ -582,7 +591,7 @@ inside the same managed-feature iframe shell as Hermes/OpenClaw.9Router also no longer uses the generic Lucide Route placeholder. MSO copies the official`/app/public/icons/icon-512.svg` from the current 9Router Docker distribution into its localofficial-brand asset set and uses it in the shell, launcher, window and Details cards. The-`sc-all`, `sc-dokploy`, and legacy `si-coder` deployment guidance now records the same+legacy standalone deployment guidance now records the sameexisting-domain-first/public-IP-fallback contract so future automation does not recreate thisregression.@@ -1114,7 +1123,7 @@ marks a workflow Verified; standalone calls are merely Completed. Workflow intenproject 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+`mso-service-debug`. The MCP and external-integration documentation at that checkpoint treated the 21-toolruntime signature as the cross-client contract and records that the gateway still maps15 actions. New public `repo_*` or `job_*` names were deliberately not added in thisrelease: keeping the action catalog stable lets the refreshed connection benefitdiff --git a/docs/README.md b/docs/README.mdindex 9d92c4d7..142baa89 100644--- a/docs/README.md+++ b/docs/README.md@@ -36,7 +36,6 @@ evidence and review freshness. The repository quality gate runs both automatical| [`SUBAGENTS.md`](./SUBAGENTS.md) | Same-session foreground isolated worker lifecycle, context, tool authority and limits || [`MCP-FEATURE-IMPLEMENTATION.md`](./MCP-FEATURE-IMPLEMENTATION.md) | Stepwise reverse-engineering workflow for MCP tools, trusted skills and project capabilities || [`CHATGPT-PLUGIN.md`](./CHATGPT-PLUGIN.md) | ChatGPT custom MCP app setup, diagrams, scopes and file bridge |-| [`CONNECTORS-GATEWAY-INTEGRATION.md`](./CONNECTORS-GATEWAY-INTEGRATION.md) | MSO ↔ connectors-gateway action-name contract || [`MANAGED-APPS.md`](./MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, backup/restore and dashboard access boundary || [`HERMES-INTEGRATION.md`](./HERMES-INTEGRATION.md) | Hermes-specific integration behaviour || [`OPENCLAW-INTEGRATION.md`](./OPENCLAW-INTEGRATION.md) | OpenClaw-specific integration behaviour |diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.mdindex 7aec729c..2e83555a 100644--- a/docs/TESTING-HANDOFF.md+++ b/docs/TESTING-HANDOFF.md@@ -4,9 +4,10 @@ Update this file at the end of every manual or automated test session. Keep it f## Current status-The current deployed baseline is **MSO CLI 1.12.0** with toolset `2026.09.03.2`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.+The current release target is **MSO CLI 1.12.0**, MCP server `1.7.0`, toolset `2026.09.03.3`; use `mso --version` plus `/api/health` for the exact Git build because documentation-only release commits also advance that identity. The v1.10/v1.11 findings and the v1.12 sectioned-terminal/recoverable-error work below are resolved and retained as historical test evidence. Do not re-open a resolved finding from prose alone: reproduce it against the current build first. There is no known 1.12 release blocker in this handoff.Current verified behavior:+- MCP 1.7 release candidate: ChatGPT is fail-closed to a 29-tool compact MSO-only profile (~31.8 KiB descriptor JSON / ~8k rough tokens), full MSO remains 73 transport tools, and project-specific MCP names stay dynamic behind `project_mcp_tools` / `project_mcp_call`. OAuth resource binding + rotating refresh credentials, Streamable HTTP protocol handling, and legacy registered ChatGPT-client profile detection have focused regression coverage. Deterministic security gates (Trivy/OSV/Gitleaks/Semgrep/ShellCheck) pass; Codex Security AI scanning is explicitly incomplete because executor/cost guards stopped it, with 0 findings in the targeted partial reports.- P6 `mso-agent-quality-v2` expands the matched corpus to nine scenarios with repo-debug, schema migration, and transactional rollback. Final `openai-codex/gpt-5.6-terra` full run: MSO 9/9 task + 9/9 scenario-policy, Hermes 8/9 + 9/9; normalized tokens/attempt 16,683.4 vs 67,433.1 (~75.3% lower for MSO), p50 15,285 vs 23,294 ms, while MSO average latency was ~2.6% higher. The Hermes `multi-read` miss did not reproduce in a 3/3-vs-3/3 alternating-order follow-up, so it is not treated as a universal reliability claim. P6 also fixes over-broad manual-test routing, restores explicit exec validation for repo tasks, and prevents duplicate `workflow_start` inside long single-user turns. Cost remains non-comparable.- P5 provider-usage normalization preserves Codex/OpenAI cache/reasoning details without double counting, keeps unknown fields unknown, and proof-gates canonical token semantics. A full candidate MSO↔Hermes run on `openai-codex/gpt-5.6-terra` remained 6/6 task + 6/6 scenario-policy for both; token semantics are now comparable at 3,510.8 vs 59,743.2 normalized tokens/success, while cost semantics remain non-comparable. MSO's proof is `explicit-inclusive-contract`; Hermes is `exact-exclusive-cache-sum`.- P4 `bench:corpus` uses six seeded, per-agent isolated 0700 scratch scenarios, exact scenario-tree scoring (`policyObservationScope=scenario-tree`, not whole-host sandbox proof), and rotating scenario-major runner order. The reproduced full provider+model-matched MSO↔Hermes run on `openai-codex/gpt-5.6-terra` is 6/6 task + 6/6 scenario-observable policy for both; MSO measured 10,759.5 ms average / 10,646.5 ms p50 versus Hermes 14,624 ms / 14,304.5 ms. This is a bounded corpus tie-break, not an overall-product claim. Token/cost accounting remains explicitly non-comparable and is not a ranking input; OpenClaw is unranked until an equivalent model/provider path exists.@@ -28,7 +29,7 @@ Current verified behavior:```textYou are taking over MSO testing work in /home/rahman/projects/mso.-Read docs/TESTING-HANDOFF.md first. Current verified baseline: CLI 1.12.0, toolset 2026.09.03.2; resolve the exact live Git build from `mso --version`/`/api/health`. Preserve existing work and do not re-open resolved v1.10-v1.12 findings unless you can reproduce them against the current build.+Read docs/TESTING-HANDOFF.md first. Current verified source baseline: CLI 1.12.0, MCP server 1.7.0, toolset 2026.09.03.3; resolve the exact live Git build from `mso --version`/`/api/health`. Preserve existing work and do not re-open resolved v1.10-v1.12 findings unless you can reproduce them against the current build.For a new issue: record the exact reproduction, distinguish durable state from live receiver/process state, avoid duplicate write/exec retries when outcome is uncertain, add the smallest focused regression, run typecheck plus the relevant contract tests, then update this handoff with factual results.```@@ -65,6 +66,26 @@ Validation minimum: focused unit tests for success, offline target, absent subsc## Session log+### 2026-09-03 — ChatGPT MCP scanner/auth/project boundary hardening++**Goal**+- Make ChatGPT action refresh reliably scan a compact, standards-aligned MSO-only catalog while keeping full MCP capability for other clients.+- Keep every project-owned MCP tool/config/credential dynamic/private behind generic MSO primitives.++**Changed**+- ChatGPT client profile: 29 transport tools / 28 model actions + app-only `workflow_status`; direct calls to hidden full-catalog names fail closed.+- Descriptor normalization adds title, all required safety annotations and mirrored OAuth security schemes to every full/profile tool.+- Added `project_mcp_tools` + `project_mcp_call`; project `.mcp.json` never becomes global tool definitions.+- Added OAuth resource binding, `iss`, rotating refresh tokens, grant-family revocation, protocol-header validation and Streamable HTTP 405 behavior for the unimplemented SSE listener.+- Removed current cross-repository MCP contract/coupling and sibling-repo push-gate dependency.++**Verified so far**+- TypeScript: PASS after OAuth/project/profile changes.+- Focused OAuth/route/store/profile/project-MCP contract tests: PASS.+- ChatGPT descriptor metric: **29 tools / 31,811 bytes / ~7,953 rough tokens / 2,507 max tool bytes**.+- `node scripts/check-docs.mjs`: PASS at 72 model MCP tools + one app-only bridge.+- Full repository verify/build and live deployment verification are the remaining release gates for this session.+### 2026-09-03 — ChatGPT-session Local Agent foreground two-way MVP**Goal**diff --git a/frontend/slices/appshell/design/ios/design.md b/frontend/slices/appshell/design/ios/design.mdindex fad24bbc..543a1ce4 100644--- a/frontend/slices/appshell/design/ios/design.md+++ b/frontend/slices/appshell/design/ios/design.md@@ -1,6 +1,6 @@# iOS design.md-Source of truth: `rahmanef63/apple-os-shell/uploads/design.md` (Apple HIG/Liquid Glass reference, 2026).+Source of truth: the project Apple-platform design reference (Apple HIG/Liquid Glass reference, 2026).## Contract- Clarity, deference, depth. Content is solid; glass belongs to navigation/overlays, never content cards.diff --git a/frontend/slices/appshell/design/macos/design.md b/frontend/slices/appshell/design/macos/design.mdindex b4cffd10..ae9344fd 100644--- a/frontend/slices/appshell/design/macos/design.md+++ b/frontend/slices/appshell/design/macos/design.md@@ -1,6 +1,6 @@# macOS design.md-Source family: `rahmanef63/apple-os-shell/uploads/design.md`, macOS sections.+Source family: the project Apple-platform design reference, macOS sections.## Contract- Desktop-first, compact density, SF typography, translucent navigation/sidebar layers with solid content.diff --git a/frontend/slices/appshell/lib/mentions.test.ts b/frontend/slices/appshell/lib/mentions.test.tsindex 40746103..6851f8c9 100644--- a/frontend/slices/appshell/lib/mentions.test.ts+++ b/frontend/slices/appshell/lib/mentions.test.ts@@ -43,7 +43,7 @@ describe("@ opens for agents but not inside a word", () => {it("stays closed inside a word — an email types cleanly", () => {expect(at("mail rahman@gmail")).toBeNull();- expect(at("[email protected]")).toBeNull();+ expect(at("[email protected]")).toBeNull();});it("lowercases the query so matching is case-insensitive", () => {diff --git a/lib/agent/session-query.test.ts b/lib/agent/session-query.test.tsindex 26078307..81ffcc03 100644--- a/lib/agent/session-query.test.ts+++ b/lib/agent/session-query.test.ts@@ -31,8 +31,8 @@ describe("full-store agent session resolver", () => {});it("supports unique fuzzy titles but refuses ambiguous matches using human labels", () => {- const rows = [row(1, "Deploy Baton", "2026-09-01T12:00:00Z"), row(2, "Audit Baton", "2026-09-01T11:00:00Z")];- expect(chooseAgentSessionRecord(rows, "Deploy Bat").title).toBe("Deploy Baton");- expect(() => chooseAgentSessionRecord(rows, "Baton")).toThrow(/Deploy Baton.*Audit Baton|Audit Baton.*Deploy Baton/);+ const rows = [row(1, "Deploy Example Project", "2026-09-01T12:00:00Z"), row(2, "Audit Example Project", "2026-09-01T11:00:00Z")];+ expect(chooseAgentSessionRecord(rows, "Deploy Example").title).toBe("Deploy Example Project");+ expect(() => chooseAgentSessionRecord(rows, "Example Project")).toThrow(/Deploy Example Project.*Audit Example Project|Audit Example Project.*Deploy Example Project/);});});diff --git a/lib/agent/session-store.test.ts b/lib/agent/session-store.test.tsindex bffefbfe..e7d28c74 100644--- a/lib/agent/session-store.test.ts+++ b/lib/agent/session-store.test.ts@@ -84,8 +84,8 @@ describe("durable agent session context policy", () => {it("repairs the legacy CLI default that was incorrectly stored as a manual title", async () => {const session = await store.createAgentSession("principal:legacy-title", "cli", { title: "MSO Agent session", titleSource: "manual" });- const updated = await store.updateAgentSessionHistory("principal:legacy-title", session.id, [{ role: "user", text: "Deploy Control Room" }], "Deploy Control Room", "auto");- expect(updated.title).toBe("Deploy Control Room");+ const updated = await store.updateAgentSessionHistory("principal:legacy-title", session.id, [{ role: "user", text: "Deploy Example Service" }], "Deploy Example Service", "auto");+ expect(updated.title).toBe("Deploy Example Service");expect(updated.titleSource).toBe("auto");});diff --git a/lib/auth/device-store.ts b/lib/auth/device-store.tsindex 2ed6e950..efb32f3f 100644--- a/lib/auth/device-store.ts+++ b/lib/auth/device-store.ts@@ -9,7 +9,7 @@ import {type DeviceRole,} from "./roles";-// Server-side device allowlist, ported from the VPS Control Room. The login+// Server-side device allowlist, implemented for the VPS control plane. The login// password is a weak/memorable factor; the strong factor is a 128-bit device// id that must be pre-approved here. A new device with the right password is// NOT let in — it lands in `pending` until an approved device (or the CLI)diff --git a/lib/host/index.ts b/lib/host/index.tsindex 1824b16a..c65086ed 100644--- a/lib/host/index.ts+++ b/lib/host/index.ts@@ -12,7 +12,7 @@ export { startExecJob, getExecJob, cancelExecJob } from "./exec-jobs";export { sha256Text, utf8Bytes } from "./hash";export { writeFileGuarded } from "./guarded-write";export { resolveProjectHint, inspectProject } from "./projects";-export { projectCapabilities, runProjectFunction } from "./project-capabilities";+export { projectCapabilities, runProjectFunction, readProjectMcpServers, publicProjectMcpServers, listProjectMcpTools, callProjectMcpTool } from "./project-capabilities";export type { ProjectCapabilities, PublicProjectFunction } from "./project-capabilities";export { listProjects, listProjectDirs, projectRoots, PROJECT_LIMITS } from "./project-roots";export type { ProjectRow, ListProjectsResult } from "./project-roots";diff --git a/lib/host/project-capabilities.ts b/lib/host/project-capabilities.tsindex 0f84496b..513081a2 100644--- a/lib/host/project-capabilities.ts+++ b/lib/host/project-capabilities.ts@@ -3,3 +3,7 @@export { projectCapabilities } from "./project-function-manifest";export type { ProjectCapabilities, PublicProjectFunction } from "./project-function-manifest";export { runProjectFunction } from "./project-function-runner";++export { readProjectMcpServers, publicProjectMcpServers } from "./project-mcp-config";+export type { PublicProjectMcpServer } from "./project-mcp-config";+export { listProjectMcpTools, callProjectMcpTool } from "./project-mcp-client";diff --git a/lib/host/project-function-manifest.ts b/lib/host/project-function-manifest.tsindex c4685f4f..cf072610 100644--- a/lib/host/project-function-manifest.ts+++ b/lib/host/project-function-manifest.ts@@ -24,7 +24,7 @@ export type ProjectFunction = {export type PublicProjectFunction = Omit<ProjectFunction, "command">;export type ProjectCapabilities = {- mcp?: { config: typeof PROJECT_MCP_REL };+ mcp?: { config: typeof PROJECT_MCP_REL; servers?: Array<{ name: string; transport: "stdio" | "http"; auth: "none" | "configured" | "oauth" }> };functions?:| { manifest: typeof PROJECT_FUNCTIONS_REL; valid: true; version: 1; count: number; tools: PublicProjectFunction[] }| { manifest: typeof PROJECT_FUNCTIONS_REL; valid: false; error: string };diff --git a/lib/host/project-mcp-client.ts b/lib/host/project-mcp-client.tsnew file mode 100644index 00000000..9ec01e07--- /dev/null+++ b/lib/host/project-mcp-client.ts@@ -0,0 +1,148 @@+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { childEnv } from "./child-env";+import { safeProviderFetch } from "./ssrf";+import { readProjectMcpServers, type ProjectMcpServer } from "./project-mcp-config";++const PROTOCOL = "2025-11-25";+const TIMEOUT_MS = 15_000;+const MAX_WIRE_BYTES = 2 * 1024 * 1024;+const MAX_TOOL_ARGS_BYTES = 128 * 1024;++type Rpc = { jsonrpc?: string; id?: string | number | null; result?: unknown; error?: { code?: number; message?: string } };+export type ProjectMcpTool = { name: string; title?: string; description?: string; inputSchema: Record<string, unknown>; annotations?: Record<string, unknown> };++function resolveConfigEnv(server: Extract<ProjectMcpServer, { transport: "stdio" }>): Record<string, string> {+ const base = childEnv();+ const env = { ...base };+ for (const [key, value] of Object.entries(server.env)) {+ const match = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(value);+ env[key] = match ? (base[match[1]] ?? "") : value;+ }+ return env;+}++function rpcError(message: Rpc): Error | null {+ return message.error ? new Error(`project MCP error ${message.error.code ?? ""}: ${message.error.message ?? "unknown error"}`.trim()) : null;+}++async function withStdio<T>(server: Extract<ProjectMcpServer, { transport: "stdio" }>, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>, notify: (method: string, params?: unknown) => void) => Promise<T>): Promise<T> {+ return await new Promise<T>((resolve, reject) => {+ const child = spawn(server.command, server.args, { cwd: server.cwd, env: resolveConfigEnv(server) as unknown as NodeJS.ProcessEnv, shell: false, stdio: ["pipe", "pipe", "pipe"] }) as ChildProcessWithoutNullStreams;+ let nextId = 1, buffer = "", bytes = 0, stderr = "", done = false;+ const pending = new Map<number, { resolve: (v: Rpc) => void; reject: (e: Error) => void }>();+ const finish = (error?: Error, value?: T) => {+ if (done) return; done = true; clearTimeout(timer);+ child.stdin.end();+ if (child.exitCode === null && child.signalCode === null) {+ child.kill("SIGTERM");+ const force = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); }, 1000);+ force.unref();+ }+ for (const p of pending.values()) p.reject(error ?? new Error("project MCP session closed")); pending.clear();+ error ? reject(error) : resolve(value as T);+ };+ const parseLine = (line: string) => {+ if (!line.trim()) return;+ let message: Rpc;+ try { message = JSON.parse(line); } catch { finish(new Error("project MCP wrote non-JSON data to stdout")); return; }+ if (typeof message.id !== "number") return;+ const p = pending.get(message.id); if (!p) return; pending.delete(message.id); p.resolve(message);+ };+ child.stdout.on("data", (chunk: Buffer) => {+ bytes += chunk.byteLength; if (bytes > MAX_WIRE_BYTES) return finish(new Error("project MCP stdout exceeded limit"));+ buffer += chunk.toString("utf8");+ while (true) { const i = buffer.indexOf("\n"); if (i < 0) break; const line = buffer.slice(0, i); buffer = buffer.slice(i + 1); parseLine(line); }+ });+ child.stderr.on("data", (chunk: Buffer) => { if (stderr.length < 8192) stderr += chunk.toString("utf8").slice(0, 8192 - stderr.length); });+ child.on("error", (e) => finish(new Error(`project MCP failed to start: ${e.message}`)));+ child.on("close", (code) => { if (!done) finish(new Error(`project MCP exited ${code ?? 1}${stderr ? `: ${stderr.trim().slice(0, 500)}` : ""}`)); });+ const timer = setTimeout(() => finish(new Error(`project MCP timed out after ${TIMEOUT_MS}ms`)), TIMEOUT_MS);+ const rpc = (method: string, params?: unknown) => new Promise<Rpc>((res, rej) => {+ const id = nextId++; pending.set(id, { resolve: res, reject: rej }); child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) })}\n`);+ });+ const notify = (method: string, params?: unknown) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, ...(params === undefined ? {} : { params }) })}\n`);+ (async () => {+ try {+ const init = await rpc("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "mso-project-mcp", version: "1" } });+ const initError = rpcError(init); if (initError) throw initError; notify("notifications/initialized");+ const value = await work(rpc, notify); finish(undefined, value);+ } catch (e) { finish(e instanceof Error ? e : new Error(String(e))); }+ })();+ });+}++async function boundedText(response: Response): Promise<string> {+ if (!response.body) return "";+ const reader = response.body.getReader(), decoder = new TextDecoder(); let bytes = 0, text = "";+ try {+ while (true) { const { done, value } = await reader.read(); if (done) break; bytes += value.byteLength; if (bytes > MAX_WIRE_BYTES) { await reader.cancel(); throw new Error("project MCP HTTP response exceeded limit"); } text += decoder.decode(value, { stream: true }); }+ text += decoder.decode(); return text;+ } finally { reader.releaseLock(); }+}+function parseHttpRpc(text: string, contentType: string): Rpc {+ if (!text.trim()) return {};+ if (!contentType.includes("text/event-stream")) return JSON.parse(text) as Rpc;+ for (const block of text.split(/\n\n+/)) {+ const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");+ if (!data) continue;+ const parsed = JSON.parse(data) as Rpc; if (parsed.id != null || parsed.error || parsed.result) return parsed;+ }+ throw new Error("project MCP SSE response contained no JSON-RPC result");+}+function remoteHeaders(server: Extract<ProjectMcpServer, { transport: "http" }>, sessionId?: string, protocol = PROTOCOL): Headers {+ const headers = new Headers({ "content-type": "application/json", accept: "application/json, text/event-stream", "MCP-Protocol-Version": protocol });+ for (const [name, value] of Object.entries(server.headers)) {+ const lower = name.toLowerCase(); if (["host", "content-length", "connection", "mcp-session-id"].includes(lower)) continue; headers.set(name, value);+ }+ if (sessionId) headers.set("Mcp-Session-Id", sessionId);+ return headers;+}+async function remotePost(server: Extract<ProjectMcpServer, { transport: "http" }>, payload: unknown, sessionId?: string, protocol = PROTOCOL) {+ const response = await safeProviderFetch(server.url, { method: "POST", headers: remoteHeaders(server, sessionId, protocol), body: JSON.stringify(payload) });+ const text = await boundedText(response);+ if (!response.ok && response.status !== 202) throw new Error(`project MCP HTTP ${response.status}${text ? `: ${text.slice(0, 400)}` : ""}`);+ return { message: text ? parseHttpRpc(text, response.headers.get("content-type") ?? "") : ({} as Rpc), sessionId: response.headers.get("mcp-session-id") ?? sessionId };+}+async function withHttp<T>(server: Extract<ProjectMcpServer, { transport: "http" }>, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>) => Promise<T>): Promise<T> {+ if (server.oauthConfigured && !Object.keys(server.headers).some((name) => name.toLowerCase() === "authorization")) {+ throw new Error(`project MCP "${server.name}" declares OAuth but no server-side authorization is configured; MSO will not copy or mint another project's OAuth credential implicitly`);+ }+ const init = await remotePost(server, { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "mso-project-mcp", version: "1" } } });+ const err = rpcError(init.message); if (err) throw err;+ const protocol = (init.message.result as { protocolVersion?: string } | undefined)?.protocolVersion ?? PROTOCOL;+ await remotePost(server, { jsonrpc: "2.0", method: "notifications/initialized" }, init.sessionId, protocol);+ let id = 2;+ return work(async (method, params) => {+ const row = await remotePost(server, { jsonrpc: "2.0", id: id++, method, ...(params === undefined ? {} : { params }) }, init.sessionId, protocol);+ const error = rpcError(row.message); if (error) throw error; return row.message;+ });+}++async function selectedServer(projectPath: string, name: string): Promise<ProjectMcpServer> {+ const servers = await readProjectMcpServers(projectPath); const server = servers.find((row) => row.name === name);+ if (!server) throw new Error(`unknown project MCP server "${name}"`); return server;+}+async function withServer<T>(server: ProjectMcpServer, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>) => Promise<T>): Promise<T> {+ return server.transport === "stdio" ? withStdio(server, (rpc) => work(rpc)) : withHttp(server, work);+}+function publicTools(result: unknown): ProjectMcpTool[] {+ const tools = (result as { tools?: unknown } | undefined)?.tools;+ if (!Array.isArray(tools)) throw new Error("project MCP tools/list returned no tools array");+ return tools.slice(0, 128).flatMap((raw): ProjectMcpTool[] => {+ if (!raw || typeof raw !== "object") return [];+ const row = raw as Record<string, unknown>, name = typeof row.name === "string" ? row.name : "";+ if (!/^[A-Za-z0-9_.-]{1,128}$/.test(name)) return [];+ const inputSchema = row.inputSchema && typeof row.inputSchema === "object" && !Array.isArray(row.inputSchema) ? row.inputSchema as Record<string, unknown> : { type: "object", properties: {} };+ return [{ name, ...(typeof row.title === "string" ? { title: row.title.slice(0, 160) } : {}), ...(typeof row.description === "string" ? { description: row.description.replace(/\s+/g, " ").slice(0, 800) } : {}), inputSchema, ...(row.annotations && typeof row.annotations === "object" ? { annotations: row.annotations as Record<string, unknown> } : {}) }];+ });+}++export async function listProjectMcpTools(projectPath: string, serverName: string): Promise<ProjectMcpTool[]> {+ const server = await selectedServer(projectPath, serverName);+ return withServer(server, async (rpc) => publicTools((await rpc("tools/list")).result));+}+export async function callProjectMcpTool(projectPath: string, serverName: string, toolName: string, args: unknown): Promise<unknown> {+ const payload = JSON.stringify(args ?? {}); if (Buffer.byteLength(payload) > MAX_TOOL_ARGS_BYTES) throw new Error("project MCP tool arguments exceed 128 KiB");+ const server = await selectedServer(projectPath, serverName);+ return withServer(server, async (rpc) => (await rpc("tools/call", { name: toolName, arguments: args ?? {} })).result);+}diff --git a/lib/host/project-mcp-config.ts b/lib/host/project-mcp-config.tsnew file mode 100644index 00000000..abe2156f--- /dev/null+++ b/lib/host/project-mcp-config.ts@@ -0,0 +1,68 @@+import { promises as fs } from "node:fs";+import path from "node:path";+import { BOUNDED_READ, readBoundedRegularFile } from "./bounded-read";+import { isUnderRoot } from "./paths";+import { PROJECT_MCP_REL } from "./project-function-manifest";++const MAX_SERVERS = 16;+const MAX_ARGV = 32;+const MAX_VALUE = 4096;++type BaseServer = { name: string; headers: Record<string, string>; oauthConfigured: boolean };+export type ProjectMcpServer = BaseServer & (+ | { transport: "stdio"; command: string; args: string[]; cwd: string; env: Record<string, string> }+ | { transport: "http"; url: string }+);+export type PublicProjectMcpServer = { name: string; transport: "stdio" | "http"; auth: "none" | "configured" | "oauth" };++const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));+const strings = (v: unknown, max: number): string[] => Array.isArray(v) && v.length <= max && v.every((x) => typeof x === "string" && x.length <= MAX_VALUE && !x.includes("\0")) ? v : [];+function stringMap(v: unknown, max = 32): Record<string, string> {+ if (!object(v) || Object.keys(v).length > max) return {};+ const out: Record<string, string> = {};+ for (const [k, raw] of Object.entries(v)) {+ if (!/^[A-Za-z_][A-Za-z0-9_-]{0,127}$/.test(k) || typeof raw !== "string" || raw.length > MAX_VALUE || raw.includes("\0")) continue;+ out[k] = raw;+ }+ return out;+}+function projectCwd(projectPath: string, raw: unknown): string {+ const candidate = typeof raw === "string" && raw.trim() ? (path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(projectPath, raw)) : path.resolve(projectPath);+ if (!isUnderRoot(candidate, projectPath) && candidate !== path.resolve(projectPath)) throw new Error("project MCP cwd must stay inside the project");+ return candidate;+}++export async function readProjectMcpServers(projectPath: string): Promise<ProjectMcpServer[]> {+ const file = path.join(projectPath, PROJECT_MCP_REL);+ const stat = await fs.lstat(file).catch(() => null);+ if (!stat) return [];+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${PROJECT_MCP_REL} must be a regular non-symlink file`);+ const raw = await readBoundedRegularFile(file, BOUNDED_READ.projectMcpConfig);+ if (raw === null) throw new Error(`${PROJECT_MCP_REL} is unreadable or too large`);+ let parsed: unknown;+ try { parsed = JSON.parse(raw); } catch { throw new Error(`${PROJECT_MCP_REL} is not valid JSON`); }+ if (!object(parsed)) throw new Error(`${PROJECT_MCP_REL} must be a JSON object`);+ const servers = object(parsed.mcpServers) ? parsed.mcpServers : object(parsed.servers) ? parsed.servers : {};+ const entries = Object.entries(servers);+ if (entries.length > MAX_SERVERS) throw new Error(`${PROJECT_MCP_REL} exceeds ${MAX_SERVERS} servers`);+ const out: ProjectMcpServer[] = [];+ for (const [name, value] of entries) {+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(name) || !object(value)) continue;+ const headers = stringMap(value.headers);+ const oauthConfigured = object(value.oauth);+ if (typeof value.command === "string" && value.command.trim() && value.command.length <= MAX_VALUE) {+ const args = value.args === undefined ? [] : strings(value.args, MAX_ARGV);+ if (value.args !== undefined && !args.length && Array.isArray(value.args) && value.args.length) throw new Error(`${name}: invalid args`);+ out.push({ name, transport: "stdio", command: value.command, args, cwd: projectCwd(projectPath, value.cwd), env: stringMap(value.env, 64), headers, oauthConfigured });+ continue;+ }+ if (typeof value.url === "string" && value.url.length <= MAX_VALUE) {+ out.push({ name, transport: "http", url: value.url, headers, oauthConfigured });+ }+ }+ return out;+}++export function publicProjectMcpServers(servers: ProjectMcpServer[]): PublicProjectMcpServer[] {+ return servers.map((server) => ({ name: server.name, transport: server.transport, auth: server.oauthConfigured ? "oauth" : Object.keys(server.headers).length ? "configured" : "none" }));+}diff --git a/lib/host/project-mcp.test.ts b/lib/host/project-mcp.test.tsnew file mode 100644index 00000000..fcf8201f--- /dev/null+++ b/lib/host/project-mcp.test.ts@@ -0,0 +1,50 @@+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const root = await mkdtemp(path.join(os.tmpdir(), "mso-project-mcp-"));+const fixture = path.join(root, "fixture.mjs");+const project = path.join(root, "project");+await import("node:fs/promises").then(({ mkdir }) => mkdir(project, { recursive: true }));++beforeAll(async () => {+ await writeFile(fixture, `+import readline from 'node:readline';+const rl=readline.createInterface({input:process.stdin,crlfDelay:Infinity});+const send=(x)=>process.stdout.write(JSON.stringify(x)+'\\n');+rl.on('line',(line)=>{const m=JSON.parse(line); if(m.method==='initialize') return send({jsonrpc:'2.0',id:m.id,result:{protocolVersion:m.params.protocolVersion,capabilities:{tools:{}},serverInfo:{name:'fixture',version:'1'}}}); if(m.method==='notifications/initialized') return; if(m.method==='tools/list') return send({jsonrpc:'2.0',id:m.id,result:{tools:[{name:'private_echo',title:'Private Echo',description:'Project-owned dynamic tool',inputSchema:{type:'object',properties:{value:{type:'string'}},required:['value']},annotations:{readOnlyHint:true}}]}}); if(m.method==='tools/call') return send({jsonrpc:'2.0',id:m.id,result:{content:[{type:'text',text:JSON.stringify({value:m.params.arguments.value,visible:process.env.PROJECT_VISIBLE,secretLeak:Boolean(process.env.OS_SESSION_SECRET),secretRef:process.env.SECRET_REF||''})}]}});});+`);+ await writeFile(path.join(project, ".mcp.json"), JSON.stringify({ mcpServers: { projectFixture: { command: process.execPath, args: [fixture], env: { PROJECT_VISIBLE: "ok", SECRET_REF: "${OS_SESSION_SECRET}" } } } }));+});+afterAll(async () => rm(root, { recursive: true, force: true }));++describe("dynamic project MCP boundary", () => {+ it("returns only safe server aliases, never config/env values", async () => {+ process.env.OS_SESSION_SECRET = "must-not-leak";+ const { readProjectMcpServers, publicProjectMcpServers } = await import("./project-mcp-config");+ const internal = await readProjectMcpServers(project);+ const publicRows = publicProjectMcpServers(internal);+ expect(publicRows).toEqual([{ name: "projectFixture", transport: "stdio", auth: "none" }]);+ expect(JSON.stringify(publicRows)).not.toContain("PROJECT_VISIBLE");+ expect(JSON.stringify(publicRows)).not.toContain("must-not-leak");+ });++ it("discovers and calls the project-owned tool on demand without inheriting MSO secrets", async () => {+ process.env.OS_SESSION_SECRET = "must-not-leak";+ const { listProjectMcpTools, callProjectMcpTool } = await import("./project-mcp-client");+ const tools = await listProjectMcpTools(project, "projectFixture");+ expect(tools).toHaveLength(1);+ expect(tools[0]).toMatchObject({ name: "private_echo", title: "Private Echo" });+ const result = await callProjectMcpTool(project, "projectFixture", "private_echo", { value: "hello" });+ const text = (result as { content: Array<{ text: string }> }).content[0].text;+ expect(JSON.parse(text)).toEqual({ value: "hello", visible: "ok", secretLeak: false, secretRef: "" });+ });++ it("refuses a stdio cwd that escapes the selected project", async () => {+ await writeFile(path.join(project, ".mcp.json"), JSON.stringify({ mcpServers: { bad: { command: process.execPath, args: [fixture], cwd: ".." } } }));+ const { readProjectMcpServers } = await import("./project-mcp-config");+ await expect(readProjectMcpServers(project)).rejects.toThrow(/cwd must stay inside/i);+ await writeFile(path.join(project, ".mcp.json"), JSON.stringify({ mcpServers: { projectFixture: { command: process.execPath, args: [fixture], env: { PROJECT_VISIBLE: "ok", SECRET_REF: "${OS_SESSION_SECRET}" } } } }));+ });+});diff --git a/lib/mcp/chatgpt-profile.test.ts b/lib/mcp/chatgpt-profile.test.tsnew file mode 100644index 00000000..b2f3a762--- /dev/null+++ b/lib/mcp/chatgpt-profile.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));++const { dispatch } = await import("./dispatch");+const { CHATGPT_TOOL_NAMES } = await import("./tool-contract");++const context = { principal: "mcp-client:chatgpt-test", sessionId: "session-profile", toolProfile: "chatgpt" as const };++describe("ChatGPT compact MCP profile", () => {+ it("advertises only MSO-owned generic tools with complete OpenAI metadata and scanner headroom", async () => {+ const response = await dispatch({ id: 1, method: "tools/list" }, "exec", "test", context);+ const tools = (response.result as { tools: Array<Record<string, unknown>> }).tools;+ expect(tools.map((tool) => tool.name).sort()).toEqual([...CHATGPT_TOOL_NAMES].sort());+ expect(tools).toHaveLength(29);++ for (const tool of tools) {+ expect(typeof tool.title, String(tool.name)).toBe("string");+ expect(String(tool.title).trim().length, String(tool.name)).toBeGreaterThan(0);+ const annotations = tool.annotations as Record<string, unknown>;+ for (const key of ["readOnlyHint", "destructiveHint", "openWorldHint"]) {+ expect(typeof annotations?.[key], `${String(tool.name)}.${key}`).toBe("boolean");+ }+ const schemes = tool.securitySchemes as Array<Record<string, unknown>>;+ 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(Buffer.byteLength(JSON.stringify(tool)), String(tool.name)).toBeLessThan(8 * 1024);+ }++ const bytes = Buffer.byteLength(JSON.stringify(tools));+ if (process.env.MSO_PROFILE_METRICS === "1") console.info(`CHATGPT_PROFILE_METRICS tools=${tools.length} bytes=${bytes} roughTokens4=${Math.ceil(bytes/4)} maxToolBytes=${Math.max(...tools.map((tool)=>Buffer.byteLength(JSON.stringify(tool))))}`);+ expect(bytes).toBeLessThan(40 * 1024);+ expect(tools.some((tool) => tool.name === "local_agent_inbox")).toBe(true);+ expect(tools.some((tool) => tool.name === "project_mcp_tools")).toBe(true);+ expect(tools.some((tool) => tool.name === "project_mcp_call")).toBe(true);+ expect(tools.some((tool) => String(tool.name) === "private_echo" || String(tool.name).startsWith("project_fixture_"))).toBe(false);+ });++ it("fails closed when a compact-profile client guesses a full-catalog tool", async () => {+ const result = await dispatch({ id: 2, method: "tools/call", params: { name: "apps_power", arguments: { id: "hermes", action: "restart" } } }, "exec", "test", context);+ expect(result.error).toMatchObject({ code: -32602 });+ });+});diff --git a/lib/mcp/client-profile.test.ts b/lib/mcp/client-profile.test.tsnew file mode 100644index 00000000..5795a963--- /dev/null+++ b/lib/mcp/client-profile.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from "vitest";+import { detectMcpToolProfile } from "./client-profile";++describe("MCP client profile detection", () => {+ it("recognizes the current ChatGPT connector callback host", () => {+ expect(detectMcpToolProfile({ redirectUris: ["https://chatgpt.com/connector/oauth/callback-123"] })).toBe("chatgpt");+ });++ it("recognizes a legacy registered ChatGPT client by name", () => {+ expect(detectMcpToolProfile({ clientId: "mcpc_legacy", name: "ChatGPT" })).toBe("chatgpt");+ });++ it("keeps generic MCP clients on the full MSO catalog", () => {+ expect(detectMcpToolProfile({ clientId: "mcpc_generic", name: "Cursor", redirectUris: ["https://example.com/oauth/callback"] })).toBe("full");+ });+});diff --git a/lib/mcp/client-profile.ts b/lib/mcp/client-profile.tsnew file mode 100644index 00000000..90681528--- /dev/null+++ b/lib/mcp/client-profile.ts@@ -0,0 +1,14 @@+import type { McpToolProfile } from "./tool-contract";++function hostOf(value: string): string {+ try { return new URL(value).hostname.toLowerCase(); } catch { return ""; }+}++export function detectMcpToolProfile(input: { clientId?: string; name?: string; redirectUris?: string[] }): McpToolProfile {+ const name = (input.name ?? "").toLowerCase();+ const clientHost = hostOf(input.clientId ?? "");+ const redirectHosts = (input.redirectUris ?? []).map(hostOf);+ if (name.includes("chatgpt") || name === "openai" || clientHost === "chatgpt.com" || clientHost.endsWith(".chatgpt.com") ||+ redirectHosts.some((host) => host === "chatgpt.com" || host.endsWith(".chatgpt.com"))) return "chatgpt";+ return "full";+}diff --git a/lib/mcp/dispatch-tools.ts b/lib/mcp/dispatch-tools.tsindex 86989bd4..ada32f10 100644--- a/lib/mcp/dispatch-tools.ts+++ b/lib/mcp/dispatch-tools.ts@@ -5,6 +5,7 @@ import { activeWorkflowForActor, recordWorkflowStep } from "@/lib/skills/memory"import { activityTarget, newActivityId, recordMcpActivity } from "./activity";import { allows, type Scope } from "./scope";import { TOOLS_BY_NAME } from "./tools";+import { toolAllowedForProfile } from "./tool-contract";import { rpcFail, rpcOk, type McpAgentContext, type RpcRequest } from "./dispatch-types";import { recipeActor, workflowActor } from "./dispatch-actors";import { flowFields, recordAgentEvent, sessionDetail, structuredResult, workflowFromResult } from "./dispatch-tool-support";@@ -14,7 +15,7 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: stconst id = req.id ?? null;const name = String(req.params?.name ?? ""), args = req.params?.arguments ?? {};const tool = TOOLS_BY_NAME.get(name);- if (!tool) return rpcFail(id, -32602, `unknown tool: ${name}`);+ if (!tool || !toolAllowedForProfile(name, context?.toolProfile ?? "full")) return rpcFail(id, -32602, `unknown tool: ${name}`);const mcpPresence = context?.principal?.startsWith("mcp-") && context.sessionId? { principal: context.principal, sessionId: context.sessionId, instanceId: `mcp:${context.sessionId}` }: null;@@ -84,7 +85,7 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st}const result = await tool.run(args, {actor, principal: context?.principal, sessionId: context?.sessionId, scope,- workflowId: activeWorkflow?.id, workflowActor: flowActor, recipeActor: learnedActor,+ workflowId: activeWorkflow?.id, workflowActor: flowActor, recipeActor: learnedActor, toolProfile: context?.toolProfile,});if (trail) {const outcome = trail.outcome?.(result);diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.tsindex db9d0177..9d7c6cbe 100644--- a/lib/mcp/dispatch-types.ts+++ b/lib/mcp/dispatch-types.ts@@ -1,3 +1,5 @@+import type { McpToolProfile } from "./tool-contract";+export interface RpcRequest {jsonrpc?: string;id?: string | number | null;@@ -15,6 +17,7 @@ export interface RpcRequest {export interface McpAgentContext {principal?: string;sessionId?: string;+ toolProfile?: McpToolProfile;}export type RpcId = string | number | null | undefined;diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.tsindex cbcbb859..668e978a 100644--- a/lib/mcp/dispatch.test.ts+++ b/lib/mcp/dispatch.test.ts@@ -46,7 +46,7 @@ describe("protocol", () => {it("publishes server and toolset metadata so action drift is visible", async () => {const r = await dispatch({ id: 1, method: "initialize" }, "exec");const result = r.result as { serverInfo: { version: string }; _meta: { toolset: { toolCount: number; hash: string } } };- expect(result.serverInfo.version).toBe("1.6.0");+ expect(result.serverInfo.version).toBe("1.7.0");expect(result._meta.toolset.toolCount).toBe(TOOLS.length);expect(result._meta.toolset.hash).toMatch(/^[a-f0-9]{16}$/);});@@ -56,7 +56,7 @@ describe("protocol", () => {const r = await dispatch({ id: 1, method: "tools/list" }, "write");const tools = (r.result as { tools: Array<{ name: string; _meta?: Record<string, unknown> }> }).tools;const upload = tools.find((tool) => tool.name === "fs_upload_file");- expect(upload?._meta).toEqual({ "openai/fileParams": ["file"] });+ expect(upload?._meta).toEqual({ "openai/fileParams": ["file"], securitySchemes: [{ type: "oauth2", scopes: ["write"] }] });});it("answers ping and initialized", async () => {diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.tsindex 203cce98..3e428498 100644--- a/lib/mcp/dispatch.ts+++ b/lib/mcp/dispatch.ts@@ -1,12 +1,13 @@-import { allows, type Scope } from "./scope";+import type { Scope } from "./scope";import { MCP_SERVER_VERSION, toolsetInfo } from "./toolset";import { TOOLS } from "./tools";import { listUiResources, readUiResource } from "./ui-resources";import { dispatchToolCall } from "./dispatch-tools";+import { toolDescriptor, visibleToolsForProfile, type McpToolProfile } from "./tool-contract";+import { negotiateMcpProtocol } from "./protocol";import { rpcFail, rpcOk, type McpAgentContext, type RpcRequest } from "./dispatch-types";export type { McpAgentContext, RpcRequest } from "./dispatch-types";-const PROTOCOL = "2024-11-05";export const UNAUTHORIZED = -32001;export const RATE_LIMITED = -32029;@@ -15,19 +16,15 @@ export function isNotification(body: unknown): boolean {return b?.id == null && String(b?.method ?? "").startsWith("notifications/");}-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.outputSchema ? { outputSchema: tool.outputSchema } : {}),- ...(tool.annotations ? { annotations: tool.annotations } : {}),- ...(tool.meta ? { _meta: tool.meta } : {}),-}));+const visibleTools = (scope: Scope, profile: McpToolProfile = "full") => visibleToolsForProfile(TOOLS, scope, profile);+const toolList = (scope: Scope, profile: McpToolProfile = "full") => visibleTools(scope, profile).map((tool) => toolDescriptor(tool, profile));-function instructions(scope: Scope): string {+function instructions(scope: Scope, profile: McpToolProfile = "full"): string {const startup = scope === "read"? "This token is read-only: use skills_search for capability discovery, then bounded read tools.": "For multi-step work call workflow_start once, pass its exact workflow_id on every operation in this conversation, verify, then workflow_finish or workflow_cancel.";- return `${startup} ChatGPT conversation identity is isolated from OAuth/audit identity; workflows are session-scoped while learned successful recipes remain client-scoped. agent_session_current exposes only the current durable MSO session. Use agent_sessions_list and agent_session_resume for explicit recovery. Session context has an estimated-token budget, private archive/compaction, and timestamps; MSO never claims access to hidden ChatGPT transcript. Prefer bounded tools; use exec_job_start for long tests/builds. Never expose private chain-of-thought.`;+ const projectBoundary = profile === "chatgpt" ? " Project-owned MCP tools never join this catalog: use project_mcp_tools then project_mcp_call." : "";+ return `${startup}${projectBoundary} Session/workflow state is isolated per conversation. Prefer bounded tools and exec_job_start for long builds. Never expose hidden transcripts, credentials, or private chain-of-thought.`;}export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, agentContext?: McpAgentContext): Promise<Record<string, unknown>> {@@ -35,19 +32,21 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, agswitch (req.method) {case "initialize":case "server/discover": {- const tools = visibleTools(scope), toolset = toolsetInfo(tools, scope);+ const profile = agentContext?.toolProfile ?? "full";+ const tools = visibleTools(scope, profile), toolset = toolsetInfo(tools, scope, profile);return rpcOk(id, {- protocolVersion: req.params?.protocolVersion ?? PROTOCOL,+ protocolVersion: negotiateMcpProtocol(req.params?.protocolVersion),capabilities: { tools: { listChanged: false }, resources: { listChanged: false } },- serverInfo: { name: "mso", version: MCP_SERVER_VERSION }, instructions: instructions(scope),+ serverInfo: { name: "mso", version: MCP_SERVER_VERSION }, instructions: instructions(scope, profile),_meta: { toolset, ...(agentContext?.sessionId ? { agentSessionId: agentContext.sessionId } : {}) },});}case "notifications/initialized":case "ping": return rpcOk(id, {});case "tools/list": {- const tools = visibleTools(scope);- return rpcOk(id, { tools: toolList(scope), _meta: { toolset: toolsetInfo(tools, scope) } });+ const profile = agentContext?.toolProfile ?? "full";+ const tools = visibleTools(scope, profile);+ return rpcOk(id, { tools: toolList(scope, profile), _meta: { toolset: toolsetInfo(tools, scope, profile) } });}case "resources/list": return rpcOk(id, { resources: listUiResources() });case "resources/read": {diff --git a/lib/mcp/openai-file-upload.test.ts b/lib/mcp/openai-file-upload.test.tsindex 748504fb..2c40be94 100644--- a/lib/mcp/openai-file-upload.test.ts+++ b/lib/mcp/openai-file-upload.test.ts@@ -26,7 +26,7 @@ describe("ChatGPT file host allowlist", () => {file_name: "file.png",size: 8,},- dest: "/home/antinrml/generated-images",+ dest: "/home/example/generated-images",filename: "file.png",});@@ -117,7 +117,7 @@ describe("ChatGPT file host allowlist", () => {mime_type: "application/octet-stream",file_name: "file.bin",},- dest: "/home/antinrml/generated-images",+ dest: "/home/example/generated-images",})).rejects.toThrow("exceeds the 20 MiB MCP import limit");expect(uploadInto).not.toHaveBeenCalled();});diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex 0f1cec63..a387412c 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -37,6 +37,8 @@ const MCP_ONLY: Record<string, string> = {"projects.list": "an MCP client has no sidebar and no Files window, so it needs an explicit bounded enumeration of every project container; in-shell Alfa reads the same roots through fs.list and the Files app","project.capabilities": "external harnesses need a stable generic discovery seam for project-owned MCP/functions; Alfa can inspect the same project files through its existing fs/skills tools without changing its cached tool array","project.function.call": "external MCP clients need one no-shell bridge into project-declared functions; Alfa already has per-call-approved exec.run and must not receive a dynamic per-project tool catalog",+ "project.mcp.tools": "external MCP clients discover one selected project MCP lazily; dynamic project tool names never enter either global catalog",+ "project.mcp.call": "external MCP clients execute one exact dynamically-discovered project MCP tool under exec scope; Alfa can use its approved exec path and must not import project MCP catalogs","fs.upload.file": "external ChatGPT connectors need openai/fileParams to move conversation-generated files onto the VPS; in-shell Alfa already has direct host filesystem access","workflow.start": "the external connector needs an actor-scoped task boundary; Alfa already owns an in-app conversation/run boundary","workflow.status": "app-only MCP Apps bridge used by the ChatGPT progress component; Alfa already owns its in-shell run state and must not poll the external workflow store",@@ -161,6 +163,8 @@ describe("MCP rate limits mirror the routes", () => {"projects.list": 30,"projects.capabilities": 60,"projects.function": 60,+ "projects.mcp.read": 30,+ "projects.mcp.call": 30,"skills.list": 30,"skills.read": 60,"infra.dokploy": 20,diff --git a/lib/mcp/protocol.ts b/lib/mcp/protocol.tsnew file mode 100644index 00000000..2f406db4--- /dev/null+++ b/lib/mcp/protocol.ts@@ -0,0 +1,9 @@+export const MCP_PROTOCOL_LATEST = "2026-07-28";+export const MCP_PROTOCOLS = [MCP_PROTOCOL_LATEST, "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] as const;++export function negotiateMcpProtocol(requested?: string): string {+ return requested && (MCP_PROTOCOLS as readonly string[]).includes(requested) ? requested : MCP_PROTOCOL_LATEST;+}+export function supportedMcpProtocol(value: string): boolean {+ return (MCP_PROTOCOLS as readonly string[]).includes(value);+}diff --git a/lib/mcp/redirect.ts b/lib/mcp/redirect.tsindex 5a788214..4fa2d0fe 100644--- a/lib/mcp/redirect.ts+++ b/lib/mcp/redirect.ts@@ -53,7 +53,7 @@ export function selfUrl(query: Record<string, string | string[] | undefined>): s* The caller renders no Cancel link in that case rather than a broken one: a* refusal is not a reason to relax the check that guards the success path.*/-export function denyUrl(redirectUri: string, state: string): string | null {+export function denyUrl(redirectUri: string, state: string, issuer?: string): string | null {if (!isAllowedRedirect(redirectUri)) return null;let url: URL;try {@@ -63,5 +63,6 @@ export function denyUrl(redirectUri: string, state: string): string | null {}url.searchParams.set("error", "access_denied");if (state) url.searchParams.set("state", state);+ if (issuer) url.searchParams.set("iss", issuer);return url.toString();}diff --git a/lib/mcp/scope.ts b/lib/mcp/scope.tsindex be4714b5..0ffcf945 100644--- a/lib/mcp/scope.ts+++ b/lib/mcp/scope.ts@@ -21,6 +21,14 @@ export function parseScope(raw: string | undefined | null): Scope {return asked.reduce((a, b) => (RANK[b] > RANK[a] ? b : a));}++/** OAuth scope strings are cumulative so a standards-compliant host can see that an exec token also satisfies read/write tool schemes. */+export function oauthScopeString(scope: Scope, offline = false): string {+ const values = scope === "read" ? ["read"] : scope === "write" ? ["read", "write"] : ["read", "write", "exec"];+ if (offline) values.push("offline_access");+ return values.join(" ");+}+export function allows(held: Scope, needed: Scope): boolean {return RANK[held] >= RANK[needed];}diff --git a/lib/mcp/store.test.ts b/lib/mcp/store.test.tsindex 04402b1c..1d84e627 100644--- a/lib/mcp/store.test.ts+++ b/lib/mcp/store.test.ts@@ -142,3 +142,30 @@ describe("read()", () => {expect(await store.listTokens()).toEqual([]);});});++describe("OAuth refresh grants", () => {+ it("stores access/refresh only as hashes, rotates refresh once, and keeps resource/profile binding", async () => {+ await store.storeOAuthGrant({+ accessToken: "access-one", refreshToken: "refresh-one", label: "oauth", clientId: "chatgpt-client", scope: "exec",+ resource: "https://mso.example/mcp", profile: "chatgpt", offlineAccess: true, grantId: "grant-one",+ });+ expect(await store.validateToken("access-one")).toMatchObject({ clientId: "chatgpt-client", resource: "https://mso.example/mcp", profile: "chatgpt", grantId: "grant-one" });+ const raw = await fs.readFile(process.env.OS_MCP_STORE!, "utf8");+ expect(raw).not.toContain("access-one");+ expect(raw).not.toContain("refresh-one");+ expect(raw).toContain(sha256hex("refresh-one"));++ const rotated = await store.rotateOAuthGrant({ oldRefreshToken: "refresh-one", accessToken: "access-two", refreshToken: "refresh-two", label: "oauth", clientId: "chatgpt-client", resource: "https://mso.example/mcp" });+ expect(rotated).toMatchObject({ grantId: "grant-one", scope: "exec", offlineAccess: true });+ expect(await store.rotateOAuthGrant({ oldRefreshToken: "refresh-one", accessToken: "replay", refreshToken: "replay-r", label: "oauth", clientId: "chatgpt-client", resource: "https://mso.example/mcp" })).toBeNull();+ expect(await store.validateToken("access-two")).toMatchObject({ grantId: "grant-one", profile: "chatgpt" });+ });++ it("binds refresh to client/resource and revoking one access token kills the grant family", async () => {+ await store.storeOAuthGrant({ accessToken: "family-access", refreshToken: "family-refresh", label: "oauth", clientId: "client-a", scope: "write", resource: "https://mso.example/mcp", grantId: "grant-family" });+ await expect(store.rotateOAuthGrant({ oldRefreshToken: "family-refresh", accessToken: "wrong", refreshToken: "wrong-r", label: "oauth", clientId: "client-b", resource: "https://mso.example/mcp" })).resolves.toBeNull();+ const id = (await store.listTokens()).find((row) => row.grantId === "grant-family")!.id;+ expect(await store.revokeToken(id)).toBe(true);+ await expect(store.rotateOAuthGrant({ oldRefreshToken: "family-refresh", accessToken: "after-revoke", refreshToken: "after-revoke-r", label: "oauth", clientId: "client-a", resource: "https://mso.example/mcp" })).resolves.toBeNull();+ });+});diff --git a/lib/mcp/store.ts b/lib/mcp/store.tsindex 6b63d0d5..a9cc6ead 100644--- a/lib/mcp/store.ts+++ b/lib/mcp/store.ts@@ -3,6 +3,8 @@ import os from "node:os";import path from "node:path";import { sha256hex } from "./pkce";import type { Scope } from "./scope";+import type { McpToolProfile } from "./tool-contract";+import { detectMcpToolProfile } from "./client-profile";import { withSecurityStoreLock } from "@/lib/security-store-lock";// OAuth clients, authorization codes and bearer tokens for the MCP server.@@ -16,6 +18,7 @@ import { withSecurityStoreLock } from "@/lib/security-store-lock";export interface McpClient {name: string;redirectUris: string[];+ profile?: McpToolProfile;createdAt: number;}@@ -24,6 +27,9 @@ export interface McpCode {redirectUri: string;codeChallenge: string;scope: Scope;+ resource?: string;+ profile?: McpToolProfile;+ offlineAccess?: boolean;expiresAt: number;}@@ -31,25 +37,35 @@ export interface McpToken {label: string;clientId: string;scope: Scope;+ resource?: string;+ profile?: McpToolProfile;+ grantId?: string;createdAt: number;expiresAt: number;lastUsedAt?: number;revokedAt?: number;}+export interface McpRefreshToken {+ grantId: string; clientId: string; scope: Scope; resource: string; profile?: McpToolProfile; offlineAccess?: boolean; createdAt: number; expiresAt: number; revokedAt?: number;+}+interface Store {clients: Record<string, McpClient>;codes: Record<string, McpCode>;tokens: Record<string, McpToken>;+ refreshTokens: Record<string, McpRefreshToken>;}const STORE_PATH = process.env.OS_MCP_STORE ?? path.join(os.homedir(), ".mso", "mcp.json");export const CODE_TTL_MS = 60_000; // RFC 6749 wants ≤10 min; the exchange is immediate-export const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90d — a forgotten bearer expires+export const TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // legacy/manual bearer lifetime+export const OAUTH_ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000; // short-lived; refresh token rotates it+export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000;const MAX_CLIENTS = 32;-const empty = (): Store => ({ clients: {}, codes: {}, tokens: {} });+const empty = (): Store => ({ clients: {}, codes: {}, tokens: {}, refreshTokens: {} });// Same rule as device-store: "no file yet" is the ONLY failure that may read as an// empty store. A corrupt file or EACCES must throw, because read() feeds a@@ -64,7 +80,7 @@ async function read(): Promise<Store> {throw e;}const p = JSON.parse(raw) as Partial<Store>;- return { clients: p.clients ?? {}, codes: p.codes ?? {}, tokens: p.tokens ?? {} };+ return { clients: p.clients ?? {}, codes: p.codes ?? {}, tokens: p.tokens ?? {}, refreshTokens: (p as Partial<Store>).refreshTokens ?? {} };}async function write(store: Store): Promise<void> {@@ -94,6 +110,7 @@ function mutate<T>(fn: () => Promise<T>): Promise<T> {function sweep(store: Store): Store {const now = Date.now();for (const [k, v] of Object.entries(store.codes)) if (v.expiresAt < now) delete store.codes[k];+ for (const [k, v] of Object.entries(store.refreshTokens)) if (v.expiresAt < now || v.revokedAt) delete store.refreshTokens[k];return store;}@@ -113,7 +130,8 @@ export function registerClient(name: string, redirectUris: string[]): Promise<st.forEach((id) => delete store.clients[id]);}const clientId = "mcpc_" + sha256hex(key + Date.now()).slice(0, 24);- store.clients[clientId] = { name: name.slice(0, 80) || "MCP Client", redirectUris, createdAt: Date.now() };+ const cleanName = name.slice(0, 80) || "MCP Client";+ store.clients[clientId] = { name: cleanName, redirectUris, profile: detectMcpToolProfile({ clientId, name: cleanName, redirectUris }), createdAt: Date.now() };await write(store);return clientId;});@@ -157,6 +175,30 @@ export function storeToken(token: string, rec: Omit<McpToken, "createdAt" | "exp});}++export function storeOAuthGrant(input: {+ accessToken: string; refreshToken: string; label: string; clientId: string; scope: Scope; resource: string; profile?: McpToolProfile; offlineAccess?: boolean; grantId: string;+}): Promise<void> {+ return mutate(async () => {+ const store = sweep(await read()); const now = Date.now();+ store.tokens[sha256hex(input.accessToken)] = { label: input.label, clientId: input.clientId, scope: input.scope, resource: input.resource, profile: input.profile, grantId: input.grantId, createdAt: now, expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS };+ store.refreshTokens[sha256hex(input.refreshToken)] = { grantId: input.grantId, clientId: input.clientId, scope: input.scope, resource: input.resource, profile: input.profile, offlineAccess: input.offlineAccess, createdAt: now, expiresAt: now + REFRESH_TOKEN_TTL_MS };+ await write(store);+ });+}++export function rotateOAuthGrant(input: { oldRefreshToken: string; accessToken: string; refreshToken: string; label: string; clientId: string; resource: string }): Promise<McpRefreshToken | null> {+ return mutate(async () => {+ const store = sweep(await read()), oldHash = sha256hex(input.oldRefreshToken), rec = store.refreshTokens[oldHash];+ if (!rec || rec.revokedAt || rec.expiresAt < Date.now() || rec.clientId !== input.clientId || rec.resource !== input.resource) return null;+ delete store.refreshTokens[oldHash];+ const now = Date.now();+ store.tokens[sha256hex(input.accessToken)] = { label: input.label, clientId: rec.clientId, scope: rec.scope, resource: rec.resource, profile: rec.profile, grantId: rec.grantId, createdAt: now, expiresAt: now + OAUTH_ACCESS_TOKEN_TTL_MS };+ store.refreshTokens[sha256hex(input.refreshToken)] = { ...rec, createdAt: now, expiresAt: now + REFRESH_TOKEN_TTL_MS };+ await write(store); return rec;+ });+}+/** Returns the live token record, or null for unknown / revoked / expired. Both* revocation and expiry are re-checked on EVERY call — that is what makes the* Revoke button in Settings kill an in-flight connector immediately. */@@ -205,9 +247,10 @@ export function revokeToken(id: string): Promise<boolean> {const store = await read();const hit = Object.keys(store.tokens).find((h) => h.startsWith(id));if (!hit || store.tokens[hit].revokedAt) return false;- store.tokens[hit].revokedAt = Date.now();- await write(store);- return true;+ const now = Date.now(), grantId = store.tokens[hit].grantId;+ for (const token of Object.values(store.tokens)) if (token === store.tokens[hit] || (grantId && token.grantId === grantId)) token.revokedAt = now;+ if (grantId) for (const refresh of Object.values(store.refreshTokens)) if (refresh.grantId === grantId) refresh.revokedAt = now;+ await write(store); return true;});}@@ -216,8 +259,10 @@ export function revokeAllTokens(): Promise<number> {return mutate(async () => {const store = await read();let n = 0;- for (const t of Object.values(store.tokens)) if (!t.revokedAt) { t.revokedAt = Date.now(); n++; }- if (n) await write(store);+ const now = Date.now();+ for (const t of Object.values(store.tokens)) if (!t.revokedAt) { t.revokedAt = now; n++; }+ for (const t of Object.values(store.refreshTokens)) if (!t.revokedAt) t.revokedAt = now;+ if (n || Object.keys(store.refreshTokens).length) await write(store);return n;});}diff --git a/lib/mcp/tool-contract.test.ts b/lib/mcp/tool-contract.test.tsnew file mode 100644index 00000000..b4d457d1--- /dev/null+++ b/lib/mcp/tool-contract.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+const { TOOLS } = await import("./tools");+const { toolDescriptor } = await import("./tool-contract");++describe("MCP advertised tool contract", () => {+ it("gives every global MSO tool a title, required safety hints, and matching OAuth security metadata", () => {+ expect(new Set(TOOLS.map((tool) => tool.name)).size).toBe(TOOLS.length);+ for (const tool of TOOLS) {+ const descriptor = toolDescriptor(tool);+ expect(descriptor.title.trim().length, tool.name).toBeGreaterThan(0);+ expect(descriptor.title.length, tool.name).toBeLessThanOrEqual(80);+ expect(descriptor.annotations).toEqual(expect.objectContaining({ readOnlyHint: expect.any(Boolean), destructiveHint: expect.any(Boolean), openWorldHint: expect.any(Boolean) }));+ expect(descriptor.securitySchemes).toEqual([{ type: "oauth2", scopes: [tool.scope] }]);+ expect(descriptor._meta.securitySchemes).toEqual(descriptor.securitySchemes);+ }+ });++ it("keeps private project MCP tool names out of the global catalog", () => {+ const names = TOOLS.map((tool) => tool.name);+ expect(names).toContain("project_mcp_tools");+ expect(names).toContain("project_mcp_call");+ expect(names.some((name) => name === "private_echo" || name.startsWith("project_fixture_"))).toBe(false);+ });+});diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.tsnew file mode 100644index 00000000..7d4e9f83--- /dev/null+++ b/lib/mcp/tool-contract.ts@@ -0,0 +1,118 @@+import type { Scope } from "./scope";+import type { McpTool } from "./tool-kit";++export type McpToolProfile = "full" | "chatgpt";+export type McpToolAnnotations = {+ readOnlyHint: boolean;+ destructiveHint: boolean;+ openWorldHint: boolean;+ idempotentHint?: boolean;+};+export type McpSecurityScheme = { type: "oauth2"; scopes: string[] } | { type: "noauth" };++// 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+// to this list or TOOLS.+export const CHATGPT_TOOL_NAMES = new Set([+ "workflow_start", "workflow_status", "workflow_finish", "workflow_cancel",+ "skills_search", "skills_read", "projects_list", "project_capabilities", "project_mcp_tools", "project_mcp_call", "project_function_call",+ "read_pipeline", "screen_capture", "fs_list", "fs_read", "fs_search", "fs_write", "fs_upload_file",+ "exec_run", "exec_job_start", "exec_job_status", "exec_job_cancel",+ "agent_session_current", "agent_session_rename",+ "local_agents_list", "local_agent_inbox", "local_agent_message_send", "local_agent_reply", "local_agent_request_wait",+] as const);++const TITLES: Record<string, string> = {+ workflow_start: "Start Workflow", workflow_status: "Workflow Status", workflow_finish: "Finish Workflow", workflow_cancel: "Cancel Workflow",+ skills_search: "Search Skills", projects_list: "List Projects", project_capabilities: "Project Capabilities",+ project_mcp_tools: "List Project MCP Tools", project_mcp_call: "Call Project MCP Tool", project_function_call: "Call Project Function",+ read_pipeline: "Run Read Pipeline", fs_list: "List Files", fs_read: "Read File", fs_search: "Search Directories", fs_write: "Write File",+ exec_run: "Run Command", exec_job_start: "Start Command Job", exec_job_status: "Command Job Status", exec_job_cancel: "Cancel Command Job",+ agent_session_current: "Current Agent Session", agent_session_rename: "Rename Agent Session",+ local_agents_list: "List Local Agents", local_agent_inbox: "Receive Local Agent Messages",+ local_agent_message_send: "Send Local Agent Message", local_agent_reply: "Reply to Local Agent", local_agent_request_wait: "Wait for Local Agent Reply",+ a2a_agent_discover: "Discover A2A Agent", a2a_agents_list: "List A2A Agents", a2a_message_send: "Send A2A Message",+ cloudflare_dns_upsert: "Upsert Cloudflare DNS", hostinger_dns_upsert: "Upsert Hostinger DNS",+};+const ACRONYMS = new Map([["mcp", "MCP"], ["a2a", "A2A"], ["dns", "DNS"], ["fs", "Files"], ["api", "API"], ["ui", "UI"]]);++export function toolTitle(name: string): string {+ if (TITLES[name]) return TITLES[name];+ return name.split(/[_\.]+/).filter(Boolean).map((word) => ACRONYMS.get(word) ?? `${word[0]?.toUpperCase() ?? ""}${word.slice(1)}`).join(" ").slice(0, 80);+}++// Only declarations that can overwrite/delete/send/cancel or run arbitrary code+// need an override. Everything else inherits the safe scope-based default below.+const DESTRUCTIVE = new Set([+ "fs_write", "fs_upload_file", "fs_move", "fs_copy", "fs_delete",+ "exec_run", "exec_job_start", "exec_job_cancel", "project_function_call", "project_mcp_call",+ "local_agent_message_send", "local_agent_reply", "a2a_message_send", "a2a_task_cancel", "a2a_agent_remove",+ "cloudflare_dns_upsert", "hostinger_dns_upsert", "apps_power", "browser_power", "tool_forge_promote",+ "agent_memory_forget", "project_memory_upsert", "workflow_cancel",+]);++const OPEN_WORLD = new Set([+ "exec_run", "exec_job_start", "project_function_call", "project_mcp_call", "fs_upload_file",+ "a2a_agent_discover", "a2a_message_send", "a2a_task_get", "a2a_task_cancel", "a2a_handoff",+ "infra_provider_doctor", "dokploy_projects_list", "dokploy_project_ensure", "cloudflare_zones_list",+ "cloudflare_dns_upsert", "hostinger_dns_upsert",+]);++export function completeToolAnnotations(tool: McpTool): McpToolAnnotations {+ const supplied = tool.annotations ?? {};+ return {+ readOnlyHint: typeof supplied.readOnlyHint === "boolean" ? supplied.readOnlyHint : tool.scope === "read",+ destructiveHint: typeof supplied.destructiveHint === "boolean" ? supplied.destructiveHint : DESTRUCTIVE.has(tool.name),+ openWorldHint: typeof supplied.openWorldHint === "boolean" ? supplied.openWorldHint : OPEN_WORLD.has(tool.name),+ ...(typeof supplied.idempotentHint === "boolean" ? { idempotentHint: supplied.idempotentHint } : {}),+ };+}++export function toolSecuritySchemes(tool: McpTool): McpSecurityScheme[] {+ return tool.securitySchemes ?? [{ type: "oauth2", scopes: [tool.scope] }];+}++export function toolAllowedForProfile(name: string, profile: McpToolProfile = "full"): boolean {+ return profile === "full" || CHATGPT_TOOL_NAMES.has(name as never);+}++function compactText(value: string, max = 280): string {+ const clean = value.replace(/\s+/g, " ").trim();+ if (clean.length <= max) return clean;+ const cut = clean.slice(0, max - 1);+ const sentence = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("; "));+ return `${(sentence > 100 ? cut.slice(0, sentence + 1) : cut).trim()}…`;+}++function compactSchema(value: unknown): unknown {+ if (Array.isArray(value)) return value.map(compactSchema);+ if (!value || typeof value !== "object") return value;+ const out: Record<string, unknown> = {};+ for (const [key, item] of Object.entries(value as Record<string, unknown>)) {+ if (key === "description" && typeof item === "string") out[key] = compactText(item, 180);+ else out[key] = compactSchema(item);+ }+ return out;+}++export function toolDescriptor(tool: McpTool, profile: McpToolProfile = "full") {+ const securitySchemes = toolSecuritySchemes(tool);+ const meta = { ...(tool.meta ?? {}), securitySchemes };+ const compact = profile === "chatgpt";+ 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 } : {}),+ securitySchemes,+ annotations: completeToolAnnotations(tool),+ _meta: meta,+ };+}++export function visibleToolsForProfile(tools: readonly McpTool[], scope: Scope, profile: McpToolProfile = "full"): McpTool[] {+ const rank: Record<Scope, number> = { read: 0, write: 1, exec: 2 };+ return tools.filter((tool) => rank[scope] >= rank[tool.scope] && toolAllowedForProfile(tool.name, profile));+}diff --git a/lib/mcp/tool-kit.ts b/lib/mcp/tool-kit.tsindex f5a1287f..474d870a 100644--- a/lib/mcp/tool-kit.ts+++ b/lib/mcp/tool-kit.ts@@ -1,5 +1,6 @@import type { AuditAction } from "@/lib/host";import type { Scope } from "./scope";+import type { McpToolProfile } from "./tool-contract";// Shared shapes for the MCP tool catalog. EVERY handler goes through lib/host — never node fs or// child_process directly — so all of it inherits the bounds that already guard@@ -39,11 +40,17 @@ export interface McpRunContext {workflowActor?: string;/** Client-scoped learned-recipe owner; survives individual session rotation. */recipeActor?: string;+ /** Client-specific static tool projection; project capabilities stay dynamic. */+ toolProfile?: McpToolProfile;}export interface McpTool {name: string;+ /** Human-readable label advertised to MCP hosts. Generated from name when omitted. */+ title?: string;description: string;+ /** Optional shorter description for the compact ChatGPT scan profile. */+ chatgptDescription?: string;scope: Scope;inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };/** MCP Apps structured output contract. */@@ -52,7 +59,9 @@ export interface McpTool {* text fallback backward compatible while exposing a smaller, explicitly safe* object to a widget. */toStructuredContent?: (result: unknown) => Record<string, unknown> | undefined;- annotations?: Record<string, boolean>;+ annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean; openWorldHint?: boolean; idempotentHint?: boolean };+ /** Per-tool auth policy advertised to MCP hosts. Defaults to OAuth with this tool's minimum MSO scope. */+ securitySchemes?: Array<{ type: "oauth2"; scopes: string[] } | { type: "noauth" }>;/** MCP Apps / OpenAI metadata: UI resource binding, visibility and file params. */meta?: Record<string, unknown>;run: (a: Record<string, unknown>, context: McpRunContext) => Promise<unknown>;@@ -89,4 +98,4 @@ export const S = (properties: Record<string, unknown>, required?: string[]) =>({ type: "object" as const, properties, ...(required ? { required } : {}) });export const PATH_P = { path: { type: "string", description: "Absolute path on the VPS, or ~/… for the owner's home." } };-export const READ_ONLY = { readOnlyHint: true, idempotentHint: true };+export const READ_ONLY = { readOnlyHint: true, destructiveHint: false, openWorldHint: false, idempotentHint: true };diff --git a/lib/mcp/tools-discovery.test.ts b/lib/mcp/tools-discovery.test.tsindex eccbbe7b..f71445a9 100644--- a/lib/mcp/tools-discovery.test.ts+++ b/lib/mcp/tools-discovery.test.ts@@ -111,11 +111,13 @@ describe("projects_list", () => {describe("project_capabilities", () => {it("returns only public capability metadata for one exact project", async () => {const result = await run("project_capabilities", { project: await projectId(widgetA) }) as {- capabilities: { mcp?: { config: string }; functions?: { valid: boolean; tools?: Array<{ name: string }> } };+ capabilities: { mcp?: { config: string; servers?: Array<{ name: string; transport: string; auth: string }> }; functions?: { valid: boolean; tools?: Array<{ name: string }> } };};- expect(result.capabilities.mcp).toEqual({ config: ".mcp.json" });+ expect(result.capabilities.mcp).toEqual({ config: ".mcp.json", servers: [{ name: "local", transport: "stdio", auth: "none" }] });expect(result.capabilities.functions).toMatchObject({ valid: true, tools: [{ name: "widget_status" }] });- expect(JSON.stringify(result)).not.toContain(process.execPath);+ const serialized = JSON.stringify(result);+ expect(serialized).not.toContain(process.execPath);+ expect(serialized).not.toContain("ignored-secret-free-fixture");});});diff --git a/lib/mcp/tools-discovery.ts b/lib/mcp/tools-discovery.tsindex 71d065b7..02b0c78d 100644--- a/lib/mcp/tools-discovery.ts+++ b/lib/mcp/tools-discovery.ts@@ -1,4 +1,4 @@-import { listProjects, projectCapabilities, resolveProjectHint, PROJECT_LIMITS } from "@/lib/host";+import { listProjects, projectCapabilities, publicProjectMcpServers, readProjectMcpServers, resolveProjectHint, PROJECT_LIMITS } from "@/lib/host";import { catalogSkillsDetailed, resolveSkill, readSkillFile, skillIsExecutableByDefault, SKILL_SCAN_LIMITS } from "@/lib/skills/catalog";import { type McpTool, str, opt, S, READ_ONLY } from "./tool-kit";@@ -28,6 +28,7 @@ export const DISCOVERY_TOOLS: McpTool[] = ["Reports whether a regular .mcp.json exists and, when present, the public name/description/schema metadata from .mso/functions.json. " +"Project function commands are deliberately withheld; execution is only through project_function_call at exec scope. " +"Nothing is enabled globally: projects without these files return an empty capability object.",+ chatgptDescription: "Inspect one selected project for opt-in MSO functions and project MCP server aliases. Secrets and project MCP tool names stay hidden until project_mcp_tools is called.",scope: "read",annotations: READ_ONLY,limit: { key: "projects.capabilities", max: 60, windowMs: 60_000 },@@ -37,7 +38,9 @@ export const DISCOVERY_TOOLS: McpTool[] = [run: async (a) => {const project = await resolveProjectHint(str(a, "project"));if (!project) throw new Error(`project not found: ${String(a.project)}`);- return { project: { id: project.id, name: project.name, path: project.path }, capabilities: (await projectCapabilities(project.path)) ?? {} };+ const capabilities = (await projectCapabilities(project.path)) ?? {};+ if (capabilities.mcp) capabilities.mcp.servers = publicProjectMcpServers(await readProjectMcpServers(project.path));+ return { project: { id: project.id, name: project.name, path: project.path }, capabilities };},},{diff --git a/lib/mcp/tools-learning-shared.ts b/lib/mcp/tools-learning-shared.tsindex 819f3472..302e391d 100644--- a/lib/mcp/tools-learning-shared.ts+++ b/lib/mcp/tools-learning-shared.ts@@ -1,6 +1,6 @@import type { EvidenceInput } from "@/lib/orchestration/types";-import { allows } from "./scope";import type { McpTool } from "./tool-kit";+import { visibleToolsForProfile, type McpToolProfile } from "./tool-contract";export function optionalStringList(value: unknown, max = 40): string[] {return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string" && Boolean(item.trim())).slice(0, max) : [];@@ -29,9 +29,9 @@ export function evidenceSchema() {};}-export async function visibleTools(scope: "read" | "write" | "exec"): Promise<McpTool[]> {+export async function visibleTools(scope: "read" | "write" | "exec", profile: McpToolProfile = "full"): Promise<McpTool[]> {const { TOOLS } = await import("./tools");- return TOOLS.filter((tool) => allows(scope, tool.scope));+ return visibleToolsForProfile(TOOLS, scope, profile);}export const WORKFLOW_PROGRESS_OUTPUT = {diff --git a/lib/mcp/tools-project-mcp.ts b/lib/mcp/tools-project-mcp.tsnew file mode 100644index 00000000..d75e2551--- /dev/null+++ b/lib/mcp/tools-project-mcp.ts@@ -0,0 +1,46 @@+import { callProjectMcpTool, listProjectMcpTools, publicProjectMcpServers, readProjectMcpServers, resolveProjectHint } from "@/lib/host";+import { type McpTool, S, str } from "./tool-kit";++export const PROJECT_MCP_TOOLS: McpTool[] = [+ {+ name: "project_mcp_tools",+ title: "List Project MCP Tools",+ description: "Discover tools from one MCP server declared by an explicitly selected project's .mcp.json. Server aliases and tool schemas are returned on demand; config, env, headers, and credentials are never returned and project tools never join MSO's global catalog.",+ chatgptDescription: "List tools from one MCP server declared by a selected project's .mcp.json. Project tool names stay dynamic and never enter MSO's global catalog.",+ scope: "exec",+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false },+ audit: { action: "exec.run" as const, targetArg: "server" },+ limit: { key: "projects.mcp.read", max: 30, windowMs: 60_000 },+ inputSchema: S({+ project: { type: "string", description: "Exact project id/path/name from projects_list." },+ server: { type: "string", description: "MCP server alias returned by project_capabilities." },+ }, ["project", "server"]),+ run: async (a) => {+ const project = await resolveProjectHint(str(a, "project")); if (!project) throw new Error(`project not found: ${String(a.project)}`);+ const servers = publicProjectMcpServers(await readProjectMcpServers(project.path));+ const selected = servers.find((server) => server.name === str(a, "server")); if (!selected) throw new Error("project MCP server not found");+ return { project: { id: project.id, name: project.name }, server: selected, tools: await listProjectMcpTools(project.path, selected.name) };+ },+ },+ {+ name: "project_mcp_call",+ title: "Call Project MCP Tool",+ description: "Call one exact tool on one MCP server declared by a validated project's .mcp.json. The project MCP configuration stays server-side; MSO launches/calls it with credential-scrubbed process environment or a guarded remote transport and returns only the MCP tool result.",+ chatgptDescription: "Call one exact tool from a selected project's MCP server. The project's MCP config and credentials stay server-side.",+ scope: "exec",+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false },+ limit: { key: "projects.mcp.call", max: 30, windowMs: 60_000 },+ audit: { action: "exec.run" as const, targetArg: "server" },+ result: { maxTextBytes: 64 * 1024, overflowHint: "Project MCP result was compacted; request a narrower project tool call." },+ inputSchema: S({+ project: { type: "string", description: "Exact project id/path/name from projects_list." },+ server: { type: "string", description: "Project MCP server alias from project_capabilities." },+ tool: { type: "string", description: "Exact tool name from project_mcp_tools." },+ arguments: { type: "object", description: "Arguments matching that dynamic tool's input schema.", additionalProperties: true },+ }, ["project", "server", "tool"]),+ run: async (a) => {+ const project = await resolveProjectHint(str(a, "project")); if (!project) throw new Error(`project not found: ${String(a.project)}`);+ return { project: { id: project.id, name: project.name }, server: str(a, "server"), tool: str(a, "tool"), result: await callProjectMcpTool(project.path, str(a, "server"), str(a, "tool"), a.arguments ?? {}) };+ },+ },+];diff --git a/lib/mcp/tools-workflow-start.ts b/lib/mcp/tools-workflow-start.tsindex 3b327166..381e51c4 100644--- a/lib/mcp/tools-workflow-start.ts+++ b/lib/mcp/tools-workflow-start.ts@@ -49,7 +49,7 @@ export const WORKFLOW_START_TOOL: McpTool =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 tools = await visibleTools(context.scope, context.toolProfile);const intentRoute = routeIntentText(intent);const routedTools = intentRoute.catalogMatched? tools.filter((tool) => intentRoute.tools.includes(tool.name) || tool.name === "workflow_start")@@ -131,7 +131,7 @@ export const WORKFLOW_START_TOOL: McpTool =...(search.recommendedRecipe ? { recipeUsed: search.recommendedRecipe.id } : {}),createdAt: new Date().toISOString(),};- const toolset = toolsetInfo(tools, context.scope);+ const toolset = toolsetInfo(tools, context.scope, context.toolProfile);// Discovery incompleteness travels WITH the bootstrap. A model told "here is the// project and the trusted skills" will not re-check whether the scan covered the// whole box; if it did not, it has to be told in the same breath.diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex 91ec987a..fc053b6f 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -12,6 +12,7 @@ import { LOCAL_AGENT_TOOLS } from "./tools-local-agents";import { SUBAGENT_TOOLS } from "./tools-subagents";import { FORGE_TOOLS } from "./tools-forge";import { READ_PIPELINE_TOOLS } from "./tools-read-pipeline";+import { PROJECT_MCP_TOOLS } from "./tools-project-mcp";import { withWorkflowContext } from "./tool-context";// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,@@ -221,4 +222,4 @@ const MUTATE_TOOLS: McpTool[] = [},];-export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));+export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex 0e681066..72c1f6fe 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -1,10 +1,11 @@import { createHash } from "crypto";import type { Scope } from "./scope";import type { McpTool } from "./tool-kit";+import { toolDescriptor, type McpToolProfile } from "./tool-contract";-export const MCP_SERVER_VERSION = "1.6.0";-export const MCP_TOOLSET_VERSION = "2026.09.03.2";-export const MCP_TOOLSET_CHANGED_AT = "2026-09-02T20:39:00Z";+export const MCP_SERVER_VERSION = "1.7.0";+export const MCP_TOOLSET_VERSION = "2026.09.03.3";+export const MCP_TOOLSET_CHANGED_AT = "2026-09-03T07:45:00Z";export type McpToolsetInfo = {serverVersion: string;@@ -12,24 +13,15 @@ export type McpToolsetInfo = {hash: string;changedAt: string;scope?: Scope;+ profile?: McpToolProfile;toolCount: number;byScope: Record<Scope, number>;names: string[];};-export function toolsetInfo(tools: readonly McpTool[], scope?: Scope): McpToolsetInfo {+export function toolsetInfo(tools: readonly McpTool[], scope?: Scope, profile: McpToolProfile = "full"): 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,- outputSchema: tool.outputSchema,- annotations: tool.annotations,- meta: tool.meta,- result: tool.result,- limit: tool.limit,- }));+ const hashInput = rows.map((tool) => ({ descriptor: toolDescriptor(tool, profile), scope: tool.scope, result: tool.result, 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;@@ -39,6 +31,7 @@ export function toolsetInfo(tools: readonly McpTool[], scope?: Scope): McpToolsehash,changedAt: MCP_TOOLSET_CHANGED_AT,...(scope ? { scope } : {}),+ ...(profile !== "full" ? { profile } : {}),toolCount: rows.length,byScope,names: rows.map((tool) => tool.name),diff --git a/lib/orchestration/capability-catalog.mjs b/lib/orchestration/capability-catalog.mjsindex 38c250b8..b481a9af 100644--- a/lib/orchestration/capability-catalog.mjs+++ b/lib/orchestration/capability-catalog.mjs@@ -19,6 +19,7 @@ const ROUTES = [/\b(read|inspect|show|open|cat|baca|lihat|cek|check)\b.{0,220}(?:~\/|\/(?:home|tmp|var|srv|opt|run)\/)[^\s,;]+/i,], tools: ["fs_read"], budget: 8_000 },{ id: "file-write", priority: 80, patterns: [/\b(write|edit|update|modify|patch|refactor|fix|ubah|perbarui|perbaiki|rapikan)\b.*\b(file|readme|config|source|code|docs?|berkas|kode|dokumentasi)\b/i], tools: ["fs_read", "fs_write"], budget: 12_000 },+ { id: "project-mcp", priority: 96, patterns: [/\b(project mcp|mcp server|mcp tool|\.mcp\.json|project connector)\b/i], tools: ["project_capabilities", "project_mcp_tools", "project_mcp_call"], budget: 10_000 },{ id: "project-function", priority: 90, patterns: [/\b(project function|declared function|automation function|project capability)\b/i], tools: ["project_capabilities", "project_function_call"], budget: 10_000 },{ id: "project-discovery", priority: 65, patterns: [/\b(find|list|locate|which|cari|temukan|daftar)\b.*\b(project|repo|repository|workspace|proyek)\b/i], tools: ["projects_list"], budget: 8_000 },{ id: "skills", priority: 65, patterns: [/\b(skill|capability|recipe|how do i|how to|best practice|cara|kemampuan)\b/i], tools: ["skills_search", "skills_read"], budget: 10_000 },diff --git a/lib/os-api/http-adapter.ts b/lib/os-api/http-adapter.tsindex 7691ed8d..9b280559 100644--- a/lib/os-api/http-adapter.ts+++ b/lib/os-api/http-adapter.ts@@ -40,7 +40,7 @@ const toSummary = (a: ManagedAppWire): ManagedApp => ({running: a.state === "running" || a.state === "unhealthy" || a.state === "starting",});-// Live adapter → REST + SSE against the VPS daemon / Control Room agent at+// Live adapter → REST + SSE against the VPS daemon / legacy control agent at// {baseUrl}/api/v1. Auth = the signed session cookie, sent automatically on// same-origin requests (no Bearer token). Host actions stay allowlisted// server-side; this is just the client.diff --git a/lib/os-api/mock-data.ts b/lib/os-api/mock-data.tsindex 5e976cfe..b3f9687b 100644--- a/lib/os-api/mock-data.ts+++ b/lib/os-api/mock-data.ts@@ -18,11 +18,11 @@ export const d = (name: string): FsEntry => ({ name, kind: "dir", size: 0 });export const MOCK_FS: Record<string, FsEntry[]> = {"/": [d("Projects"), d("Downloads"), d("Documents"), d("apps"),f("readme.md", 1840, "md"), f("notes.txt", 612, "txt")],- "/Projects": [d("example-next-app"), d("control-room"), f("TODO.md", 980, "md")],+ "/Projects": [d("example-next-app"), d("example-service"), f("TODO.md", 980, "md")],"/Projects/example-next-app": [d("src"), d("logs"), f("package.json", 2_040, "json"), f("README.md", 4_120, "md")],"/Projects/example-next-app/src": [f("index.ts", 3_200, "ts"), f("app.tsx", 5_600, "tsx"), f("worker.ts", 2_900, "ts"), f("styles.css", 1_400, "css")],"/Projects/example-next-app/logs": [f("worker.log", 2_480, "log"), f("deploy.log", 1_900, "log")],- "/Projects/control-room": [f("deploy.sh", 1_120, "sh"), f("config.json", 860, "json")],+ "/Projects/example-service": [f("deploy.sh", 1_120, "sh"), f("config.json", 860, "json")],"/Downloads": [f("invoice.pdf", 240_000, "pdf"), f("backup.zip", 156_000_000, "zip"),f("dataset.csv", 4_200_000, "csv"), f("archive.tar.gz", 64_000_000, "gz")],"/Documents": [d("Invoices"), f("resume.pdf", 320_000, "pdf"), f("plan.md", 2_300, "md")],diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjsindex 57e76358..a6a3f279 100755--- a/scripts/check-docs.mjs+++ b/scripts/check-docs.mjs@@ -62,41 +62,51 @@ for (const name of appOnlyTools) {const counts = { read: 0, write: 0, exec: 0 };for (const scope of documentedTools.values()) counts[scope] += 1;const marker = `server=${server} version=${version} tools=${documentedTools.size} read=${counts.read} write=${counts.write} exec=${counts.exec}`;-const markerDocs = ["docs/MCP.md", "docs/CHATGPT-PLUGIN.md", "docs/CONNECTORS-GATEWAY-INTEGRATION.md", "docs/ARCHITECTURE.md", "CLAUDE.md"];+const markerDocs = ["docs/MCP.md", "docs/ARCHITECTURE.md", "CLAUDE.md"];for (const file of markerDocs) {const text = read(file);if (!text.includes(`<!-- mcp-toolset: ${marker} -->`)) {fail.push(`${file}: MCP marker stale; expected ${marker}`);}}-for (const file of ["docs/MCP.md", "docs/CHATGPT-PLUGIN.md", "docs/CONNECTORS-GATEWAY-INTEGRATION.md"]) {+for (const file of ["docs/MCP.md"]) {const text = read(file);for (const name of documentedTools.keys()) {if (!text.includes(`\`${name}\``)) fail.push(`${file}: MCP tool ${name} is not documented`);}}-// ChatGPT's human scope catalog must match source scope membership, not merely contain every name somewhere.+// ChatGPT uses a deliberately compact static profile. Parse its SSOT name set+// from tool-contract.ts, then require the ChatGPT guide to match THAT profile+// rather than the full MSO catalog. Project-owned dynamic MCP names never belong+// in this set.+const toolContract = read("lib/mcp/tool-contract.ts");+const profileBlock = /CHATGPT_TOOL_NAMES\s*=\s*new Set\(\[([\s\S]*?)\]\s*as const\)/.exec(toolContract)?.[1] ?? "";+const chatgptNames = [...profileBlock.matchAll(/"([^"]+)"/g)].map((match) => match[1]);+if (!chatgptNames.length) fail.push("could not parse CHATGPT_TOOL_NAMES from lib/mcp/tool-contract.ts");+for (const name of chatgptNames) if (!tools.has(name)) fail.push(`ChatGPT profile references missing MCP tool ${name}`);+const chatgptModelTools = new Map(chatgptNames.filter((name) => !appOnlyTools.has(name)).map((name) => [name, tools.get(name)]));+const chatgptCounts = { read: 0, write: 0, exec: 0 };+for (const scope of chatgptModelTools.values()) if (scope) chatgptCounts[scope] += 1;+const chatgptAppOnly = chatgptNames.filter((name) => appOnlyTools.has(name)).length;+const profileMarker = `server=${server} version=${version} tools=${chatgptModelTools.size} read=${chatgptCounts.read} write=${chatgptCounts.write} exec=${chatgptCounts.exec} app-only=${chatgptAppOnly} total=${chatgptNames.length}`;const chatgpt = read("docs/CHATGPT-PLUGIN.md");+if (!chatgpt.includes(`<!-- mcp-chatgpt-profile: ${profileMarker} -->`)) fail.push(`docs/CHATGPT-PLUGIN.md: ChatGPT profile marker stale; expected ${profileMarker}`);+for (const name of chatgptModelTools.keys()) if (!chatgpt.includes(`\`${name}\``)) fail.push(`docs/CHATGPT-PLUGIN.md: ChatGPT profile tool ${name} is not documented`);const scopeOrder = ["read", "write", "exec"];for (let i = 0; i < scopeOrder.length; i += 1) {const scope = scopeOrder[i];const next = scopeOrder[i + 1];- const expected = [...documentedTools].filter(([, value]) => value === scope).map(([name]) => name).sort();+ const expected = [...chatgptModelTools].filter(([, value]) => value === scope).map(([name]) => name).sort();const heading = scope === "read"- ? `### \`read\` — ${expected.length} model/operator tools`- : `### \`${scope}\` — ${scope === "write" ? "read" : "write"} + ${expected.length} tools`;- if (!chatgpt.includes(heading)) fail.push(`docs/CHATGPT-PLUGIN.md: stale ${scope} scope heading; expected ${heading}`);+ ? `### \`read\` — ${expected.length} ChatGPT model tools`+ : `### \`${scope}\` — + ${expected.length} ChatGPT model tools`;+ if (!chatgpt.includes(heading)) fail.push(`docs/CHATGPT-PLUGIN.md: stale ${scope} profile heading; expected ${heading}`);const start = chatgpt.indexOf(`### \`${scope}\` —`);- const end = next ? chatgpt.indexOf(`### \`${next}\` —`, start + 1) : chatgpt.indexOf("\n`exec_run` is full host shell power", start + 1);- if (start < 0 || end < 0) {- fail.push(`docs/CHATGPT-PLUGIN.md: could not parse ${scope} scope block`);- continue;- }+ const end = next ? chatgpt.indexOf(`### \`${next}\` —`, start + 1) : chatgpt.indexOf("\n### App-only ChatGPT bridge", start + 1);+ if (start < 0 || end < 0) { fail.push(`docs/CHATGPT-PLUGIN.md: could not parse ${scope} profile block`); continue; }const actual = [...chatgpt.slice(start, end).matchAll(/^- \`([^\`]+)\`/gm)].map((match) => match[1]).sort();- if (actual.join("\n") !== expected.join("\n")) {- fail.push(`docs/CHATGPT-PLUGIN.md: ${scope} scope tool list differs from source catalog`);- }+ if (actual.join("\n") !== expected.join("\n")) fail.push(`docs/CHATGPT-PLUGIN.md: ${scope} ChatGPT profile list differs from source contract`);}// MCP.md's scope table must match source membership exactly.@@ -109,24 +119,6 @@ for (const scope of scopeOrder) {if (actual.join("\n") !== expected.join("\n")) fail.push(`docs/MCP.md: ${scope} scope row differs from source catalog`);}-// The connectors contract repeats the scope partition for cross-repo mapping review.-const connectorDoc = read("docs/CONNECTORS-GATEWAY-INTEGRATION.md");-const connectorLabels = { read: "Read", write: "Write", exec: "Exec" };-for (let i = 0; i < scopeOrder.length; i += 1) {- const scope = scopeOrder[i];- const next = scopeOrder[i + 1];- const expected = [...documentedTools].filter(([, value]) => value === scope).map(([name]) => name).sort();- const expectedHeading = scope === "read"- ? `### Read (${expected.length} model/operator)`- : `### ${connectorLabels[scope]} (${expected.length} beyond ${scope === "write" ? "read" : "write"})`;- if (!connectorDoc.includes(expectedHeading)) fail.push(`docs/CONNECTORS-GATEWAY-INTEGRATION.md: stale ${scope} heading; expected ${expectedHeading}`);- const start = connectorDoc.indexOf(`### ${connectorLabels[scope]} (`);- const end = next ? connectorDoc.indexOf(`### ${connectorLabels[next]} (`, start + 1) : connectorDoc.indexOf("### App-only bridge", start + 1);- if (start < 0 || end < 0) { fail.push(`docs/CONNECTORS-GATEWAY-INTEGRATION.md: could not parse ${scope} block`); continue; }- const actual = [...connectorDoc.slice(start, end).matchAll(/`([^`]+)`/g)].map((match) => match[1]).sort();- if (actual.join("\n") !== expected.join("\n")) fail.push(`docs/CONNECTORS-GATEWAY-INTEGRATION.md: ${scope} scope list differs from source catalog`);-}-// --- Slice catalog counts.const dirs = (p) => readdirSync(join(ROOT, p), { withFileTypes: true }).filter((x) => x.isDirectory()).map((x) => x.name);const sliceCount = dirs("frontend/slices").length;diff --git a/scripts/gates.sh b/scripts/gates.shindex b741577f..f5108908 100755--- a/scripts/gates.sh+++ b/scripts/gates.sh@@ -3,7 +3,7 @@# that execs it.## Why it lives here and not in .git/hooks/pre-push: a hook is untracked, so a fresh-# clone had NO gates at all, and re-running an sc-git hook installer silently+# clone had NO gates at all, and a third-party hook installer silently# overwrote the file — dropping the audit and build guards and re-adding a# `check-slices.mjs` line for a script deleted on 2026-08-03, which blocks every# push. Both failure modes were documented in CLAUDE.md, and a doc is not a control.@@ -42,17 +42,10 @@ fifail() { echo ""; echo "❌ $1 push blocked."; [ -n "${2-}" ] && echo " $2"; exit 1; }# ── Guard 1 — typecheck + lint + test.-# sc-git's ci.js is used when present (it is the shared runner across this owner's-# repos) but must not be REQUIRED: a fresh clone on another machine has no such-# path, and silently skipping the whole guard there is exactly the hole this file-# exists to close. `bun run verify` is the in-repo equivalent.-SC_CI="/home/rahman/projects/opensource/si-coder-agent/skills/sc-git/scripts/ci.js"-if [ -f "$SC_CI" ]; then- node "$SC_CI" --skip build || fail "sc-git ci failed." "override (NOT recommended): git push --no-verify"-else- echo "▶ sc-git ci.js not present — running \`bun run verify\` instead"- bun run verify || fail "verify failed." "reproduce: bun run verify"-fi+# MSO is self-contained: a fresh clone must never depend on a sibling/private repo+# to decide whether it is safe to push. `bun run verify` is the canonical in-repo gate.+echo "▶ running MSO verify"+bun run verify || fail "verify failed." "reproduce: bun run verify"# ── Guard 1b — architecture. check-contrast is informational (a WCAG palette audit# is a design task, not a push blocker), so it is allowed to exit non-zero.@@ -67,17 +60,14 @@ node scripts/gen-changelog.mjs --check || fail "changelog stale — run: node scnode scripts/check-contrast.mjs || true# ── Guard 1c — dependency audit, high/critical only.-# Must live HERE rather than lean on ci.js: that runner has a hardcoded-# STEPS=['typecheck','lint','test','build'] and never invokes `verify`. The wrapper+# Must live HERE rather than rely on an external CI wrapper. The audit wrapper# skips (exit 0) when the registry is unreachable, so a network blip cannot fake a# CVE and block a push.node scripts/audit.mjs || fail "audit: unignored high/critical advisory."-# ── Guard 1d — build. ci.js above keeps `--skip build` ON PURPOSE: it would build in-# THIS directory, and `next build` wipes .next before compiling — which is what the-# live :4005 process is serving from. verify-build.sh compiles a throwaway copy of-# HEAD instead. Adds ~35 s to a push; if that ever becomes intolerable, DELETE this-# guard rather than "fixing" it by letting ci.js build in place.+# ── Guard 1d — build. Never build in THIS directory: `next build` wipes .next+# before compiling, while the live :4005 process may be serving from it.+# verify-build.sh compiles a throwaway copy of HEAD instead.bash scripts/verify-build.sh >/dev/null 2>&1 \&& echo "build: HEAD compiles (out-of-tree)." \|| fail "build failed." "reproduce: bash scripts/verify-build.sh"diff --git a/scripts/gen-changelog.mjs b/scripts/gen-changelog.mjsindex 765347b0..68981c82 100644--- a/scripts/gen-changelog.mjs+++ b/scripts/gen-changelog.mjs@@ -65,10 +65,11 @@ const SELF = /^docs\(changelog\)/i;for (const line of RAW.split("\n").filter(Boolean)) {const [hash, date, subject] = line.split("\0");if (SELF.test(subject ?? "")) continue;- const m = /^(\w+)(?:\(([^)]*)\))?!?:\s*(.+)$/.exec(subject ?? "");+ const publicSubject = (subject ?? "").replace(/record that [A-Za-z0-9._-]+ now consumes this MCP surface/gi, "record external MCP consumer compatibility");+ const m = /^(\w+)(?:\(([^)]*)\))?!?:\s*(.+)$/.exec(publicSubject);const type = m && LABEL.has(m[1]) ? m[1] : "other";if (!byDay.has(date)) byDay.set(date, []);- byDay.get(date).push({ hash, type, scope: m?.[2] ?? "", subject: m?.[3] ?? subject ?? "" });+ byDay.get(date).push({ hash, type, scope: m?.[2] ?? "", subject: m?.[3] ?? publicSubject });}// Collapse identical (type, scope, subject) within a day. A retried ship, adiff --git a/scripts/install-core.sh b/scripts/install-core.shindex fe66fabf..fb7d3790 100755--- a/scripts/install-core.sh+++ b/scripts/install-core.sh@@ -567,7 +567,7 @@ Environment=MSO_RUNTIME_INSTANCE_ID=$RUNTIME_INSTANCE_ID# at logout.## The UID IS WRITTEN OUT, NOT the %U specifier. Do not "tidy" this back to %U — it-# was tried and it FAILS: with User=antinrml and UID=1000, systemd 255 expanded %U+# was tried and it FAILS: with User=example and UID=1000, systemd 255 expanded %U# to 0, so the unit got XDG_RUNTIME_DIR=/run/user/0 and every systemctl --user# answered "No such file or directory" — the original bug wearing a new message.# Specifiers are expanded while the unit is parsed, before the NAME in User= hasdiff --git a/scripts/install.sh b/scripts/install.shindex 3cb9358b..75bdcc64 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -12,7 +12,7 @@ set -Eeuo pipefailumask 077CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"-CORE_SHA256="104a7ebc51b3d5a3ff068697eb0d263e45959656125e1d580612ca64206126e7"+CORE_SHA256="b769aea7c8b21a34d49222da6d6384ec4ebd917eb5cde97c7b62083e92217c91"CORE_EOF='# MSO_INSTALLER_CORE_EOF'TMP_INSTALLER=''diff --git a/scripts/mso-agent-sessions.test.ts b/scripts/mso-agent-sessions.test.tsindex 122e44d4..aa692b77 100644--- a/scripts/mso-agent-sessions.test.ts+++ b/scripts/mso-agent-sessions.test.ts@@ -2,9 +2,9 @@ import { describe, expect, it } from "vitest";import { formatSessionModified, resolveSessionQuery, sessionCompletionItems, sessionPromptHistory, visibleSessionRows } from "./mso-agent-sessions.mjs";const rows = [- { id: "20260901_120000_aaaaaaaa", name: "milo", title: "Deploy Baton", source: "cli", historyTurns: 10, createdAt: "2026-09-01T11:50:00.000Z", updatedAt: "2026-09-01T12:00:00.000Z" },+ { id: "20260901_120000_aaaaaaaa", name: "milo", title: "Deploy Example Project", source: "cli", historyTurns: 10, createdAt: "2026-09-01T11:50:00.000Z", updatedAt: "2026-09-01T12:00:00.000Z" },{ id: "20260901_110000_bbbbbbbb", name: "luna", title: "Audit MSO", source: "cli", historyTurns: 4, createdAt: "2026-09-01T10:50:00.000Z", updatedAt: "2026-09-01T11:00:00.000Z" },- { id: "20260901_100000_cccccccc", name: "nara", title: "Older Baton notes", source: "cli", historyTurns: 2, createdAt: "2026-09-01T09:50:00.000Z", updatedAt: "2026-09-01T10:00:00.000Z" },+ { id: "20260901_100000_cccccccc", name: "nara", title: "Older Example notes", source: "cli", historyTurns: 2, createdAt: "2026-09-01T09:50:00.000Z", updatedAt: "2026-09-01T10:00:00.000Z" },];describe("MSO Agent session resolver", () => {@@ -19,7 +19,7 @@ describe("MSO Agent session resolver", () => {});it("refuses ambiguous fuzzy titles instead of guessing", () => {- const result = resolveSessionQuery(rows, "Baton");+ const result = resolveSessionQuery(rows, "Example");expect(result.session).toBeNull();expect(result.ambiguous).toHaveLength(2);});@@ -28,7 +28,7 @@ describe("MSO Agent session resolver", () => {const now = Date.parse("2026-09-01T12:05:00.000Z");const items = sessionCompletionItems([rows[1], rows[0], rows[2]], "", now);expect(items.map((item) => item.text)).toEqual(["@milo", "@luna", "@nara"]);- expect(items[0]).toMatchObject({ text: "@milo", value: rows[0].id, meta: "Deploy Baton · modified 5m ago" });+ expect(items[0]).toMatchObject({ text: "@milo", value: rows[0].id, meta: "Deploy Example Project · modified 5m ago" });expect(`${items[0].text} ${items[0].meta}`).not.toContain(rows[0].id);expect(sessionCompletionItems(rows, "audit", now)).toHaveLength(1);expect(sessionCompletionItems(rows, "bbbbbbbb", now)[0]?.text).toBe("@luna");diff --git a/security/codex-components.json b/security/codex-components.jsonindex ae46ca58..5832d636 100644--- a/security/codex-components.json+++ b/security/codex-components.json@@ -180,7 +180,6 @@"docs/AUDIT-2026-06-11.md","docs/AUDIT-2026-08-24.md","docs/CHATGPT-PLUGIN.md",- "docs/CONNECTORS-GATEWAY-INTEGRATION.md","docs/DEVELOPMENT.md","docs/FAQ.md","docs/HERMES-INTEGRATION.md",