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(projects): add opt-in function capabilities
rahmanef63e0d5c62a74d6
diff --git a/.env.example b/.env.exampleindex dd4e98d4..e4eecf98 100644--- a/.env.example+++ b/.env.example@@ -217,3 +217,9 @@ OS_SESSION_SECRET=# Internal loopback origin used by the read-only `screen_capture` MCP tool. The# implementation refuses non-loopback values. Default http://127.0.0.1:4005.# OS_SCREENSHOT_ORIGIN=http://127.0.0.1:4005++# Optional exact machine-to-machine ingress for PROJECT integrations on a managed+# app host. Stock MSO leaves this unset and exposes no such lane. JSON array, max+# 8 entries; POST only; target MUST be loopback; auth currently hmac-v2-json.+# MSO only prefilters HMAC-shaped headers — the loopback app verifies the secret.+# OS_PROJECT_INGRESS_ROUTES=[{"app":"hermes","method":"POST","path":"/webhooks/project-example","target":"http://127.0.0.1:8644/webhooks/project-example","auth":"hmac-v2-json","maxBodyBytes":262144}]diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex d4e5debe..f424a7d2 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -4,6 +4,12 @@Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;this is the *what*, and it is what Settings → About shows as “What's new”.+## 2026-08-21++**Added**++- `projects` add opt-in function capabilities+## 2026-08-20**Added**diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.mdindex 04e3b496..d015f4ee 100644--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md@@ -4,7 +4,7 @@## Cross-repo contract-MSO currently exposes **26 tool names** (server `1.5.3`, toolset `2026.08.20.6`). The gateway manifest still maps **15** of them through literal `x-upstream` strings:+MSO currently exposes **28 tool names** (server `1.6.0`, toolset `2026.08.21.1`). The gateway manifest still maps **15** of them through literal `x-upstream` strings:```json{ "id": "mso.fs.delete", "x-upstream": "fs_delete" }@@ -38,6 +38,8 @@ The gateway has not yet synchronized the tools added or deliberately withheld fr| `workflow_finish` | added later; exact-id verified recipe boundary || `fs_upload_file` | added later; ChatGPT `openai/fileParams` binding the gateway does not model || `projects_list` | added 2026-08-20; enumerates every configured project container |+| `project_capabilities` | added 2026-08-21; detects opt-in project MCP/function manifests without exposing secrets |+| `project_function_call` | added 2026-08-21; exec-scope generic runner for functions declared by a project || `skills_list` | added 2026-08-20; global + per-project skill catalog with trust || `skills_read` | added 2026-08-20; exact-catalog-id SKILL.md read, trusted tiers only |diff --git a/docs/MCP.md b/docs/MCP.mdindex cf973dfd..6ae1298d 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -59,14 +59,14 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe| Scope | Tools ||---|---|-| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` |+| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `project_capabilities` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` || `write` | + `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` |-| `exec` | + `exec_run` `browser_power` |+| `exec` | + `project_function_call` `exec_run` `browser_power` |Alfa — the in-app assistant — has the same host capabilities under dot.case names,and `lib/mcp/parity.test.ts` fails if one surface gains a tool the other lackswithout a written reason. `skills_search` maps to Alfa's `skills.search`.-`screen_capture`, `projects_list`, `fs_upload_file`, `workflow_start`, `workflow_cancel` and+`screen_capture`, `projects_list`, `project_capabilities`, `project_function_call`, `fs_upload_file`, `workflow_start`, `workflow_cancel` and`workflow_finish` are explicitly MCP-only: the external connector needs visual proof,an explicit project enumeration and an actor-scoped task boundary, while Alfa alreadyruns inside the rendered shell, has the Files window and owns an in-app run boundary.@@ -104,10 +104,58 @@ 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.-Current catalog: **26 tools** (14 read, 10 write, 2 exec), server `1.5.3` / toolset-`2026.08.20.6`. `projects_list`, `skills_list` and `skills_read` are the new public-names in this release; `image_generation_status` and `image_generate` were removed-(see the migration note below).+Current catalog: **28 tools** (15 read, 10 write, 3 exec), server `1.6.0` / toolset+`2026.08.21.1`. `project_capabilities` and `project_function_call` add one stable+project-automation seam without creating a dynamic MCP tool catalog; existing tool names+remain unchanged.++## 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:++- `.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.++The manifest is versioned and intentionally uses **fixed argv**, not a shell template:++```json+{+ "version": 1,+ "functions": [{+ "name": "asset_status",+ "description": "Read the project's asset status.",+ "inputSchema": {+ "type": "object",+ "properties": { "id": { "type": "string" } },+ "required": ["id"],+ "additionalProperties": false+ },+ "command": ["bun", "run", "project:call", "--", "asset_status"]+ }]+}+```++`project_capabilities` is read-scope and returns only public name/description/schema+metadata. `project_function_call` is always **exec-scope**, even for a function named+"read": it executes project code. MSO spawns the manifest argv directly with no shell+and sends the model/caller's JSON object on stdin; caller values are never interpolated+into command arguments. The child receives the existing scrubbed environment, so MSO+credentials and provider tokens are not inherited. Projects without either file gain no+new 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.++For project callbacks that must enter a managed app (for example a signed webhook into a+loopback-only agent), deployments may opt into `OS_PROJECT_INGRESS_ROUTES`. It defaults+to empty. Routes are exact POST paths, max eight, loopback-only targets, and currently+require HMAC-V2-shaped JSON headers; the loopback service remains responsible for real+cryptographic verification.## Safe text inspection and overwritediff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex c327667f..996292ba 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -8,6 +8,28 @@ Running log of what shipped each phase. Newest at top.> Read those phases as history. **This file is the source of truth for what exists** —> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.+## 2026-08-21 — opt-in project MCP/function capabilities; stock MSO unchanged (DONE)++Project-specific automation no longer requires a business-specific feature in MSO. A+validated project may opt in with `.mcp.json` (presence only; contents/credentials are+never exposed) and `.mso/functions.json` (versioned public schemas + fixed argv). The+public MCP catalog stays stable: `project_capabilities` discovers one project's declared+surface and `project_function_call` executes one declared function at **exec** scope.+Function names are data, not dynamic MCP tool names, so switching projects does not alter+the model tool prefix or invalidate the prompt cache. Caller input is JSON stdin to+`spawn(argv)` — never shell interpolation — and child processes inherit the existing+credential-scrubbed environment. No manifest means no extra capability.++The same opt-in rule now applies to public machine ingress.+`OS_PROJECT_INGRESS_ROUTES` defaults to empty; when explicitly configured it permits at+most eight exact POST paths on known managed-app hosts, targets loopback HTTP only, and+requires HMAC-V2-shaped JSON traffic before the app-host CSRF gate. The loopback app still+verifies the real secret. There is no project/product name or webhook path compiled into+MSO. Tests pin both sides: stock MSO remains closed, malformed/off-box/wildcard routes fail+closed, `.mso` symlinks are ignored, project commands cannot interpolate caller strings+into a shell, and project function execution remains exec-only. Toolset advances to+`1.6.0` / `2026.08.21.1`: **28 tools** (15 read, 10 write, 3 exec).+## 2026-08-20 — lossless continuation and exact-id project resolution (DONE)The final fail-closed review found six remaining items. Five were continuation bugs of thediff --git a/frontend/slices/assistant/CONTRACT.md b/frontend/slices/assistant/CONTRACT.mdindex 4c0e12bc..a4829ee5 100644--- a/frontend/slices/assistant/CONTRACT.md+++ b/frontend/slices/assistant/CONTRACT.md@@ -161,7 +161,13 @@ Four reasons, and the third is the one that settles it:**Reaffirmed 2026-08-20** when MCP gained global project/skill discovery: capabilityscoping stayed deleted on both surfaces, and the removed MSO image generation was NOT-replaced by a per-agent toggle. **Done 2026-07-30.** The tool picker, the "Generalist / Curated — by skill" switch,+replaced by a per-agent toggle.++**Extended 2026-08-21 for project function calling:** project-specific function names+remain DATA, never additions/removals to the model tool array. MCP exposes the stable+`project_capabilities` + `project_function_call` pair; a project may opt in with+`.mso/functions.json`. Alfa keeps its existing stable host catalog and can use project+skills/files + approved `exec.run`; no project switch changes its cached tool prefix. **Done 2026-07-30.** The tool picker, the "Generalist / Curated — by skill" switch,the per-agent Skills grant list and every string that counted tools per agent aregone; `toolsForAgent()` went with them. `agent.allTools` and `agent.skills` remain onthe type because they are persisted and `store-migration.test.ts` covers them — theydiff --git a/lib/host/bounded-read.ts b/lib/host/bounded-read.tsindex f3cd7b1e..33573925 100644--- a/lib/host/bounded-read.ts+++ b/lib/host/bounded-read.ts@@ -24,6 +24,8 @@ export const BOUNDED_READ = {gitHead: 4 * 1024,gitRef: 4 * 1024,packedRefs: 1024 * 1024,+ projectFunctions: 256 * 1024,+ projectMcpConfig: 256 * 1024,} as const;export async function readBoundedRegularFile(file: string, maxBytes: number): Promise<string | null> {diff --git a/lib/host/index.ts b/lib/host/index.tsindex 1083deee..a19d2b8f 100644--- a/lib/host/index.ts+++ b/lib/host/index.ts@@ -11,6 +11,8 @@ export { runCommand } from "./exec";export { sha256Text, utf8Bytes } from "./hash";export { writeFileGuarded } from "./guarded-write";export { resolveProjectHint, inspectProject } from "./projects";+export { projectCapabilities, runProjectFunction } 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";export { normalizeProjectKey, projectAliasesFor, projectAliasTarget } from "./project-aliases";diff --git a/lib/host/project-capabilities.test.ts b/lib/host/project-capabilities.test.tsnew file mode 100644index 00000000..ee106ba7--- /dev/null+++ b/lib/host/project-capabilities.test.ts@@ -0,0 +1,80 @@+import { afterEach, describe, expect, it } from "vitest";+import { promises as fs } from "fs";+import os from "os";+import path from "path";+import { projectCapabilities, runProjectFunction } from "./project-capabilities";++const roots: string[] = [];+afterEach(async () => { await Promise.all(roots.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); });++async function project() {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-project-cap-"));+ roots.push(dir);+ await fs.mkdir(path.join(dir, ".mso"));+ return dir;+}++const manifest = (command: string[]) => ({+ version: 1,+ functions: [{+ name: "echo_payload",+ description: "Echo the JSON payload received on stdin.",+ inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"], additionalProperties: false },+ command,+ timeoutMs: 5000,+ }],+});++describe("project capability manifests", () => {+ it("is invisible when a project did not opt in", async () => {+ const dir = await project();+ expect(await projectCapabilities(dir)).toBeUndefined();+ });++ it("reports MCP + public function metadata without exposing argv or MCP contents", async () => {+ const dir = await project();+ await fs.writeFile(path.join(dir, ".mcp.json"), JSON.stringify({ mcpServers: { secretServer: { env: { TOKEN: "do-not-return" } } } }));+ await fs.writeFile(path.join(dir, ".mso/functions.json"), JSON.stringify(manifest([process.execPath, "-e", ""])), { mode: 0o600 });+ const capabilities = await projectCapabilities(dir);+ expect(capabilities?.mcp).toEqual({ config: ".mcp.json" });+ expect(capabilities?.functions).toMatchObject({ valid: true, version: 1, count: 1 });+ const text = JSON.stringify(capabilities);+ expect(text).toContain("echo_payload");+ expect(text).not.toContain("do-not-return");+ expect(text).not.toContain(process.execPath);+ });++ it("executes fixed argv with caller input on JSON stdin, never shell interpolation", async () => {+ const dir = await project();+ const code = "let s='';process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>process.stdout.write(JSON.stringify({payload:JSON.parse(s),fn:process.env.MSO_PROJECT_FUNCTION})))";+ await fs.writeFile(path.join(dir, ".mso/functions.json"), JSON.stringify(manifest([process.execPath, "-e", code])));+ const payload = { value: "$(touch /tmp/should-not-run); hello" };+ const result = await runProjectFunction(dir, "echo_payload", payload);+ expect(result.code).toBe(0);+ expect(JSON.parse(result.stdout)).toEqual({ payload, fn: "echo_payload" });+ });++ it("validates required fields and additionalProperties before spawning project code", async () => {+ const dir = await project();+ const code = "process.stdin.resume();process.stdin.on('end',()=>process.stdout.write('ran'))";+ await fs.writeFile(path.join(dir, ".mso/functions.json"), JSON.stringify(manifest([process.execPath, "-e", code])));+ await expect(runProjectFunction(dir, "echo_payload", {})).rejects.toThrow(/required input\.value/i);+ await expect(runProjectFunction(dir, "echo_payload", { value: "x", surprise: true })).rejects.toThrow(/unknown input\.surprise/i);+ });++ it("fails closed on a symlinked .mso directory or invalid manifest", async () => {+ const dir = await project();+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), "mso-project-cap-outside-"));+ roots.push(outside);+ await fs.rm(path.join(dir, ".mso"), { recursive: true });+ await fs.writeFile(path.join(outside, "functions.json"), JSON.stringify(manifest([process.execPath, "-e", ""])), { mode: 0o600 });+ await fs.symlink(outside, path.join(dir, ".mso"));+ expect(await projectCapabilities(dir)).toBeUndefined();+ await expect(runProjectFunction(dir, "echo_payload", {})).rejects.toThrow(/no \.mso\/functions\.json/i);++ const second = await project();+ await fs.writeFile(path.join(second, ".mso/functions.json"), JSON.stringify({ version: 1, functions: [{ name: "BAD NAME" }] }));+ expect(await projectCapabilities(second)).toMatchObject({ functions: { valid: false } });+ await expect(runProjectFunction(second, "anything", {})).rejects.toThrow(/invalid|name/i);+ });+});diff --git a/lib/host/project-capabilities.ts b/lib/host/project-capabilities.tsnew file mode 100644index 00000000..0f84496b--- /dev/null+++ b/lib/host/project-capabilities.ts@@ -0,0 +1,5 @@+// Stable facade: discovery and execution live in separate modules so read-scope+// manifest parsing cannot accidentally grow process-launch concerns.+export { projectCapabilities } from "./project-function-manifest";+export type { ProjectCapabilities, PublicProjectFunction } from "./project-function-manifest";+export { runProjectFunction } from "./project-function-runner";diff --git a/lib/host/project-containers.ts b/lib/host/project-containers.tsindex e602fdea..3928f201 100644--- a/lib/host/project-containers.ts+++ b/lib/host/project-containers.ts@@ -63,6 +63,7 @@ export type ProjectRow = {packageName?: string;packageVersion?: string;git?: { branch?: string; head?: string };+ capabilities?: import("./project-capabilities").ProjectCapabilities;};diff --git a/lib/host/project-function-manifest.ts b/lib/host/project-function-manifest.tsnew file mode 100644index 00000000..c4685f4f--- /dev/null+++ b/lib/host/project-function-manifest.ts@@ -0,0 +1,126 @@+// SERVER-ONLY. Opt-in capability metadata declared BY a project, not features+// baked into MSO. Every file read is bounded/O_NOFOLLOW; MCP config contents are+// never returned because they commonly contain credential wiring.+import { promises as fs } from "fs";+import path from "path";+import { BOUNDED_READ, readBoundedRegularFile } from "./bounded-read";+import { isUnderRoot } from "./paths";++export const PROJECT_FUNCTIONS_REL = ".mso/functions.json" as const;+export const PROJECT_MCP_REL = ".mcp.json" as const;+const MAX_FUNCTIONS = 32;+const MAX_ARGV = 16;+const MAX_ARG = 512;+const MAX_DESCRIPTION = 600;+const DEFAULT_TIMEOUT_MS = 30_000;++export type ProjectFunction = {+ name: string;+ description: string;+ inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[]; additionalProperties?: boolean };+ command: string[];+ timeoutMs: number;+};++export type PublicProjectFunction = Omit<ProjectFunction, "command">;+export type ProjectCapabilities = {+ mcp?: { config: typeof PROJECT_MCP_REL };+ functions?:+ | { manifest: typeof PROJECT_FUNCTIONS_REL; valid: true; version: 1; count: number; tools: PublicProjectFunction[] }+ | { manifest: typeof PROJECT_FUNCTIONS_REL; valid: false; error: string };+};+export type ProjectFunctionsRead = { found: false } | { found: true; functions?: ProjectFunction[]; error?: string };++const plainObject = (value: unknown): value is Record<string, unknown> =>+ Boolean(value && typeof value === "object" && !Array.isArray(value));++async function projectMsoDir(projectPath: string): Promise<string | null> {+ const candidate = path.join(projectPath, ".mso");+ const stat = await fs.lstat(candidate).catch(() => null);+ if (!stat?.isDirectory() || stat.isSymbolicLink()) return null;+ const real = await fs.realpath(candidate).catch(() => null);+ return real && isUnderRoot(real, projectPath) && real === path.resolve(candidate) ? real : null;+}++function parseInputSchema(value: unknown, functionName: string): ProjectFunction["inputSchema"] {+ if (!plainObject(value) || value.type !== "object" || !plainObject(value.properties)) {+ throw new Error(`${functionName}: inputSchema must be an object JSON Schema`);+ }+ const required = value.required;+ if (required !== undefined && (!Array.isArray(required) || !required.every((item) => typeof item === "string"))) {+ throw new Error(`${functionName}: inputSchema.required must be a string array`);+ }+ if (value.additionalProperties !== undefined && typeof value.additionalProperties !== "boolean") {+ throw new Error(`${functionName}: inputSchema.additionalProperties must be boolean`);+ }+ return {+ type: "object",+ properties: value.properties,+ ...(required ? { required: [...new Set(required)] } : {}),+ ...(typeof value.additionalProperties === "boolean" ? { additionalProperties: value.additionalProperties } : {}),+ };+}++function parseManifest(raw: string): ProjectFunction[] {+ let parsed: unknown;+ try { parsed = JSON.parse(raw); } catch { throw new Error("functions manifest is not valid JSON"); }+ if (!plainObject(parsed) || parsed.version !== 1 || !Array.isArray(parsed.functions)) {+ throw new Error("functions manifest must be {version:1, functions:[…]}");+ }+ if (parsed.functions.length > MAX_FUNCTIONS) throw new Error(`functions manifest exceeds ${MAX_FUNCTIONS} functions`);+ const seen = new Set<string>();+ return parsed.functions.map((value, index): ProjectFunction => {+ if (!plainObject(value)) throw new Error(`functions[${index}] must be an object`);+ const name = typeof value.name === "string" ? value.name.trim() : "";+ if (!/^[a-z][a-z0-9_.-]{0,63}$/.test(name)) throw new Error(`functions[${index}].name is invalid`);+ if (seen.has(name)) throw new Error(`duplicate function name: ${name}`);+ seen.add(name);+ const description = typeof value.description === "string" ? value.description.trim() : "";+ if (!description || description.length > MAX_DESCRIPTION) throw new Error(`${name}: description must be 1-${MAX_DESCRIPTION} chars`);+ const command = Array.isArray(value.command) ? value.command : [];+ if (!command.length || command.length > MAX_ARGV || typeof command[0] !== "string" || command[0].length === 0 ||+ !command.every((arg) => typeof arg === "string" && arg.length <= MAX_ARG && !arg.includes("\0"))) {+ throw new Error(`${name}: command must have a non-empty executable plus at most ${MAX_ARGV - 1} fixed argv strings (max ${MAX_ARG} chars each)`);+ }+ const timeoutMs = value.timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : Number(value.timeoutMs);+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > DEFAULT_TIMEOUT_MS) {+ throw new Error(`${name}: timeoutMs must be 1000-${DEFAULT_TIMEOUT_MS}`);+ }+ return { name, description, inputSchema: parseInputSchema(value.inputSchema, name), command: [...command], timeoutMs };+ });+}++export async function readProjectFunctionsManifest(projectPath: string): Promise<ProjectFunctionsRead> {+ const mso = await projectMsoDir(projectPath);+ if (!mso) return { found: false };+ const file = path.join(mso, "functions.json");+ const stat = await fs.lstat(file).catch(() => null);+ if (!stat) return { found: false };+ if (!stat.isFile() || stat.isSymbolicLink()) return { found: true, error: "functions manifest must be a regular non-symlink file" };+ const raw = await readBoundedRegularFile(file, BOUNDED_READ.projectFunctions);+ if (raw === null) return { found: true, error: `functions manifest is unreadable or exceeds ${BOUNDED_READ.projectFunctions} bytes` };+ try { return { found: true, functions: parseManifest(raw) }; }+ catch (error) { return { found: true, error: error instanceof Error ? error.message : "invalid functions manifest" }; }+}++async function hasMcpConfig(projectPath: string): Promise<boolean> {+ const file = path.join(projectPath, PROJECT_MCP_REL);+ const stat = await fs.lstat(file).catch(() => null);+ if (!stat?.isFile() || stat.isSymbolicLink()) return false;+ const raw = await readBoundedRegularFile(file, BOUNDED_READ.projectMcpConfig);+ if (raw === null) return false;+ try { return plainObject(JSON.parse(raw)); } catch { return false; }+}++export async function projectCapabilities(projectPath: string): Promise<ProjectCapabilities | undefined> {+ const [mcp, fn] = await Promise.all([hasMcpConfig(projectPath), readProjectFunctionsManifest(projectPath)]);+ const capabilities: ProjectCapabilities = {};+ if (mcp) capabilities.mcp = { config: PROJECT_MCP_REL };+ if (fn.found) {+ capabilities.functions = fn.functions+ ? { manifest: PROJECT_FUNCTIONS_REL, valid: true, version: 1, count: fn.functions.length,+ tools: fn.functions.map(({ command: _command, ...tool }) => tool) }+ : { manifest: PROJECT_FUNCTIONS_REL, valid: false, error: fn.error ?? "invalid functions manifest" };+ }+ return capabilities.mcp || capabilities.functions ? capabilities : undefined;+}diff --git a/lib/host/project-function-runner.ts b/lib/host/project-function-runner.tsnew file mode 100644index 00000000..d31ce569--- /dev/null+++ b/lib/host/project-function-runner.ts@@ -0,0 +1,95 @@+// SERVER-ONLY. Exec-scope runner for ONE function from a project's opt-in+// .mso/functions.json. Manifest argv is fixed project data; caller JSON travels+// only on stdin. No shell, no interpolation, credential-scrubbed environment.+import { spawn, type ChildProcessWithoutNullStreams } from "child_process";+import { childEnv } from "./child-env";+import { PROJECT_FUNCTIONS_REL, readProjectFunctionsManifest, type ProjectFunction } from "./project-function-manifest";++const MAX_INPUT_BYTES = 128 * 1024;+const MAX_OUTPUT_BYTES = 1024 * 1024;+const plainObject = (value: unknown): value is Record<string, unknown> =>+ Boolean(value && typeof value === "object" && !Array.isArray(value));++function typeMatches(type: unknown, value: unknown): boolean {+ if (type === "string") return typeof value === "string";+ if (type === "number") return typeof value === "number" && Number.isFinite(value);+ if (type === "integer") return typeof value === "number" && Number.isInteger(value);+ if (type === "boolean") return typeof value === "boolean";+ if (type === "object") return plainObject(value);+ if (type === "array") return Array.isArray(value);+ if (type === "null") return value === null;+ return true;+}++function validateInput(definition: ProjectFunction, input: Record<string, unknown>): void {+ for (const required of definition.inputSchema.required ?? []) {+ if (!Object.prototype.hasOwnProperty.call(input, required)) throw new Error(`${definition.name}: missing required input.${required}`);+ }+ if (definition.inputSchema.additionalProperties === false) {+ const unknown = Object.keys(input).find((key) => !Object.prototype.hasOwnProperty.call(definition.inputSchema.properties, key));+ if (unknown) throw new Error(`${definition.name}: unknown input.${unknown}`);+ }+ for (const [key, value] of Object.entries(input)) {+ const property = definition.inputSchema.properties[key];+ if (!plainObject(property)) continue;+ if (!typeMatches(property.type, value)) throw new Error(`${definition.name}: input.${key} has wrong type`);+ if (Array.isArray(property.enum) && !property.enum.some((candidate) => JSON.stringify(candidate) === JSON.stringify(value))) {+ throw new Error(`${definition.name}: input.${key} is not an allowed enum value`);+ }+ }+}++export async function runProjectFunction(+ projectPath: string,+ name: string,+ input: unknown,+): Promise<{ code: number; stdout: string; stderr: string }> {+ const manifest = await readProjectFunctionsManifest(projectPath);+ if (!manifest.found) throw new Error(`project has no ${PROJECT_FUNCTIONS_REL}`);+ if (!manifest.functions) throw new Error(manifest.error ?? "invalid functions manifest");+ const definition = manifest.functions.find((candidate) => candidate.name === name);+ if (!definition) throw new Error(`unknown project function "${name}"`);+ if (!plainObject(input)) throw new Error("input must be a JSON object");+ validateInput(definition, input);+ const payload = JSON.stringify(input);+ if (Buffer.byteLength(payload) > MAX_INPUT_BYTES) throw new Error(`project function input exceeds ${MAX_INPUT_BYTES} bytes`);++ return new Promise((resolve) => {+ const child = spawn(definition.command[0], definition.command.slice(1), {+ cwd: projectPath,+ env: { ...childEnv(), MSO_PROJECT_FUNCTION: definition.name } as unknown as NodeJS.ProcessEnv,+ shell: false,+ stdio: ["pipe", "pipe", "pipe"],+ }) as ChildProcessWithoutNullStreams;+ let stdout = "", stderr = "", stdoutBytes = 0, stderrBytes = 0;+ let finished = false, overflow = false, timedOut = false;+ const append = (current: string, bytes: number, chunk: Buffer): [string, number] => {+ const slice = chunk.subarray(0, Math.max(0, MAX_OUTPUT_BYTES - bytes));+ return [current + slice.toString("utf8"), bytes + slice.byteLength];+ };+ child.stdout.on("data", (chunk: Buffer) => {+ if (stdoutBytes + chunk.byteLength > MAX_OUTPUT_BYTES) overflow = true;+ [stdout, stdoutBytes] = append(stdout, stdoutBytes, chunk);+ if (overflow) child.kill("SIGTERM");+ });+ child.stderr.on("data", (chunk: Buffer) => {+ if (stderrBytes + chunk.byteLength > MAX_OUTPUT_BYTES) overflow = true;+ [stderr, stderrBytes] = append(stderr, stderrBytes, chunk);+ if (overflow) child.kill("SIGTERM");+ });+ const timer = setTimeout(() => { if (!finished) { timedOut = true; child.kill("SIGTERM"); } }, definition.timeoutMs);+ child.on("error", (error: Error) => {+ if (finished) return;+ finished = true; clearTimeout(timer);+ resolve({ code: 1, stdout, stderr: `${stderr}${stderr ? "\n" : ""}${error.message}` });+ });+ child.on("close", (code: number | null, signal: NodeJS.Signals | null) => {+ if (finished) return;+ finished = true; clearTimeout(timer);+ const note = overflow ? "output exceeded limit" : timedOut ? `timed out after ${definition.timeoutMs}ms` : signal ? `terminated by ${signal}` : "";+ resolve({ code: overflow || timedOut ? 1 : (code ?? 1), stdout,+ stderr: `${stderr}${note ? `${stderr ? "\n" : ""}${note}` : ""}` });+ });+ child.stdin.end(payload);+ });+}diff --git a/lib/host/project-list.ts b/lib/host/project-list.tsindex 4445bed4..13bd46c1 100644--- a/lib/host/project-list.ts+++ b/lib/host/project-list.ts@@ -2,6 +2,7 @@// the walk stays about containment and budgets, and this stays about presentation.import path from "path";import { boundedGitMeta, packageMeta } from "./project-meta";+import { projectCapabilities } from "./project-capabilities";import { PROJECT_LIMITS, type ProjectRow, type ScanReport } from "./project-containers";import { decodeCursor } from "./project-cursor";import { listProjectDirs } from "./project-roots";@@ -30,7 +31,7 @@ export async function listProjects(const offset = Math.max(Math.round(options.offset ?? 0), 0);const page = matched.slice(offset, offset + limit);const projects = await Promise.all(page.map(async ({ container, dir }) => {- const [pkg, git] = await Promise.all([packageMeta(dir), boundedGitMeta(dir)]);+ const [pkg, git, capabilities] = await Promise.all([packageMeta(dir), boundedGitMeta(dir), projectCapabilities(dir)]);const name = path.basename(dir);return {id: `${container.id}/${name}`,@@ -42,6 +43,7 @@ export async function listProjects(...(pkg.name ? { packageName: pkg.name } : {}),...(pkg.version ? { packageVersion: pkg.version } : {}),...(git.available ? { git: { branch: git.branch, head: git.head?.sha?.slice(0, 12) } } : {}),+ ...(capabilities ? { capabilities } : {}),};}));const hasMore = offset + page.length < matched.length;diff --git a/lib/host/projects.ts b/lib/host/projects.tsindex 3ae9e1e6..a51dbcb6 100644--- a/lib/host/projects.ts+++ b/lib/host/projects.ts@@ -2,6 +2,7 @@ import { promises as fs } from "fs";import path from "path";import { normalizeProjectKey, projectAliasesFor, projectAliasTarget } from "./project-aliases";import { boundedGitMeta, fullGitMeta, packageMeta } from "./project-meta";+import { projectCapabilities } from "./project-capabilities";import { homeDir, isUnderRoot } from "./paths";import { validateProjectChild, validateProjectDescendant, validateRootHint } from "./project-candidate";import { configuredRootPaths, containerById, containerFor, listProjectDirsIn, projectContainers, type ProjectContainer } from "./project-roots";@@ -142,8 +143,10 @@ export async function resolveProjectHint(hint: string, rootHint?: string): Promi}export async function inspectProject(project: ProjectResolution, options: { includeGitStatus?: boolean } = {}) {- return {- git: options.includeGitStatus ? await fullGitMeta(project.path) : await boundedGitMeta(project.path),- package: await packageMeta(project.path),- };+ const [git, pkg, capabilities] = await Promise.all([+ options.includeGitStatus ? fullGitMeta(project.path) : boundedGitMeta(project.path),+ packageMeta(project.path),+ projectCapabilities(project.path),+ ]);+ return { git, package: pkg, ...(capabilities ? { capabilities } : {}) };}diff --git a/lib/managed-apps/project-ingress-proxy.test.ts b/lib/managed-apps/project-ingress-proxy.test.tsnew file mode 100644index 00000000..cc521d46--- /dev/null+++ b/lib/managed-apps/project-ingress-proxy.test.ts@@ -0,0 +1,54 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";++const TEMPLATE = "{id}.mso.rahmanef.com";+const ROUTES = JSON.stringify([{+ app: "hermes", method: "POST", path: "/webhooks/project-example",+ target: "http://127.0.0.1:8644/webhooks/project-example", auth: "hmac-v2-json",+}]);++async function loadProxy(ingress = "") {+ vi.resetModules();+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", TEMPLATE);+ vi.stubEnv("OS_PROJECT_INGRESS_ROUTES", ingress);+ return (await import("../../proxy")).proxy;+}++function req(path: string, signature = "a".repeat(64)) {+ return new NextRequest(`https://hermes.mso.rahmanef.com${path}`, {+ method: "POST",+ headers: {+ host: "hermes.mso.rahmanef.com",+ "sec-fetch-site": "cross-site",+ "content-type": "application/json",+ "x-webhook-timestamp": String(Math.floor(Date.now() / 1000)),+ "x-webhook-signature-v2": signature,+ },+ body: "{}",+ });+}+const rewriteOf = (res: Response) => res.headers.get("x-middleware-rewrite");+afterEach(() => vi.unstubAllEnvs());++describe("proxy opt-in project ingress", () => {+ it("keeps stock MSO closed when no ingress config exists", async () => {+ const res = await (await loadProxy())(req("/webhooks/project-example"));+ expect(res.status).toBe(403);+ expect(rewriteOf(res)).toBeNull();+ });++ it("relays only the exact operator-declared route", async () => {+ const proxy = await loadProxy(ROUTES);+ expect(rewriteOf(await proxy(req("/webhooks/project-example"))))+ .toBe("http://127.0.0.1:8644/webhooks/project-example");+ const other = await proxy(req("/webhooks/other"));+ expect(other.status).toBe(403);+ expect(rewriteOf(other)).toBeNull();+ });++ it("rejects malformed auth-shaped traffic before loopback", async () => {+ const res = await (await loadProxy(ROUTES))(req("/webhooks/project-example", "bad"));+ expect(res.status).toBe(403);+ expect(rewriteOf(res)).toBeNull();+ });+});diff --git a/lib/managed-apps/project-ingress.test.ts b/lib/managed-apps/project-ingress.test.tsnew file mode 100644index 00000000..e11296cb--- /dev/null+++ b/lib/managed-apps/project-ingress.test.ts@@ -0,0 +1,58 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { projectIngressDecision, projectIngressRoutes } from "./project-ingress";++const route = JSON.stringify([{+ app: "hermes",+ method: "POST",+ path: "/webhooks/project-example",+ target: "http://127.0.0.1:8644/webhooks/project-example",+ auth: "hmac-v2-json",+ maxBodyBytes: 262144,+}]);++function request(path: string, headers: Record<string, string> = {}) {+ return new Request(`https://hermes.mso.example${path}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-webhook-timestamp": String(Math.floor(Date.now() / 1000)),+ "x-webhook-signature-v2": "a".repeat(64),+ ...headers,+ },+ body: "{}",+ });+}++afterEach(() => vi.unstubAllEnvs());++describe("opt-in project ingress", () => {+ it("does nothing by default", () => {+ vi.stubEnv("OS_PROJECT_INGRESS_ROUTES", "");+ expect(projectIngressRoutes()).toEqual([]);+ expect(projectIngressDecision(request("/webhooks/project-example"), "hermes", "/webhooks/project-example")).toEqual({ matched: false });+ });++ it("matches only an explicitly configured exact app/method/path", () => {+ const decision = projectIngressDecision(request("/webhooks/project-example"), "hermes", "/webhooks/project-example", route);+ expect(decision).toEqual({ matched: true, target: "http://127.0.0.1:8644/webhooks/project-example" });+ expect(projectIngressDecision(request("/webhooks/other"), "hermes", "/webhooks/other", route)).toEqual({ matched: false });+ expect(projectIngressDecision(request("/webhooks/project-example"), "openclaw", "/webhooks/project-example", route)).toEqual({ matched: false });+ });++ it("rejects stale/malformed auth-shaped traffic before loopback", () => {+ expect(projectIngressDecision(request("/webhooks/project-example", { "x-webhook-signature-v2": "bad" }), "hermes", "/webhooks/project-example", route)).toEqual({ matched: true });+ expect(projectIngressDecision(request("/webhooks/project-example", { "x-webhook-timestamp": String(Math.floor(Date.now() / 1000) - 301) }), "hermes", "/webhooks/project-example", route)).toEqual({ matched: true });+ });++ it("fails closed on off-box, wildcard, duplicate or malformed config", () => {+ for (const raw of [+ JSON.stringify([{ app: "hermes", method: "POST", path: "/x", target: "https://evil.example/x", auth: "hmac-v2-json" }]),+ JSON.stringify([{ app: "hermes", method: "POST", path: "/webhooks/*", target: "http://127.0.0.1:8644/x", auth: "hmac-v2-json" }]),+ JSON.stringify([+ { app: "hermes", method: "POST", path: "/x", target: "http://127.0.0.1:8644/x", auth: "hmac-v2-json" },+ { app: "hermes", method: "POST", path: "/x", target: "http://127.0.0.1:8645/x", auth: "hmac-v2-json" },+ ]),+ "not-json",+ ]) expect(projectIngressRoutes(raw)).toEqual([]);+ });+});diff --git a/lib/managed-apps/project-ingress.ts b/lib/managed-apps/project-ingress.tsnew file mode 100644index 00000000..449d4b7e--- /dev/null+++ b/lib/managed-apps/project-ingress.ts@@ -0,0 +1,86 @@+// Edge-safe, opt-in machine ingress for project integrations. Default = empty,+// so stock MSO exposes no public managed-app POST lane. A deployment may declare+// exact app/method/path -> LOOPBACK routes with OS_PROJECT_INGRESS_ROUTES.+//+// MSO only performs a cheap HMAC-V2-shaped prefilter. The loopback service remains+// the cryptographic authority because MSO intentionally does not receive its secret.+export type ProjectIngressRoute = {+ app: string;+ method: "POST";+ path: string;+ target: string;+ auth: "hmac-v2-json";+ maxBodyBytes: number;+};++const MAX_ROUTES = 8;+const DEFAULT_BODY_LIMIT = 256 * 1024;+const MAX_BODY_LIMIT = 1024 * 1024;+const APP_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;+const PATH_RE = /^\/[a-zA-Z0-9._~!$&'()+,;=:@\/-]{1,180}$/;+const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1"]);++function validTarget(raw: unknown): string | null {+ if (typeof raw !== "string") return null;+ try {+ const url = new URL(raw);+ if (url.protocol !== "http:" || !LOOPBACK.has(url.hostname) || !url.port || url.username || url.password || url.search || url.hash) return null;+ const port = Number(url.port);+ if (!Number.isInteger(port) || port < 1 || port > 65535 || !PATH_RE.test(url.pathname) || url.pathname.includes("..")) return null;+ return url.toString();+ } catch { return null; }+}++export function projectIngressRoutes(raw = process.env.OS_PROJECT_INGRESS_ROUTES ?? ""): ProjectIngressRoute[] {+ if (!raw.trim()) return [];+ let parsed: unknown;+ try { parsed = JSON.parse(raw); } catch { return []; }+ if (!Array.isArray(parsed) || parsed.length > MAX_ROUTES) return [];+ const out: ProjectIngressRoute[] = [];+ const keys = new Set<string>();+ for (const row of parsed) {+ if (!row || typeof row !== "object" || Array.isArray(row)) return [];+ const r = row as Record<string, unknown>;+ const app = typeof r.app === "string" ? r.app : "";+ const method = r.method === "POST" ? "POST" : null;+ const requestPath = typeof r.path === "string" ? r.path : "";+ const target = validTarget(r.target);+ const auth = r.auth === "hmac-v2-json" ? "hmac-v2-json" : null;+ const maxBodyBytes = r.maxBodyBytes === undefined ? DEFAULT_BODY_LIMIT : Number(r.maxBodyBytes);+ if (!APP_RE.test(app) || !method || !PATH_RE.test(requestPath) || requestPath.includes("..") || !target || !auth) return [];+ if (!Number.isInteger(maxBodyBytes) || maxBodyBytes < 1024 || maxBodyBytes > MAX_BODY_LIMIT) return [];+ const key = `${app}:${method}:${requestPath}`;+ if (keys.has(key)) return [];+ keys.add(key);+ out.push({ app, method, path: requestPath, target, auth, maxBodyBytes });+ }+ return out;+}++function plausibleHmacV2Json(request: Request, route: ProjectIngressRoute): boolean {+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";+ if (!contentType.startsWith("application/json")) return false;+ const seconds = Number(request.headers.get("x-webhook-timestamp") ?? "");+ if (!Number.isInteger(seconds) || Math.abs(Math.floor(Date.now() / 1000) - seconds) > 300) return false;+ if (!/^[0-9a-f]{64}$/i.test(request.headers.get("x-webhook-signature-v2") ?? "")) return false;+ const lengthHeader = request.headers.get("content-length");+ if (lengthHeader) {+ const length = Number(lengthHeader);+ if (!Number.isFinite(length) || length < 0 || length > route.maxBodyBytes) return false;+ }+ return true;+}++export function projectIngressDecision(+ request: Request,+ managedApp: string | null,+ pathname: string,+ raw = process.env.OS_PROJECT_INGRESS_ROUTES ?? "",+): { matched: false } | { matched: true; target?: string } {+ if (!managedApp) return { matched: false };+ const route = projectIngressRoutes(raw).find((candidate) =>+ candidate.app === managedApp && candidate.method === request.method && candidate.path === pathname,+ );+ if (!route) return { matched: false };+ return plausibleHmacV2Json(request, route) ? { matched: true, target: route.target } : { matched: true };+}diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.tsindex 06ff4c16..a6cbd2d5 100644--- a/lib/mcp/dispatch.test.ts+++ b/lib/mcp/dispatch.test.ts@@ -44,7 +44,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.5.3");+ expect(result.serverInfo.version).toBe("1.6.0");expect(result._meta.toolset.toolCount).toBe(TOOLS.length);expect(result._meta.toolset.hash).toMatch(/^[a-f0-9]{16}$/);});diff --git a/lib/mcp/global-tools.test.ts b/lib/mcp/global-tools.test.tsindex d5ed6fd2..c180d2ea 100644--- a/lib/mcp/global-tools.test.ts+++ b/lib/mcp/global-tools.test.ts@@ -98,6 +98,13 @@ describe("no per-project or per-agent tool filter exists", () => {expect(tool.inputSchema.required ?? [], tool.name).not.toContain("workflow_id");}});++ it("keeps project function execution in exec while discovery stays read", async () => {+ expect(await names("read")).toContain("project_capabilities");+ expect(await names("read")).not.toContain("project_function_call");+ expect(await names("write")).not.toContain("project_function_call");+ expect(await names("exec")).toContain("project_function_call");+ });});describe("image generation is gone from every surface", () => {@@ -137,6 +144,6 @@ describe("file import survives the image-generation removal", () => {describe("global discovery is part of the public catalog", () => {it("ships projects_list, skills_list and skills_read at read scope", async () => {const read = await names("read");- for (const name of ["projects_list", "skills_list", "skills_read", "skills_search"]) expect(read).toContain(name);+ for (const name of ["projects_list", "project_capabilities", "skills_list", "skills_read", "skills_search"]) expect(read).toContain(name);});});diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex 6edc3294..920fb9ce 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -35,6 +35,8 @@ const ALFA_ONLY: Record<string, string> = {const MCP_ONLY: Record<string, string> = {"screen.capture": "external MCP clients need visual proof of the rendered OS; in-shell Alfa already runs inside that browser UI","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","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.cancel": "same actor-scoped boundary; external runs need explicit recovery from an interrupted task",@@ -102,6 +104,8 @@ describe("MCP rate limits mirror the routes", () => {// Global discovery reads: no HTTP route mirrors them, and each one walks// every configured container, so they get their own small buckets."projects.list": 30,+ "projects.capabilities": 60,+ "projects.function": 60,"skills.list": 30,"skills.read": 60,};diff --git a/lib/mcp/project-functions.test.ts b/lib/mcp/project-functions.test.tsnew file mode 100644index 00000000..4ff3110a--- /dev/null+++ b/lib/mcp/project-functions.test.ts@@ -0,0 +1,44 @@+import { afterAll, describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+import { promises as fs } from "fs";+import os from "os";+import path from "path";++const base = await fs.mkdtemp(path.join(os.tmpdir(), "mso-mcp-project-fn-"));+const project = path.join(base, "widget");+await fs.mkdir(path.join(project, ".mso"), { recursive: true });+const code = "let s='';process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>process.stdout.write(s))";+await fs.writeFile(path.join(project, ".mso/functions.json"), JSON.stringify({+ version: 1,+ functions: [{+ name: "echo_json", description: "Echo input JSON.",+ inputSchema: { type: "object", properties: { value: { type: "string" } }, required: ["value"] },+ command: [process.execPath, "-e", code],+ }],+}));+const previous = process.env.OS_FS_READ_ROOTS;+process.env.OS_FS_READ_ROOTS = base;+const { TOOLS_BY_NAME } = await import("./tools");++afterAll(async () => {+ if (previous === undefined) delete process.env.OS_FS_READ_ROOTS;+ else process.env.OS_FS_READ_ROOTS = previous;+ await fs.rm(base, { recursive: true, force: true });+});++describe("project function MCP bridge", () => {+ it("is one stable exec-scope tool, not a dynamic tool per project function", () => {+ const tool = TOOLS_BY_NAME.get("project_function_call");+ expect(tool?.scope).toBe("exec");+ expect(TOOLS_BY_NAME.has("echo_json")).toBe(false);+ });++ it("runs an opted-in project function with exact JSON stdin", async () => {+ const result = await TOOLS_BY_NAME.get("project_function_call")!.run({+ project,+ name: "echo_json",+ input: { value: "hello; $(not-a-shell)" },+ }, { scope: "exec" });+ expect(result).toEqual({ code: 0, stdout: JSON.stringify({ value: "hello; $(not-a-shell)" }), stderr: "" });+ });+});diff --git a/lib/mcp/tools-discovery.test.ts b/lib/mcp/tools-discovery.test.tsindex 1406182b..26e210fc 100644--- a/lib/mcp/tools-discovery.test.ts+++ b/lib/mcp/tools-discovery.test.ts@@ -25,6 +25,16 @@ async function skill(dir: string, name: string, description: string, body = "steawait skill(path.join(widgetA, ".claude/skills"), "widget-deploy", "Ship the widget service from root A.");await fs.writeFile(path.join(widgetA, "package.json"), JSON.stringify({ name: "widget", version: "0.1.0" }));+await fs.writeFile(path.join(widgetA, ".mcp.json"), JSON.stringify({ mcpServers: { local: { command: "ignored-secret-free-fixture" } } }));+await fs.mkdir(path.join(widgetA, ".mso"), { recursive: true });+await fs.writeFile(path.join(widgetA, ".mso/functions.json"), JSON.stringify({+ version: 1,+ functions: [{+ name: "widget_status", description: "Read widget status.",+ inputSchema: { type: "object", properties: {}, additionalProperties: false },+ command: [process.execPath, "-e", "process.stdout.write('ok')"],+ }],+}));await skill(path.join(widgetB, ".claude/skills"), "widget-deploy", "Ship the widget service from root B.");// A project whose skills ROOT escapes the project via symlink: the SKILL.md is a real// regular file, so it is discoverable — but containment fails, so it is untrusted and@@ -76,12 +86,14 @@ describe("projects_list", () => {it("enumerates every project across BOTH containers, keeping same-named ones distinct", async () => {const result = await run("projects_list") as {- total: number; scan: Scan; projects: Array<{ id: string; name: string; rootId: string; packageName?: string }>;+ total: number; scan: Scan; projects: Array<{ id: string; name: string; rootId: string; packageName?: string; capabilities?: Record<string, unknown> }>;};expect(result.projects.map((p) => p.name)).toEqual(["gadget", "widget", "widget"]);expect(new Set(result.projects.map((p) => p.id)).size).toBe(3);expect(result.total).toBe(3);- expect(result.projects.find((p) => p.packageName === "widget")).toBeDefined();+ const optedIn = result.projects.find((p) => p.packageName === "widget");+ expect(optedIn).toBeDefined();+ expect(optedIn?.capabilities).toMatchObject({ mcp: { config: ".mcp.json" }, functions: { valid: true, count: 1 } });});it("reports a truthful scan report on a complete enumeration", async () => {@@ -97,6 +109,17 @@ 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 }> } };+ };+ expect(result.capabilities.mcp).toEqual({ config: ".mcp.json" });+ expect(result.capabilities.functions).toMatchObject({ valid: true, tools: [{ name: "widget_status" }] });+ expect(JSON.stringify(result)).not.toContain(process.execPath);+ });+});+describe("skills_list spans global and project roots", () => {it("returns official repo skills AND per-project skills in one catalog", async () => {const { skills, scan } = await run("skills_list", { limit: 200 }) as { skills: SkillRow[]; scan: Scan };diff --git a/lib/mcp/tools-discovery.ts b/lib/mcp/tools-discovery.tsindex 0c486428..71d065b7 100644--- a/lib/mcp/tools-discovery.ts+++ b/lib/mcp/tools-discovery.ts@@ -1,4 +1,4 @@-import { listProjects, PROJECT_LIMITS } from "@/lib/host";+import { listProjects, projectCapabilities, 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";@@ -21,11 +21,30 @@ const page = (a: Record<string, unknown>, max: number, fallback: number) => ({});export const DISCOVERY_TOOLS: McpTool[] = [+ {+ name: "project_capabilities",+ description:+ "Inspect ONE validated project for opt-in automation capabilities without exposing secrets. " ++ "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.",+ scope: "read",+ annotations: READ_ONLY,+ limit: { key: "projects.capabilities", max: 60, windowMs: 60_000 },+ inputSchema: S({+ project: { type: "string", description: "Exact project id from projects_list, absolute path, name or alias." },+ }, ["project"]),+ 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)) ?? {} };+ },+ },{name: "projects_list",description:"Enumerate the owner's projects across EVERY configured project container (each OS_FS_READ_ROOTS entry and its projects/ subdirectory), not just ~/projects. " +- "Returns a globally unique id (<rootId>/<name>, so two roots may hold a project of the same name), absolute path, its container root, package name/version and bounded Git branch/head read straight off .git with no shell. " ++ "Returns a globally unique id (<rootId>/<name>, so two roots may hold a project of the same name), absolute path, its container root, package name/version, bounded Git branch/head, and opt-in MCP/function capability summary. " +"USE THIS FIRST when the user names a project you have not located — it is one call, needs no shell scope, and its id or path is the input to workflow_start. " +"Hidden directories, symlinks, credential paths and directories not owned by the MSO user are excluded. " +"ALWAYS check `scan.truncated`: when true the listing is incomplete and `scan.truncationReasons` says which cap was hit — do not report that a project is absent from a truncated scan. " +diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.tsindex 427c93d9..c9d06287 100644--- a/lib/mcp/tools.ts+++ b/lib/mcp/tools.ts@@ -1,4 +1,4 @@-import { writeFileGuarded, makeDir, remove, move, copy, runCommand } from "@/lib/host";+import { writeFileGuarded, makeDir, remove, move, copy, runCommand, resolveProjectHint, runProjectFunction } from "@/lib/host";import { type McpTool, str, opt, S, PATH_P } from "./tool-kit";import { importOpenAiProvidedFile } from "./openai-file-upload";import { READ_TOOLS } from "./tools-read";@@ -106,6 +106,34 @@ const MUTATE_TOOLS: McpTool[] = [run: async (a) => { await remove(str(a, "path")); return { ok: true, path: a.path }; },},+ {+ name: "project_function_call",+ limit: { key: "projects.function", max: 60, windowMs: 60_000 },+ audit: {+ action: "exec.run" as const,+ targetArg: "project",+ outcome: (r) => {+ const { code } = r as { code: number };+ return { ok: code === 0, action: "exec.run", detail: `project function exit ${code}` };+ },+ },+ description:+ "Execute ONE function explicitly declared by a validated project's .mso/functions.json. " ++ "This is project code execution and therefore requires exec scope. The manifest supplies fixed argv; model/user input is passed only as JSON on stdin and is NEVER interpolated into a shell command. " ++ "Call project_capabilities first for function names and schemas. Projects without an opt-in manifest expose nothing.",+ scope: "exec",+ annotations: { destructiveHint: true, openWorldHint: true },+ inputSchema: S({+ project: { type: "string", description: "Exact project id from projects_list, absolute path, name or alias." },+ name: { type: "string", description: "Function name returned by project_capabilities." },+ input: { type: "object", description: "JSON object passed to the project function on stdin.", additionalProperties: true },+ }, ["project", "name", "input"]),+ run: async (a) => {+ const project = await resolveProjectHint(str(a, "project"));+ if (!project) throw new Error(`project not found: ${String(a.project)}`);+ return runProjectFunction(project.path, str(a, "name"), a.input);+ },+ },{name: "exec_run",limit: { key: "exec", max: 60, windowMs: 60_000 },diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex 3d20d576..a607eaab 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -2,9 +2,9 @@ import { createHash } from "crypto";import type { Scope } from "./scope";import type { McpTool } from "./tool-kit";-export const MCP_SERVER_VERSION = "1.5.3";-export const MCP_TOOLSET_VERSION = "2026.08.20.6";-export const MCP_TOOLSET_CHANGED_AT = "2026-08-20T16:40:00Z";+export const MCP_SERVER_VERSION = "1.6.0";+export const MCP_TOOLSET_VERSION = "2026.08.21.1";+export const MCP_TOOLSET_CHANGED_AT = "2026-08-21T13:45:00Z";export type McpToolsetInfo = {serverVersion: string;diff --git a/lib/skills/memory.ts b/lib/skills/memory.tsindex 1558d099..77c14e8e 100644--- a/lib/skills/memory.ts+++ b/lib/skills/memory.ts@@ -207,6 +207,8 @@ const SAFE_TOOL_ARGS: Record<string, readonly string[]> = {fs_usage: ["path"],apps_logs: ["id"],projects_list: ["query", "limit", "offset"],+ project_capabilities: ["project"],+ project_function_call: ["project", "name"],skills_list: ["project", "trust", "limit", "offset"],skills_read: ["name"],screen_capture: ["shell", "width", "height"],diff --git a/proxy.ts b/proxy.tsindex dd4c3693..84db4e76 100644--- a/proxy.ts+++ b/proxy.ts@@ -24,6 +24,7 @@ import {} from "@/lib/managed-apps/origin";import { proxyPrefix, upstreamSocketHeaders } from "@/lib/managed-apps/proxy-headers";import { getManagedAppDefinition } from "@/lib/managed-apps/catalog";+import { projectIngressDecision } from "@/lib/managed-apps/project-ingress";import { verifySession } from "@/lib/auth/session";import { isApproved } from "@/lib/auth/device-store";import { IS_DEMO } from "@/lib/demo";@@ -150,6 +151,17 @@ export async function proxy(request: NextRequest) {const host = request.headers.get("host") ?? request.nextUrl.host;const managedApp = managedAppIdForHost(host);+ // Optional project integrations may expose ONE exact machine-to-machine POST+ // lane on a managed-app host. Stock MSO has no routes because+ // OS_PROJECT_INGRESS_ROUTES defaults to empty. The route config is fixed by the+ // operator, targets loopback only, and the upstream still verifies the real+ // HMAC secret; this edge check only rejects obvious public garbage before CSRF.+ const ingress = projectIngressDecision(request, managedApp, pathname);+ if (ingress.matched) {+ if (!ingress.target) return blocked();+ return NextResponse.rewrite(new URL(ingress.target));+ }+// A host inside the app namespace that is NOT an app (a new `X.mso.rahmanef.com`// record, or a `*.os` wildcard) must not serve the cockpit: the session cookie is// widened to that name, so such a host would be same-origin with a fully