Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(mcp): add project automation flows and dynamic MCP sessions

Rahmana75b76de2c46
diff --git a/app/api/v1/flows/route.ts b/app/api/v1/flows/route.ts
new file mode 100644
index 00000000..1ddad603
--- /dev/null
+++ b/app/api/v1/flows/route.ts
@@ -0,0 +1,38 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { createAgentSession } from "@/lib/agent/session-store";
+import { readSetupJson } from "@/lib/infra/setup-http";
+import { flowCatalog } from "@/lib/workflow/automation-catalog";
+import { flowStatus } from "@/lib/workflow/automation-engine";
+import { executeCapabilityCall } from "@/lib/capabilities/execute";
+import { maxScope } from "@/lib/mcp/scope";
+import { TOOLS_BY_NAME } from "@/lib/mcp/tools";
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+const headers = { "Cache-Control": "no-store, private" };
+const fail = (e: unknown) => NextResponse.json({ error: e instanceof Error ? e.message.slice(0, 300) : "flow failed" }, { status: 400, headers });
+export async function GET(req: NextRequest) {
+ const auth = await getSessionContext();
+ if (auth?.role !== "owner") return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ try {
+ const q = req.nextUrl.searchParams;
+ if (q.has("run_id")) return NextResponse.json(await flowStatus(q.get("run_id")!, { principal: "cli:" + auth.session.device_id, scope: maxScope() }, Number(q.get("wait_ms")) || 0), { headers });
+ const { project, flows, revision } = await flowCatalog(q.get("project") ?? "", q.get("flow") || undefined);
+ return NextResponse.json({ project: project.id, flows, revision }, { headers });
+ } catch (e) { return fail(e); }
+}
+export async function POST(req: NextRequest) {
+ const auth = await getSessionContext();
+ if (auth?.role !== "owner") return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ try {
+ const { action = "run", ...args } = await readSetupJson(req);
+ const name = action === "run" ? "flow_run" : action === "upsert" || action === "delete" ? "flow_manage" : "";
+ if (!name) throw new Error("unknown flow action");
+ const principal = "cli:" + auth.session.device_id;
+ const session = await createAgentSession(principal, "cli", { title: "Automation: " + String(args.flow ?? ""), titleSource: "auto" });
+ const outcome = await executeCapabilityCall({ tool: TOOLS_BY_NAME.get(name)!, args: { ...args, ...(action === "run" ? {} : { action }) },
+ actor: principal, scope: maxScope(), context: { principal, sessionId: session.id } });
+ if (outcome.kind !== "success") throw new Error(outcome.message);
+ return NextResponse.json(outcome.result, { headers });
+ } catch (e) { return fail(e); }
+}
diff --git a/app/api/v1/project-mcp/route.ts b/app/api/v1/project-mcp/route.ts
new file mode 100644
index 00000000..70ebece7
--- /dev/null
+++ b/app/api/v1/project-mcp/route.ts
@@ -0,0 +1,19 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { readSetupJson } from "@/lib/infra/setup-http";
+import { executeCapabilityCall } from "@/lib/capabilities/execute";
+import { maxScope } from "@/lib/mcp/scope";
+import { PROJECT_MCP_MANAGE_TOOLS } from "@/lib/mcp/tools-project-mcp-manage";
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+export async function POST(req: NextRequest) {
+ const headers = { "Cache-Control": "no-store, private" };
+ const auth = await getSessionContext();
+ if (auth?.role !== "owner") return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
+ try {
+ const args = await readSetupJson(req), actor = "device:" + auth.session.device_id;
+ const result = await executeCapabilityCall({ tool: PROJECT_MCP_MANAGE_TOOLS[0], args, actor, scope: maxScope(), context: { principal: actor } });
+ if (result.kind !== "success") throw new Error(result.message);
+ return NextResponse.json(result.result, { headers });
+ } catch (e) { return NextResponse.json({ error: e instanceof Error ? e.message.slice(0, 300) : "MCP operation failed" }, { status: 400, headers }); }
+}
diff --git a/app/mcp/route-protocol.test.ts b/app/mcp/route-protocol.test.ts
index 4ca41caa..1e4251e5 100644
--- a/app/mcp/route-protocol.test.ts
+++ b/app/mcp/route-protocol.test.ts
@@ -28,7 +28,7 @@ vi.mock("@/lib/mcp/capability-runtime", () => ({ msoCapabilityRuntime: { list: (
vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));
vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({}) }));
vi.mock("@/lib/mcp/client-profile", () => ({ detectMcpToolProfile: () => "full" }));
-vi.mock("@/lib/mcp/protocol", () => ({ supportedMcpProtocol: (v: string) => ["2025-06-18", "2025-03-26", "2024-11-05"].includes(v) }));
+
vi.mock("@/lib/mcp/tool-contract", () => ({ visibleToolsForProfile: () => [] }));
vi.mock("@/lib/agent/session-store", () => ({ findOrCreateAgentSessionForConversation: vi.fn() }));
@@ -65,7 +65,7 @@ describe("/mcp protocol boundary", () => {
expect(mocks.dispatch).not.toHaveBeenCalled();
});
- it("rejects a 2026-07-28 modern probe so the client can fall back to initialize", async () => {
+ it("rejects modern metadata missing required clientCapabilities", async () => {
mocks.validateToken.mockResolvedValueOnce({ hash: "2".repeat(64), scope: "read", clientId: "client-modern-probe", label: "Modern probe" });
const { POST } = await import("./route");
const res = await POST(request(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "server/discover", params: { _meta: { "io.modelcontextprotocol/protocolVersion": "2026-07-28" } } }), { "MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "server/discover" }));
diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.ts
index 706c1750..0d87f35b 100644
--- a/app/mcp/route.test.ts
+++ b/app/mcp/route.test.ts
@@ -48,7 +48,6 @@ vi.mock("@/lib/mcp/capability-runtime", () => ({
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) => ["2025-06-18", "2025-03-26", "2024-11-05"].includes(v) }));
vi.mock("@/lib/mcp/tool-contract", () => ({ visibleToolsForProfile: () => [] }));
vi.mock("@/lib/agent/session-store", () => ({
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index cfb9a317..bfaa0bd2 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -6,7 +6,8 @@ import { rateLimited, rateLimitedUntrusted } from "@/lib/host/limits-api";
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 { validateMcpRequest, modernMcpResult } from "@/lib/mcp/modern-http";
+import { MCP_SERVER_VERSION } from "@/lib/mcp/toolset";
import { visibleToolsForProfile } from "@/lib/mcp/tool-contract";
import { mcpSessionHeaders, resolveMcpSession } from "@/lib/mcp/session-context";
import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";
@@ -74,10 +75,8 @@ 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: responseHeaders(req, { "Cache-Control": "no-store" }) });
- }
+ const wire = validateMcpRequest(req, body);
+ if (wire.error) return Response.json(wire.error, { status: 400, headers: responseHeaders(req, { "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");
@@ -85,7 +84,7 @@ export async function POST(req: Request) {
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 = responseHeaders(req, mcpSessionHeaders(resolved.responseSessionId));
+ const headers = responseHeaders(req, mcpSessionHeaders(wire.modern ? undefined : resolved.responseSessionId));
if (isNotification(body)) return new Response(null, { status: 202, headers });
void touchToken(token.hash).catch(() => {});
@@ -99,7 +98,7 @@ export async function POST(req: Request) {
capabilities: msoCapabilityRuntime,
};
const result = await dispatch(rpc, effectiveScope, actor, agentContext);
- return Response.json(result, { status: 200, headers });
+ return Response.json(wire.modern ? modernMcpResult(result, MCP_SERVER_VERSION) : result, { status: wire.modern && (result.error as { code?: number } | undefined)?.code === -32601 ? 404 : 200, headers });
}
export async function GET(req: Request) {
@@ -111,6 +110,7 @@ export async function GET(req: Request) {
if ((req.headers.get("accept") ?? "").toLowerCase().includes("text/event-stream")) {
return new Response(null, { status: 405, headers: responseHeaders(req, { Allow: "POST", "Cache-Control": "no-store" }) });
}
+ if (req.headers.get("MCP-Protocol-Version") === "2026-07-28") return new Response(null, { status: 405, headers: responseHeaders(req, { Allow: "POST", "Cache-Control": "no-store" }) });
const full = toolsetInfo(TOOLS, undefined, "full");
const chatgptTools = visibleToolsForProfile(TOOLS, "exec", "chatgpt");
return Response.json({
diff --git a/bin/mso b/bin/mso
index 11bd5d08..a6dde53b 100755
--- a/bin/mso
+++ b/bin/mso
@@ -47,6 +47,7 @@
# model [ref] Select active model from a connected provider
# onboard [-y] Guided setup: AI, apps, infrastructure, skills
# setup Alias for onboard
+# flow list|inspect|run|status|save|delete Project API/MCP automation (flow --help)
# integrations Named credential users, connections, sources, setup and execution
# provider * Infrastructure credentials: list | set | rm | doctor
# providers * Alias for provider
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index e33f8f82..a568e883 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -12,6 +12,7 @@ const run = (...args: string[]) =>
const commandOwnerFiles = [
"scripts/cli/commands-host.sh",
"scripts/cli/commands-runtime.sh",
+ "scripts/cli/flows.sh",
"scripts/cli/commands-state.sh",
"scripts/cli/config-command.sh",
"scripts/cli/commands-admin.sh",
diff --git a/claude-skills/provider-automation/SKILL.md b/claude-skills/provider-automation/SKILL.md
new file mode 100644
index 00000000..29df3cd5
--- /dev/null
+++ b/claude-skills/provider-automation/SKILL.md
@@ -0,0 +1,56 @@
+---
+name: provider-automation
+description: "Discover, define and run repeatable project API/MCP flows with explicit session, project and connection context, durable receipts and independent verification."
+metadata:
+ mso:
+ risk: high
+ policy: inspect-execute-verify
+---
+
+# /provider-automation — Provider Automation
+
+## Trigger and boundaries
+
+Use for repeated provider API operations, project MCP chains, and declared project functions. Required: exact project id/path, requested outcome, authorized connection alias, input and idempotency key. Credentials stay in the private connection store. One operation can use its existing tool directly.
+
+## Fast route
+
+1. Call `agent_session_open` once with a stable conversation key, unless this conversation already has a session. Carry returned `mso/sessionId` in request metadata.
+2. Call `flow_catalog` with the exact project. Inspect the selected flow to get its input schema, ordered steps and scope.
+3. Reuse an existing flow. For a new repeated pattern, inspect the provider operation or paged `project_mcp_tools` schema first; save a versioned definition with `flow_manage` and the catalog revision.
+4. Call `flow_run` with project, flow, nonsecret input and a unique logical operation key.
+5. Use `flow_status` with `wait_ms:25000` until terminal. Reusing the same key retrieves that run; it never starts its mutations again.
+
+## Tool routing
+
+| Need | Capability |
+|---|---|
+| Provider operation schema and connection state | integration_query |
+| Cloudflare/Hostinger DNS ensure | flow_catalog → flow_run → flow_status |
+| Add a project MCP | project_mcp_manage inspect → upsert with revision |
+| Discover all downstream tools | project_mcp_tools, following nextCursor |
+| Versioned project flow CRUD | flow_catalog / flow_manage |
+| Promote a generated asset | session_artifacts → project_asset_attach |
+| Display integration controls | mso_ui with the integrations view |
+
+## Execution flow
+
+For multi-step agent work, reuse its exact `workflow_id`; `workflow_start` already resolves skills and learned recipes. The flow runner inherits that workflow and session. Do not start duplicate workflows or bypass scope/allowlists.
+
+Definitions live in `.mso/flows.json` version 1. Steps may use `integration_execute`, `project_mcp_call`, or `project_function_call`. Values may reference `input.name`, `steps.previous.result.field`, or `project` using a whole-value `{"$ref":"..."}`. Project steps inherit the canonical project. Cross-project switching, inline credentials, arbitrary shell templates and forward references are rejected. See `docs/AUTOMATION-FLOWS.md`.
+
+## Verification contract
+
+- Expected state: the requested provider/project state, not merely a completed receipt.
+- Targeted checks: inspect the schema and connection before mutation; use a step expectation for required provider checks.
+- Runtime proof: inspect each step result and independently query the resulting state.
+- Visual proof: verify the integration canvas or project preview for visual changes.
+- Diff boundary: only the selected project manifest, connection and authorized provider resources.
+
+## Failure and rollback
+
+A failed or interrupted run stops subsequent steps. An interrupted mutation has an uncertain outcome: inspect the provider before choosing a new key. Never automatically replay, resume or roll back external writes. Existing user authorization remains valid; ask only for genuinely missing scope or input. Receipts are retained for 30 days, so keep important provider identifiers in project documentation.
+
+## Recipe memory
+
+Save reusable metadata and references only. Never store secrets, auth links or copied request bodies containing private credentials. Finish the existing workflow with verified results; failed runs must not replace successful recipes.
diff --git a/docs/AUTOMATION-FLOWS.md b/docs/AUTOMATION-FLOWS.md
new file mode 100644
index 00000000..2e549962
--- /dev/null
+++ b/docs/AUTOMATION-FLOWS.md
@@ -0,0 +1,140 @@
+# Project automation flows
+
+MSO MCP 1.13.0 adds reusable execution behind four stable tools. Project/provider-specific
+operations remain dynamic data; all existing MSO capabilities remain available.
+
+## CLI
+
+```bash
+mso flow list --project /absolute/project
+mso flow inspect cloudflare.dns.ensure --project /absolute/project
+mso flow run cloudflare.dns.ensure --project /absolute/project \
+ --input '{"user":"owner","connection":"production","name":"app.example.com","type":"CNAME","content":"origin.example.com","proxied":true}' \
+ --key dns-app-example-com-v1 --wait
+mso flow status <run-id> --wait
+mso flow save publish --project /absolute/project --revision <revision> --input @flow.json
+mso flow delete publish --project /absolute/project --revision <revision>
+```
+
+The names above are examples. Inspect the real connection with `integration_query` first.
+The built-in `cloudflare.dns.ensure` and `hostinger.dns.ensure` verify the selected account,
+then upsert the requested DNS record. Cloudflare accepts A/AAAA/CNAME/TXT; Hostinger
+currently accepts A/CNAME/TXT. Successful API acceptance does not prove DNS propagation.
+
+## Agent contract
+
+Open/reuse an agent session with `agent_session_open(conversation_key, project)`.
+Send returned `params._meta["mso/sessionId"]` or the `Mso-Session-Id` header on subsequent
+calls. Principals cannot select another principal's session. Existing ChatGPT conversation
+metadata remains supported. The logical conversation key is stable across reconnects.
+
+Discover `flow_catalog(project)`, then inspect `flow_catalog(project, flow)` for
+input schema, ordered steps, required scope and project context. Call
+`flow_run(project, flow, input, idempotency_key)`, then `flow_status(run_id, wait_ms)`.
+The CLI and MCP use the same execution kernel; child calls keep scope, tool allowlist,
+argument constraints, session, workflow, connection checks and audits.
+
+## Schema and CRUD
+
+Project definitions are stored in `.mso/flows.json`: `{"version":1,"flows":[...]}`.
+The structural [JSON Schema](schemas/mso-flows.schema.json) is paired with runtime semantic
+validation. `flow_manage` requires an exact flow id and the revision returned by
+`flow_catalog` (`new` for an absent file). Conflicts fail rather than overwriting concurrent edits.
+Built-in ids cannot be replaced. Definitions contain no credentials.
+
+Example definition for a project that already exposes a matching `assets` MCP:
+
+```json
+{
+ "id": "asset.register",
+ "description": "Register one existing project image through the assets MCP.",
+ "inputs": {
+ "path": {"type":"string","description":"Project-relative image path","required":true}
+ },
+ "steps": [{
+ "id": "register",
+ "tool": "project_mcp_call",
+ "arguments": {
+ "server": "assets",
+ "tool": "register_image",
+ "arguments": {"path":{"$ref":"input.path"}}
+ }
+ }]
+}
+```
+
+Inspect the actual downstream tool schema before adapting this example. Steps may call
+`integration_execute`, `project_mcp_call`, or `project_function_call`; existing provider
+adapters, Composio operations and declared project functions remain the extension points.
+This is not a promise that every arbitrary provider API operation is already implemented.
+
+References replace a whole JSON value: `{"$ref":"input.name"}`,
+`{"$ref":"steps.previous.result.field"}`, or `{"$ref":"project"}`.
+No string interpolation, eval, forward references or prototype properties are allowed.
+The exact result path depends on the inspected tool. Project calls inherit the canonical project.
+
+## Durability and bounded work
+
+| Rule | MSO policy |
+|---|---|
+| Manifest | 64 KiB, 32 flows |
+| Flow | 32 input fields, 1–12 ordered steps, nesting at most 12 |
+| Run input | 32 KiB, typed fields; no inline credential/header fields |
+| Concurrent runs | Four per principal |
+| Step receipt result | Bounded to 12 KiB; full result available to following steps in memory |
+| Whole run | No new step begins after ten minutes; each child retains its own timeout |
+| Status long poll | At most 25 seconds |
+| Receipt retention | 30 days, maximum 1,000 retained per principal |
+
+Reusing a key with identical project/definition/input returns its existing receipt; changed input
+is rejected. Receipts are private and checkpointed around each step. They are not an exactly-once
+guarantee from external providers. A process interruption leaves an uncertain mutation:
+inspect the provider, then deliberately choose a new key if another attempt is appropriate.
+There is no automatic external retry, background queue or automatic rollback.
+The runner currently remains in the MSO process; use existing managed jobs for standalone builds.
+
+## Add MCP, assets and canvas
+
+In Integrations, click **Add MCP**, enter the exact project, alias and HTTPS endpoint,
+then select a private MCP connection or public access. Configure private credentials through
+the existing New connection form first. The same Add MCP form works inside the integration
+canvas. It refuses alias replacement and preserves unrelated project bindings. This is
+project registration, not a universal OAuth authorization popup for every provider.
+
+Use `project_mcp_manage` for inspect/upsert/delete with revision checks, and
+`project_mcp_tools` with cursors for discovery. Tools stay namespaced by project and server.
+Use existing `fs_upload_file` for incoming assets, `session_artifacts` for agent-generated
+artifacts, and `project_asset_attach` to copy an owned artifact into a durable project path.
+Identical content is reusable; differing existing content and escaping/symlink paths are refused.
+Existing `fs_*` tools provide subsequent project file CRUD.
+
+## Official constraints versus local budgets
+
+Reviewed 2026-09-12. MCP, OpenAI plugins and GPT Actions are distinct contracts.
+
+| Surface | Constraint / treatment |
+|---|---|
+| MCP | No universal catalog token limit is asserted. Negotiate the advertised protocol and capabilities. |
+| OpenAI function compatibility | MSO names use letters/numbers/underscore/hyphen, at most 64 characters. |
+| OpenAI UI metadata | Invocation status strings at most 64 characters. |
+| GPT Actions only | 300-character operation descriptions/summaries; 700-character parameter descriptions; under 100,000 characters per request/response; 45-second timeout. These are not MCP limits. |
+| MSO compact catalog | Under 96 KiB total and 8 KiB per descriptor; local regression budgets. |
+| Token counts | Byte/4 is a heuristic only. Use the selected model's tokenizer or the official input-token count endpoint for a real model-specific count. |
+
+Run `node scripts/check-mcp-budgets.mjs` after catalog changes. It runs in the release test
+suite too. Refresh/rescan the client after toolset changes; a server deployment cannot force
+a cached ChatGPT plugin snapshot to refresh.
+
+Sources: [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28),
+[OpenAI plugin reference](https://developers.openai.com/plugins/reference),
+[GPT Actions production](https://developers.openai.com/api/docs/actions/production),
+[token counting](https://developers.openai.com/api/docs/guides/token-counting),
+[remote MCP review](https://developers.openai.com/plugins/deploy/app-review).
+
+## Workflow storage
+
+Active workflow updates now checkpoint to the base store's `.active.json` sidecar instead
+of serializing learned recipes on every tool event. Snapshot ids prevent an old sidecar
+from undoing a newer complete store. Back up both files together. Full learning writes
+still atomically persist the complete store. This follows the existing single-process
+workflow-store model; a multi-writer database is not introduced.
diff --git a/docs/CLI.md b/docs/CLI.md
index 6b87d6ba..21bd4d0a 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -87,6 +87,7 @@ Commands:
model [ref] Select active model from a connected provider
onboard [-y] Guided setup: AI, apps, infrastructure, skills
setup Alias for onboard
+ flow list|inspect|run|status|save|delete Project API/MCP automation (flow --help)
integrations Named credential users, connections, sources, setup and execution
provider * Infrastructure credentials: list | set | rm | doctor
providers * Alias for provider
diff --git a/docs/MCP.md b/docs/MCP.md
index dad158ca..2ab45d09 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -66,7 +66,10 @@ normally omit `Origin`; browser-origin traffic is accepted only from the configu
from a loopback browser talking to the loopback cockpit.
-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.
+For reusable provider/project flows, explicit agent sessions, Add MCP and asset promotion,
+see [AUTOMATION-FLOWS.md](./AUTOMATION-FLOWS.md).
+
+MSO uses Streamable HTTP JSON-RPC on `POST /mcp`. `initialize` negotiates supported protocol versions and subsequent `MCP-Protocol-Version` headers are validated. Modern 2026-07-28 clients use per-request protocol/capability metadata, matching Mcp-Method/Mcp-Name headers and server/discover; initialize and Mcp-Session-Id remain legacy-only. Modern responses include resultType and serverInfo metadata. 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.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 6ac77990..9a6d513b 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,14 @@
+## 2026-09-12 — Dynamic project MCP and reusable provider flows
+
+Added versioned project automation, shared CLI/MCP execution, durable idempotency receipts,
+provider-neutral sessions, Add MCP in native/embedded integrations, and safe project asset promotion.
+HTTP/SSE discovery is incremental, auth-bound and paginated; rich downstream results retain
+image/audio/resource blocks. Modern 2026-07-28 requests coexist with legacy clients. Existing
+MSO capabilities are retained, with automated compact-catalog byte and official metadata checks.
+Session enumeration no longer drops records beyond 5,000; active workflow checkpoints avoid
+rewriting recipe history per event. Nonzero exec results now count as failed outcomes.
+See [automation contracts and limits](AUTOMATION-FLOWS.md).
+
## 2026-09-12 — Hosted history scan and security inventory readiness
The hosted checks for PR #41 exposed two distinct failures not covered by the earlier local
diff --git a/docs/PROJECT-MCP-CONNECTIONS.md b/docs/PROJECT-MCP-CONNECTIONS.md
index c47cee69..c0f6b3e3 100644
--- a/docs/PROJECT-MCP-CONNECTIONS.md
+++ b/docs/PROJECT-MCP-CONNECTIONS.md
@@ -44,8 +44,20 @@ selected bearer. No account fallback or scope escalation occurs.
Tools remain dynamic data behind `project_capabilities`, `project_mcp_tools`
and `project_mcp_call`; no project-specific tool joins the MSO global catalog.
-Discovery follows at most eight pages and 128 permitted tools, and fails explicitly
-on incomplete/repeated cursors instead of claiming an exhaustive partial catalog.
+Discovery is paginated (default 50, maximum 100 tools per page), with opaque cursors
+bound to the connection identity and upstream page. Follow nextCursor until absent.
+A 30-second bounded cache reuses HTTP sessions and discovery; connection authorization
+is checked before reuse. Private credential rotation invalidates cached identity.
+The legacy aggregate helper still stops after eight upstream pages and fails explicitly
+if incomplete. Downstream responses are bounded to 2 MiB; an individually very large
+descriptor may exceed the preferred 48 KiB page budget.
+
+HTTP probes modern server/discover once and falls back to legacy initialize when unsupported.
+Modern stdio is opt-in with protocolVersion: 2026-07-28. Rich image/audio/resource results
+are preserved; downstream UI metadata is namespaced rather than trusted as MSO UI origins.
+
+Use Integrations → Add MCP or project_mcp_manage to register an HTTPS endpoint with
+revision checks. See [automation flows](AUTOMATION-FLOWS.md) for CLI, sessions and assets.
Tool arguments are objects, bounded to 128 KiB; downstream schema validation remains
the application's authority. Descriptions/results are untrusted tool data.
diff --git a/docs/README.md b/docs/README.md
index dd4959b4..b36f7eed 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -34,6 +34,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`INTEGRATION-PORTABILITY.md`](./INTEGRATION-PORTABILITY.md) | Reviewed JSON identity transfers, encrypted credentials, SC interoperability and receiver limits |
| [`INTEGRATIONS.md`](./INTEGRATIONS.md) | Native temporary credential forms, direct HTTPS secret submission, CLI and ChatGPT Page |
| [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs |
+| [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits |
| [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |
| [`A2A.md`](./A2A.md) | A2A v1 peer discovery, delegation/task lifecycle, CLI/MCP surface and trust boundary |
| [`LOCAL-AGENTS.md`](./LOCAL-AGENTS.md) | Native same-host session presence, identity, mailbox delivery, TUI/tools/API and isolation |
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index c1ac2be7..9cd6329a 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,21 +4,21 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.12.3 version=2026.09.10.1 tools=97 read=47 write=30 exec=20 -->
+<!-- mcp-toolset: server=1.13.0 version=2026.09.12.1 tools=104 read=49 write=34 exec=21 -->
| Fact | Current source value |
|---|---:|
-| MCP server | `1.12.3` |
-| Toolset | `2026.09.10.1` |
-| Toolset changed at | `2026-09-10T02:40:00Z` |
-| Transport tools | **99** |
-| Model/operator tools | **97** |
-| Read | **47** |
-| Write | **30** |
-| Exec | **20** |
+| MCP server | `1.13.0` |
+| Toolset | `2026.09.12.1` |
+| Toolset changed at | `2026-09-12T12:55:00Z` |
+| Transport tools | **106** |
+| Model/operator tools | **104** |
+| Read | **49** |
+| Write | **34** |
+| Exec | **21** |
| App-only bridges | **2** |
-### Read (47)
+### Read (49)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -36,6 +36,8 @@
- `dokploy_applications_list`
- `dokploy_projects_list`
- `exec_job_status`
+- `flow_catalog`
+- `flow_status`
- `fs_list`
- `fs_read`
- `fs_search`
@@ -68,18 +70,20 @@
- `tool_forge_candidates`
- `vps_status`
-### Write (30)
+### Write (34)
- `a2a_agent_register`
- `a2a_agent_remove`
- `agent_memory_forget`
- `agent_memory_remember`
- `agent_session_note`
+- `agent_session_open`
- `agent_session_rename`
- `apps_power`
- `cloudflare_dns_upsert`
- `dokploy_application_public_env_upsert`
- `dokploy_project_ensure`
+- `flow_manage`
- `fs_copy`
- `fs_delete`
- `fs_mkdir`
@@ -91,7 +95,9 @@
- `integration_setup_open`
- `local_agent_message_send`
- `local_agent_reply`
+- `project_asset_attach`
- `project_knowledge_set`
+- `project_mcp_manage`
- `project_memory_upsert`
- `project_script_run`
- `session_artifact_register`
@@ -101,7 +107,7 @@
- `workflow_finish`
- `workflow_start`
-### Exec (20)
+### Exec (21)
- `a2a_handoff`
- `a2a_message_send`
@@ -111,6 +117,7 @@
- `exec_job_cancel`
- `exec_job_start`
- `exec_run`
+- `flow_run`
- `integration_execute`
- `local_agent_request`
- `project_agent_run`
@@ -131,20 +138,20 @@
## ChatGPT model profile
-<!-- mcp-chatgpt-profile: server=1.12.3 version=2026.09.10.1 tools=97 read=47 write=30 exec=20 app-only=2 total=99 -->
+<!-- mcp-chatgpt-profile: server=1.13.0 version=2026.09.12.1 tools=104 read=49 write=34 exec=21 app-only=2 total=106 -->
The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **99** |
-| ChatGPT model/operator tools | **97** |
-| Read | **47** |
-| Write | **30** |
-| Exec | **20** |
+| ChatGPT transport tools | **106** |
+| ChatGPT model/operator tools | **104** |
+| Read | **49** |
+| Write | **34** |
+| Exec | **21** |
| App-only bridges | **2** |
-### ChatGPT read (47)
+### ChatGPT read (49)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -162,6 +169,8 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `dokploy_applications_list`
- `dokploy_projects_list`
- `exec_job_status`
+- `flow_catalog`
+- `flow_status`
- `fs_list`
- `fs_read`
- `fs_search`
@@ -194,18 +203,20 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `tool_forge_candidates`
- `vps_status`
-### ChatGPT write (30)
+### ChatGPT write (34)
- `a2a_agent_register`
- `a2a_agent_remove`
- `agent_memory_forget`
- `agent_memory_remember`
- `agent_session_note`
+- `agent_session_open`
- `agent_session_rename`
- `apps_power`
- `cloudflare_dns_upsert`
- `dokploy_application_public_env_upsert`
- `dokploy_project_ensure`
+- `flow_manage`
- `fs_copy`
- `fs_delete`
- `fs_mkdir`
@@ -217,7 +228,9 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `integration_setup_open`
- `local_agent_message_send`
- `local_agent_reply`
+- `project_asset_attach`
- `project_knowledge_set`
+- `project_mcp_manage`
- `project_memory_upsert`
- `project_script_run`
- `session_artifact_register`
@@ -227,7 +240,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `workflow_finish`
- `workflow_start`
-### ChatGPT exec (20)
+### ChatGPT exec (21)
- `a2a_handoff`
- `a2a_message_send`
@@ -237,6 +250,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/
- `exec_job_cancel`
- `exec_job_start`
- `exec_run`
+- `flow_run`
- `integration_execute`
- `local_agent_request`
- `project_agent_run`
diff --git a/docs/schemas/mso-flows.schema.json b/docs/schemas/mso-flows.schema.json
new file mode 100644
index 00000000..5aad5efb
--- /dev/null
+++ b/docs/schemas/mso-flows.schema.json
@@ -0,0 +1,145 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "title": "MSO project automation manifest v1",
+ "description": "Structural schema. Runtime also enforces byte limits, secret-field rejection, unique ids, backward-only references, safe defaults, project and authority constraints.",
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "version",
+ "flows"
+ ],
+ "properties": {
+ "version": {
+ "const": 1
+ },
+ "flows": {
+ "type": "array",
+ "maxItems": 32,
+ "items": {
+ "$ref": "#/$defs/flow"
+ }
+ }
+ },
+ "$defs": {
+ "flow": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id",
+ "description",
+ "inputs",
+ "steps"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[a-z][a-z0-9_.-]{0,63}$"
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 600
+ },
+ "inputs": {
+ "type": "object",
+ "maxProperties": 32,
+ "propertyNames": {
+ "pattern": "^[a-z][a-z0-9_-]{0,63}$"
+ },
+ "additionalProperties": {
+ "$ref": "#/$defs/input"
+ }
+ },
+ "steps": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": 12,
+ "items": {
+ "$ref": "#/$defs/step"
+ }
+ }
+ }
+ },
+ "input": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "description"
+ ],
+ "properties": {
+ "type": {
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "object",
+ "array"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 300
+ },
+ "required": {
+ "type": "boolean"
+ },
+ "default": {},
+ "enum": {
+ "type": "array",
+ "maxItems": 64,
+ "items": {
+ "type": [
+ "string",
+ "number",
+ "boolean"
+ ]
+ }
+ }
+ }
+ },
+ "step": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id",
+ "tool",
+ "arguments"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[a-z][a-z0-9_-]{0,63}$"
+ },
+ "tool": {
+ "enum": [
+ "integration_execute",
+ "project_mcp_call",
+ "project_function_call"
+ ]
+ },
+ "arguments": {
+ "type": "object"
+ },
+ "expect": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "path",
+ "equals"
+ ],
+ "properties": {
+ "path": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256
+ },
+ "equals": {}
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/lib/agent/session-create.ts b/lib/agent/session-create.ts
index 17dcd6b5..35212fe1 100644
--- a/lib/agent/session-create.ts
+++ b/lib/agent/session-create.ts
@@ -24,12 +24,9 @@ async function buildRecord(
principal: string,
source: AgentSessionSource,
options: CreateOptions,
+ usedNames: string[],
): Promise<AgentSession> {
const now = new Date().toISOString();
- const owner = principalHash(principal);
- const usedNames = (await listSessionRecords())
- .filter((row) => row.principalHash === owner)
- .map((row) => row.name);
const name = options.name ? requireAgentSessionName(options.name) : allocateAgentSessionName(usedNames);
if (usedNames.includes(name)) throw new Error(`session name @${name} is already in use`);
const memorySnapshot =
@@ -87,23 +84,9 @@ export async function withUniqueSessionName<T>(
commit: (record: AgentSession) => Promise<T>,
): Promise<T> {
const owner = principalHash(principal);
- const requested = options.name ? requireAgentSessionName(options.name) : undefined;
- for (let attempt = 0; attempt < 100; attempt += 1) {
- const used = (await listSessionRecords())
- .filter((row) => row.principalHash === owner)
- .map((row) => row.name);
- const name = requested ?? allocateAgentSessionName(used);
- try {
- return await withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
- const record = await buildRecord(principal, source, { ...options, name });
- return commit(record);
- });
- } catch (error) {
- const duplicate = error instanceof Error && /session name @.+ is already in use/.test(error.message);
- if (!requested && duplicate) continue;
- throw error;
- }
- }
- throw new Error("could not allocate a unique session name");
+ // ponytail: one owner lock and scan per creation; index names if this measured scan becomes material.
+ return withSecurityStoreLock(sessionNameLockTarget(owner), async () => {
+ const used = (await listSessionRecords()).filter(row => row.principalHash === owner).map(row => row.name);
+ return commit(await buildRecord(principal, source, options, used));
+ });
}
-
diff --git a/lib/agent/session-enumeration.test.ts b/lib/agent/session-enumeration.test.ts
new file mode 100644
index 00000000..54246b44
--- /dev/null
+++ b/lib/agent/session-enumeration.test.ts
@@ -0,0 +1,18 @@
+import { afterAll, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-session-enumeration-"));
+vi.stubEnv("OS_AGENT_SESSIONS_DIR", root);
+vi.resetModules();
+const { listSessionRecords } = await import("./session-files");
+afterAll(async () => { vi.unstubAllEnvs(); await fs.rm(root, {recursive:true,force:true}); });
+it("enumerates sessions beyond the former 5000-file cutoff with bounded reads", async () => {
+ for (let start=0; start<5001; start+=100) await Promise.all(Array.from({length:Math.min(100,5001-start)},async (_,offset)=>{
+ const id="20260912_000000_"+(start+offset).toString(16).padStart(8,"0");
+ await fs.writeFile(path.join(root,id+".json"),JSON.stringify({id,principalHash:"fixture",source:"mcp",history:[],events:[],memorySnapshot:{}}),{mode:0o600});
+ }));
+ const rows=await listSessionRecords();
+ expect(rows).toHaveLength(5001);
+ expect(rows.some(row=>row.id.endsWith("00001388"))).toBe(true);
+},15000);
diff --git a/lib/agent/session-files.ts b/lib/agent/session-files.ts
index c8922341..4eed9f25 100644
--- a/lib/agent/session-files.ts
+++ b/lib/agent/session-files.ts
@@ -29,8 +29,9 @@ export function sessionLockTarget(id: string): string {
return path.join(LOCK_ROOT, "sessions", id);
}
-export function sessionNameLockTarget(ownerHash: string, name: string): string {
+export function sessionNameLockTarget(ownerHash: string, name?: string): string {
if (!HASH64.test(ownerHash)) throw new Error("invalid agent session owner hash");
+ if (name === undefined) return path.join(LOCK_ROOT, "name-allocation", ownerHash);
if (!/^[a-z][a-z0-9-]{1,23}$/.test(name)) throw new Error("invalid agent session name lock");
return path.join(LOCK_ROOT, "names", ownerHash, name);
}
@@ -163,11 +164,11 @@ export async function listSessionRecords(): Promise<AgentSession[]> {
throw error;
}
const out: AgentSession[] = [];
- for (const name of names.slice(0, 5000)) {
- if (!name.endsWith(".json")) continue;
- const id = name.slice(0, -5);
- if (!SESSION_ID.test(id)) continue;
- try { const row = await readSessionFile(id); if (row) out.push(row); } catch { /* isolate corrupt rows */ }
+ const ids = names.filter(name => name.endsWith(".json") && SESSION_ID.test(name.slice(0, -5))).map(name => name.slice(0, -5));
+ // Bounded concurrency, complete enumeration: never silently drop later sessions.
+ for (let start = 0; start < ids.length; start += 32) {
+ const rows = await Promise.all(ids.slice(start, start + 32).map(id => readSessionFile(id).catch(() => null)));
+ out.push(...rows.filter((row): row is AgentSession => row !== null));
}
return out;
}
diff --git a/lib/agent/session-mutations.ts b/lib/agent/session-mutations.ts
index a2bbeaaa..a0dc8cca 100644
--- a/lib/agent/session-mutations.ts
+++ b/lib/agent/session-mutations.ts
@@ -66,7 +66,7 @@ export async function renameAgentSessionName(
): Promise<AgentSession> {
const name = requireAgentSessionName(value);
const owner = principalHash(principal);
- return withSecurityStoreLock(sessionNameLockTarget(owner, name), async () => {
+ return withSecurityStoreLock(sessionNameLockTarget(owner), async () => {
const duplicate = (await listSessionRecords()).find((row) =>
row.principalHash === owner && row.id !== id && row.name === name,
);
diff --git a/lib/capabilities/actors.ts b/lib/capabilities/actors.ts
index 4afe3301..2a5b81fa 100644
--- a/lib/capabilities/actors.ts
+++ b/lib/capabilities/actors.ts
@@ -1,6 +1,6 @@
import type { CapabilityToolProfile } from "./tool";
-export interface CapabilityAgentContext { principal?: string; sessionId?: string; toolProfile?: CapabilityToolProfile; }
+export interface CapabilityAgentContext { principal?: string; sessionId?: string; toolProfile?: CapabilityToolProfile; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }
export function workflowActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {
return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;
}
diff --git a/lib/capabilities/execute.ts b/lib/capabilities/execute.ts
index b982181a..10b98824 100644
--- a/lib/capabilities/execute.ts
+++ b/lib/capabilities/execute.ts
@@ -1,3 +1,4 @@
+import { capabilityReportedFailure } from "./result-outcome";
import { audit } from "@/lib/host/audit-api";
import { maybeAutoTitleAgentSession } from "@/lib/agent/session-store";
import { touchLocalAgentPresence } from "@/lib/agent/local-agent-presence";
@@ -31,8 +32,12 @@ export async function executeCapabilityCall(input: {
actor?: string;
context?: CapabilityExecutionContext;
}): Promise<CapabilityExecutionResult> {
+ const startedAt = Date.now();
const { tool, args, scope, actor, context } = input;
const name = tool.name;
+ if (context?.allowedTools && !context.allowedTools.includes(name)) return { kind: "error", message: "tool is not allowed for this token" };
+ const constraints = context?.toolArgumentConstraints?.[name];
+ if (constraints && Object.entries(constraints).some(([key, allowed]) => typeof args[key] !== "string" || !allowed.includes(args[key] as string))) return { kind: "error", message: "tool input is not allowed for this token" };
const presence = context?.principal?.startsWith("mcp-") && context.sessionId
? { principal: context.principal, sessionId: context.sessionId, instanceId: `mcp:${context.sessionId}` }
: null;
@@ -87,7 +92,7 @@ export async function executeCapabilityCall(input: {
}
const trail = tool.audit, auditTarget = trail?.targetArg != null ? String(args[trail.targetArg] ?? "") : undefined;
- const activityId = newActivityId(), startedAt = Date.now();
+ const activityId = newActivityId();
if (!workflowProbe) void recordCapabilityActivity({ id: activityId, actor, tool: name, state: "started", scope, ...initialFlow, target });
try {
if (presence)
@@ -109,18 +114,22 @@ export async function executeCapabilityCall(input: {
workflowId: activeWorkflow?.id,
workflowActor: flowActor,
recipeActor: learnedActor,
+ allowedTools: context?.allowedTools,
+ toolArgumentConstraints: context?.toolArgumentConstraints,
capabilities: context?.capabilities,
toolProfile: context?.toolProfile,
});
+ const reportedFailure = capabilityReportedFailure(result) || trail?.outcome?.(result)?.ok === false;
+ const completedState = reportedFailure ? "failed" : "completed";
if (trail) {
const outcome = trail.outcome?.(result);
- void audit({ action: outcome?.action ?? trail.action, actor, target: auditTarget, ok: outcome?.ok ?? true, detail: outcome?.detail, meta: { via: "mcp", scope } });
+ void audit({ action: outcome?.action ?? trail.action, actor, target: auditTarget, ok: !reportedFailure, detail: outcome?.detail, meta: { via: "mcp", scope } });
}
const durationMs = Date.now() - startedAt, completedWorkflow = workflowFromResult(result) ?? activeWorkflow;
if (!workflowProbe) {
- void recordCapabilityActivity({ id: activityId, actor, tool: name, state: "completed", scope, ...flowFields(completedWorkflow), target, durationMs });
- await recordWorkflowStep(flowActor, completedWorkflow?.id, { id: activityId, tool: name, state: "completed", target, args, durationMs, ts: new Date().toISOString() });
- await recordAgentEvent(context, name, "completed", args, completedWorkflow?.id, target);
+ void recordCapabilityActivity({ id: activityId, actor, tool: name, state: completedState, scope, ...flowFields(completedWorkflow), target, durationMs });
+ await recordWorkflowStep(flowActor, completedWorkflow?.id, { id: activityId, tool: name, state: completedState, target, args, durationMs, ts: new Date().toISOString() });
+ await recordAgentEvent(context, name, completedState, args, completedWorkflow?.id, target);
}
if (presence)
await touchLocalAgentPresence(presence.principal, presence.sessionId, "idle", presence.instanceId).catch(() => undefined);
diff --git a/lib/capabilities/result-outcome.test.ts b/lib/capabilities/result-outcome.test.ts
new file mode 100644
index 00000000..c19a9668
--- /dev/null
+++ b/lib/capabilities/result-outcome.test.ts
@@ -0,0 +1,6 @@
+import { expect, it } from "vitest";
+import { capabilityReportedFailure } from "./result-outcome";
+it("classifies direct/nested MCP errors and failed processes without guessing from ordinary status data", () => {
+ for (const result of [{ isError: true, content: [] }, { result: { isError: true } }, { code: 2, stdout: "", stderr: "failed" }]) expect(capabilityReportedFailure(result)).toBe(true);
+ for (const result of [{ code: 404 }, { ok: false }, { result: { content: [] } }, null]) expect(capabilityReportedFailure(result)).toBe(false);
+});
diff --git a/lib/capabilities/result-outcome.ts b/lib/capabilities/result-outcome.ts
new file mode 100644
index 00000000..0ff9f8c8
--- /dev/null
+++ b/lib/capabilities/result-outcome.ts
@@ -0,0 +1,8 @@
+/** Operational failures remain intact for callers, but must not count as successful steps. */
+export function capabilityReportedFailure(value: unknown, depth = 0): boolean {
+ if (!value || typeof value !== "object" || Array.isArray(value) || depth > 3) return false;
+ const row = value as Record<string, unknown>;
+ if (row.isError === true) return true;
+ if (typeof row.code === "number" && row.code !== 0 && (typeof row.stdout === "string" || typeof row.stderr === "string")) return true;
+ return capabilityReportedFailure(row.result, depth + 1);
+}
diff --git a/lib/capabilities/runtime.ts b/lib/capabilities/runtime.ts
index 2330fdb2..5e204f41 100644
--- a/lib/capabilities/runtime.ts
+++ b/lib/capabilities/runtime.ts
@@ -1,8 +1,7 @@
import type { Scope } from "./scope";
-export type CapabilityContent =
- | { type: "text"; text: string }
- | { type: "image"; data: string; mimeType: string };
+export type { McpContent as CapabilityContent } from "@/lib/contracts/mcp-content";
+import type { McpContent as CapabilityContent } from "@/lib/contracts/mcp-content";
export interface CapabilityDescriptor {
name: string;
diff --git a/lib/capabilities/tool.ts b/lib/capabilities/tool.ts
index 27351ceb..691feba7 100644
--- a/lib/capabilities/tool.ts
+++ b/lib/capabilities/tool.ts
@@ -4,9 +4,8 @@ import type { Scope } from "./scope";
export type CapabilityToolProfile = "full" | "chatgpt";
-export type CapabilityContent =
- | { type: "text"; text: string }
- | { type: "image"; data: string; mimeType: string };
+export type { McpContent as CapabilityContent } from "@/lib/contracts/mcp-content";
+import type { McpContent as CapabilityContent } from "@/lib/contracts/mcp-content";
export interface CapabilityDirectResult {
__mcpDirect: true;
@@ -46,6 +45,8 @@ export interface CapabilityRunContext {
workflowId?: string;
workflowActor?: string;
recipeActor?: string;
+ allowedTools?: readonly string[];
+ toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>;
capabilities?: CapabilityRuntime;
toolProfile?: CapabilityToolProfile;
}
diff --git a/lib/contracts/automation.ts b/lib/contracts/automation.ts
new file mode 100644
index 00000000..79bdff8e
--- /dev/null
+++ b/lib/contracts/automation.ts
@@ -0,0 +1,27 @@
+export type FlowInput = {
+ type: "string" | "number" | "integer" | "boolean" | "object" | "array";
+ description: string;
+ required?: boolean;
+ default?: unknown;
+ enum?: Array<string | number | boolean>;
+};
+export type FlowStep = {
+ id: string;
+ tool: "integration_execute" | "project_mcp_call" | "project_function_call";
+ arguments: Record<string, unknown>;
+ expect?: { path: string; equals: unknown };
+};
+export type AutomationFlow = {
+ id: string;
+ description: string;
+ inputs: Record<string, FlowInput>;
+ steps: FlowStep[];
+};
+export type FlowRun = {
+ version: 1; id: string; owner: string; sessionId: string; project: string; flow: string;
+ fingerprint: string; pid: number; instance: string;
+ state: "running" | "completed" | "failed" | "interrupted";
+ startedAt: string; updatedAt: string; finishedAt?: string;
+ steps: Array<{ id: string; tool: string; state: "running" | "completed" | "failed"; durationMs?: number; result?: unknown; error?: string }>;
+ error?: string;
+};
diff --git a/lib/contracts/mcp-content.ts b/lib/contracts/mcp-content.ts
new file mode 100644
index 00000000..f7d6f1da
--- /dev/null
+++ b/lib/contracts/mcp-content.ts
@@ -0,0 +1,6 @@
+/** MCP content blocks remain intact across broker transports. */
+export type McpContent =
+ | { type: "text"; text: string; annotations?: Record<string, unknown>; _meta?: Record<string, unknown> }
+ | { type: "image" | "audio"; data: string; mimeType: string; annotations?: Record<string, unknown>; _meta?: Record<string, unknown> }
+ | { type: "resource_link"; uri: string; name: string; description?: string; mimeType?: string; _meta?: Record<string, unknown> }
+ | { type: "resource"; resource: { uri: string; mimeType?: string; text?: string; blob?: string }; _meta?: Record<string, unknown> };
diff --git a/lib/contracts/project-mcp.ts b/lib/contracts/project-mcp.ts
index bc9076ca..695c0274 100644
--- a/lib/contracts/project-mcp.ts
+++ b/lib/contracts/project-mcp.ts
@@ -4,3 +4,5 @@ export type PublicProjectMcpServer = {
transport: "stdio" | "http";
auth: "none" | "configured" | "oauth" | "integration";
};
+
+export type ProjectMcpTool = { name: string; title?: string; description?: string; inputSchema: Record<string, unknown>; outputSchema?: unknown; annotations?: unknown; icons?: unknown; execution?: unknown; _meta?: unknown };
diff --git a/lib/host/fs-upload.ts b/lib/host/fs-upload.ts
index 5f1942f3..313f784e 100644
--- a/lib/host/fs-upload.ts
+++ b/lib/host/fs-upload.ts
@@ -18,6 +18,7 @@ const MAX_UPLOAD = 100 * 1024 * 1024; // 100 MiB per file
export async function uploadInto(
dest: string,
files: { relPath: string; data: Uint8Array }[],
+ options: { overwrite?: boolean } = {},
): Promise<{ written: number; failed: string[] }> {
const destReal = await resolveUploadDest(dest);
@@ -40,7 +41,8 @@ export async function uploadInto(
await assertUploadTarget(full, destReal); // parent may have appeared since the first check
await fs.writeFile(tmp, data, { mode: 0o600, flag: "wx" });
await fs.chmod(tmp, 0o644);
- await fs.rename(tmp, full);
+ if (options.overwrite === false) await fs.link(tmp, full);
+ else await fs.rename(tmp, full);
written++;
} catch {
failed.push(relPath);
diff --git a/lib/host/project-assets.test.ts b/lib/host/project-assets.test.ts
new file mode 100644
index 00000000..7b0f7600
--- /dev/null
+++ b/lib/host/project-assets.test.ts
@@ -0,0 +1,19 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+let root = "";
+afterEach(async () => { vi.unstubAllEnvs(); if (root) await fs.rm(root, { recursive: true, force: true }); });
+it("attaches once, refuses overwrites/traversal/symlinks and keeps a durable project copy", async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-project-asset-"));
+ vi.stubEnv("OS_FS_WRITE_ROOTS", root); vi.stubEnv("OS_FS_READ_ROOTS", root); vi.resetModules();
+ const { attachProjectAsset } = await import("./project-assets");
+ const data = Buffer.alloc(24, 1);
+ const result = await attachProjectAsset(root, "public/assets/hero.png", data, "image/png");
+ expect(result.unchanged).toBe(false); expect(await fs.readFile(result.path)).toEqual(data);
+ expect((await attachProjectAsset(root, "public/assets/hero.png", data, "image/png")).unchanged).toBe(true);
+ await expect(attachProjectAsset(root, "public/assets/hero.png", Buffer.alloc(24, 2), "image/png")).rejects.toThrow("different content");
+ for (const target of ["../outside.png", "/outside.png", "a/../b.png", "a\\b.png", "hero.html"]) await expect(attachProjectAsset(root, target, data, "image/png")).rejects.toThrow();
+ await fs.symlink(os.tmpdir(), path.join(root, "link"));
+ await expect(attachProjectAsset(root, "link/x.png", data, "image/png")).rejects.toThrow();
+});
diff --git a/lib/host/project-assets.ts b/lib/host/project-assets.ts
new file mode 100644
index 00000000..b0339c67
--- /dev/null
+++ b/lib/host/project-assets.ts
@@ -0,0 +1,30 @@
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { createHash } from "node:crypto";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { readBoundedRegularBuffer } from "./bounded-read";
+import { assertUploadTarget } from "./paths";
+import { uploadInto, resolveUploadDest } from "./fs-api";
+export async function attachProjectAsset(projectPath: string, relativePath: string, bytes: Buffer, mimeType: string) {
+ const parts = relativePath.split("/");
+ if (!relativePath || relativePath.length > 1024 || parts.some(p => !p || p === "." || p === ".." || p.trim() !== p || /[\\\x00-\x1f]/.test(p))) throw new Error("asset path must stay inside the project");
+ const extensions: Record<string, string[]> = { "image/png": [".png"], "image/jpeg": [".jpg", ".jpeg"], "image/webp": [".webp"], "application/json": [".json"] };
+ if (!extensions[mimeType]?.includes(path.extname(relativePath).toLowerCase())) throw new Error("asset extension must match its MIME type");
+ const directory = await resolveUploadDest(projectPath), target = path.join(directory, ...parts);
+ await assertUploadTarget(target, directory);
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
+ return withSecurityStoreLock(target, async () => {
+ const stat = await fs.lstat(target).catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return null; throw e; });
+ let unchanged = false;
+ if (stat) {
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("unsafe asset target");
+ const current = await readBoundedRegularBuffer(target, 12 * 1024 * 1024);
+ if (!current || createHash("sha256").update(current).digest("hex") !== sha256) throw new Error("asset already exists with different content; choose another path");
+ unchanged = true;
+ } else {
+ const result = await uploadInto(directory, [{ relPath: relativePath, data: bytes }], { overwrite: false });
+ if (result.written !== 1) throw new Error("asset could not be created safely; inspect the destination");
+ }
+ return { path: target, relativePath, sha256, bytes: bytes.length, mimeType, unchanged, retention: "project-owned; independent of temporary session cleanup" };
+ });
+}
diff --git a/lib/host/project-capabilities.ts b/lib/host/project-capabilities.ts
index 513081a2..d6e28325 100644
--- a/lib/host/project-capabilities.ts
+++ b/lib/host/project-capabilities.ts
@@ -6,4 +6,4 @@ 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";
+export { listProjectMcpTools, listProjectMcpToolPage, callProjectMcpTool } from "./project-mcp-client";
diff --git a/lib/host/project-flow-manifest.ts b/lib/host/project-flow-manifest.ts
new file mode 100644
index 00000000..4e43e882
--- /dev/null
+++ b/lib/host/project-flow-manifest.ts
@@ -0,0 +1,44 @@
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { readBoundedRegularFile } from "./bounded-read";
+import { resolveReadable } from "./paths";
+import { makeDir, writeFileGuarded, sha256Text } from "./fs-api";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { parseFlow, object } from "@/lib/workflow/automation-schema";
+import type { AutomationFlow } from "@/lib/contracts/automation";
+
+export async function readProjectFlows(projectPath: string): Promise<{ flows: AutomationFlow[]; revision: string }> {
+ const directory = path.join(projectPath, ".mso"), file = path.join(directory, "flows.json");
+ const stat = await fs.lstat(directory).catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return null; throw e; });
+ if (!stat) return { flows: [], revision: "new" };
+ if (!stat.isDirectory() || stat.isSymbolicLink() || await fs.realpath(directory) !== directory) throw new Error("unsafe project flow directory");
+ const exists = await fs.lstat(file).catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return null; throw e; });
+ if (!exists) return { flows: [], revision: "new" };
+ if (exists.isSymbolicLink()) throw new Error("unsafe project flow manifest");
+ await resolveReadable(file);
+ const raw = await readBoundedRegularFile(file, 64 * 1024);
+ if (raw === null) throw new Error("flow manifest unreadable or exceeds 64 KiB");
+ const parsed: unknown = JSON.parse(raw);
+ if (!object(parsed) || parsed.version !== 1 || Object.keys(parsed).some(k => !["version", "flows"].includes(k)) ||
+ !Array.isArray(parsed.flows) || parsed.flows.length > 32) throw new Error("flow manifest must be {version:1,flows:[up to 32 flows]}");
+ const flows = parsed.flows.map(parseFlow);
+ if (new Set(flows.map(flow => flow.id)).size !== flows.length) throw new Error("duplicate flow id");
+ return { flows, revision: sha256Text(raw) };
+}
+export async function manageProjectFlow(projectPath: string, input: { action: "upsert" | "delete"; id: string; flow?: unknown; revision: string }) {
+ const directory = path.join(projectPath, ".mso"), file = path.join(directory, "flows.json");
+ await makeDir(directory);
+ return withSecurityStoreLock(file, async () => {
+ const current = await readProjectFlows(projectPath);
+ if (current.revision !== input.revision) throw new Error("flow revision changed; inspect before editing");
+ const definition = input.action === "upsert" ? parseFlow(input.flow) : undefined;
+ if (definition && definition.id !== input.id) throw new Error("flow id mismatch");
+ const flows = current.flows.filter(flow => flow.id !== input.id);
+ if (definition) flows.push(definition);
+ if (flows.length > 32) throw new Error("project flow limit is 32");
+ const content = JSON.stringify({ version: 1, flows }, null, 2) + "\n";
+ if (Buffer.byteLength(content) > 64 * 1024) throw new Error("flow manifest exceeds 64 KiB");
+ const result = await writeFileGuarded({ path: file, content, ...(current.revision !== "new" ? { expectedSha256: current.revision } : {}) });
+ return { id: input.id, action: input.action, revision: result.sha256 };
+ });
+}
diff --git a/lib/host/project-mcp-auth.test.ts b/lib/host/project-mcp-auth.test.ts
index dc29d94d..9ddf27ff 100644
--- a/lib/host/project-mcp-auth.test.ts
+++ b/lib/host/project-mcp-auth.test.ts
@@ -4,6 +4,7 @@ vi.mock("@/lib/infra/connection-service", () => ({ directConnectionValues: vi.fn
vi.mock("./ssrf", () => ({ safeProviderFetch: vi.fn(async (_url, init) => {
const payload = JSON.parse(init.body);
state.calls.push({ ...payload, auth: new Headers(init.headers).get("authorization") });
+ if (payload.method === "server/discover") return new Response(JSON.stringify({ jsonrpc: "2.0", id: payload.id, error: { code: -32601, message: "legacy" } }), { status: 400 });
if (payload.method === "tools/list" && state.paging) {
const second = Boolean(payload.params?.cursor);
return new Response(JSON.stringify({ jsonrpc: "2.0", id: payload.id, result: {
diff --git a/lib/host/project-mcp-catalog.test.ts b/lib/host/project-mcp-catalog.test.ts
new file mode 100644
index 00000000..ca5c9bb3
--- /dev/null
+++ b/lib/host/project-mcp-catalog.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it, vi } from "vitest";
+let calls = 0, token = "first";
+vi.mock("./project-mcp-auth", () => ({ projectMcpAuthorization: async (server: object) => ({ server: { ...server, headers: { authorization: token } }, allowed: null }) }));
+vi.mock("./project-mcp-transport", () => ({ withProjectMcpServer: async (_server: unknown, work: (rpc: () => Promise<unknown>) => Promise<unknown>) => {
+ calls++; return work(async () => ({ result: { tools: Array.from({ length: 151 }, (_,i) => ({ name: "tool_" + i, inputSchema: { type: "object" }, outputSchema: { type: "object" }, _meta: { ui: { resourceUri: "ui://fixture" } } })) } }));
+} }));
+import { listMcpToolPage } from "./project-mcp-catalog";
+const server = { name: "fixture", transport: "http" as const, url: "https://example.com/mcp", headers: {}, oauthConfigured: false };
+describe("complete bounded MCP discovery", () => {
+ it("paginates beyond 128 tools, retains schemas/UI metadata and reuses only matching auth cache", async () => {
+ const a = await listMcpToolPage(server, { limit: 100 });
+ expect(a.tools).toHaveLength(100); expect(a.complete).toBe(false);
+ const b = await listMcpToolPage(server, { cursor: a.nextCursor, limit: 100 });
+ expect(b.tools).toHaveLength(51); expect(b.complete).toBe(true); expect(calls).toBe(1);
+ expect(b.tools[0]).toMatchObject({ outputSchema: { type: "object" }, _meta: { ui: { resourceUri: "ui://fixture" } } });
+ token = "rotated";
+ await expect(listMcpToolPage(server, { cursor: a.nextCursor })).rejects.toThrow("another connection");
+ await listMcpToolPage(server); expect(calls).toBe(2);
+ });
+});
diff --git a/lib/host/project-mcp-catalog.ts b/lib/host/project-mcp-catalog.ts
new file mode 100644
index 00000000..112afacb
--- /dev/null
+++ b/lib/host/project-mcp-catalog.ts
@@ -0,0 +1,75 @@
+import { createHash } from "node:crypto";
+import { projectMcpAuthorization } from "./project-mcp-auth";
+import { withProjectMcpServer } from "./project-mcp-transport";
+import type { ProjectMcpServer } from "./project-mcp-config";
+import type { Rpc } from "./project-mcp-wire";
+import type { ProjectMcpTool } from "@/lib/contracts/project-mcp";
+export type { ProjectMcpTool } from "@/lib/contracts/project-mcp";
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+export function publicTools(result: unknown): ProjectMcpTool[] {
+ if (!object(result) || !Array.isArray(result.tools)) throw new Error("project MCP tools/list returned no tools array");
+ return result.tools.map(raw => {
+ if (!object(raw) || typeof raw.name !== "string" || !/^[A-Za-z0-9_.-]{1,128}$/.test(raw.name) || !object(raw.inputSchema)) throw new Error("invalid project MCP tool descriptor");
+ const kept = Object.fromEntries(["title", "description", "outputSchema", "annotations", "icons", "execution", "_meta"].filter(k => raw[k] !== undefined).map(k => [k, raw[k]]));
+ return { name: raw.name, inputSchema: raw.inputSchema, ...kept };
+ });
+}
+function nextCursor(result: unknown): string | undefined {
+ const next = (result as { nextCursor?: unknown })?.nextCursor;
+ if (next === undefined) return;
+ if (typeof next !== "string" || !next || next.length > 4096) throw new Error("project MCP returned an invalid continuation cursor");
+ return next;
+}
+export async function allTools(rpc: (method: string, params?: unknown) => Promise<Rpc>): Promise<ProjectMcpTool[]> {
+ const tools: ProjectMcpTool[] = [], seen = new Set<string>();
+ let cursor: string | undefined;
+ for (let page = 0; page < 8; page++) {
+ const result = (await rpc("tools/list", cursor ? { cursor } : {})).result;
+ tools.push(...publicTools(result)); cursor = nextCursor(result);
+ if (!cursor) return tools;
+ if (seen.has(cursor)) throw new Error("project MCP returned a repeated continuation cursor");
+ seen.add(cursor);
+ }
+ throw new Error("project MCP catalog exceeds 8 pages; use paginated project_mcp_tools");
+}
+type Page = { tools: ProjectMcpTool[]; next?: string; until: number; hash: string };
+const cache = new Map<string, Page>();
+export async function listMcpToolPage(server: ProjectMcpServer, options: { cursor?: string; limit?: number; refresh?: boolean } = {}) {
+ const auth = await projectMcpAuthorization(server);
+ const identity = createHash("sha256").update(JSON.stringify({ server: auth.server, allowed: auth.allowed })).digest("hex");
+ let remote: string | undefined, offset = 0, expectedHash: string | undefined;
+ if (options.cursor) {
+ if (options.cursor.length > 8192) throw new Error("invalid project MCP cursor");
+ let c; try { c = JSON.parse(Buffer.from(options.cursor, "base64url").toString()); } catch { throw new Error("invalid project MCP cursor"); }
+ if (!object(c) || c.identity !== identity || !Number.isSafeInteger(c.offset) || Number(c.offset) < 0 ||
+ (c.remote !== undefined && (typeof c.remote !== "string" || c.remote.length > 4096))) throw new Error("project MCP cursor expired or belongs to another connection");
+ remote = c.remote as string | undefined; offset = Number(c.offset); expectedHash = typeof c.hash === "string" ? c.hash : undefined;
+ }
+ const key = identity + ":" + (remote ?? ""), now = Date.now();
+ for (const [k,v] of cache) if (v.until <= now) cache.delete(k);
+ let page = !options.refresh && server.transport === "http" ? cache.get(key) : undefined;
+ const cached = Boolean(page);
+ if (!page) {
+ const result = await withProjectMcpServer(server, async rpc => (await rpc("tools/list", remote ? { cursor: remote } : {})).result);
+ const tools = publicTools(result);
+ page = { tools, next: nextCursor(result), until: now + 30_000, hash: createHash("sha256").update(JSON.stringify(tools)).digest("hex") };
+ if (page.next === remote && remote !== undefined) throw new Error("project MCP returned a repeated continuation cursor");
+ if (server.transport === "http") {
+ if (cache.size >= 16) cache.delete(cache.keys().next().value!);
+ cache.set(key, page);
+ }
+ }
+ if (expectedHash && page.hash !== expectedHash) throw new Error("project MCP page changed; restart discovery");
+ const limit = Math.max(1, Math.min(100, Math.trunc(options.limit ?? 50)));
+ if (offset > page.tools.length) throw new Error("project MCP page changed; restart discovery");
+ const tools: ProjectMcpTool[] = []; let bytes = 0;
+ for (const tool of page.tools.slice(offset, offset + limit)) {
+ const size = Buffer.byteLength(JSON.stringify(tool));
+ if (tools.length && bytes + size > 48 * 1024) break;
+ tools.push(tool); bytes += size;
+ }
+ const more = offset + tools.length < page.tools.length;
+ const next = more ? { identity, remote, offset: offset + tools.length, hash: page.hash } : page.next ? { identity, remote: page.next, offset: 0 } : undefined;
+ return { tools, ...(next ? { nextCursor: Buffer.from(JSON.stringify(next)).toString("base64url") } : {}),
+ complete: !next, cached, cacheTtlMs: cached ? Math.max(0, page.until - Date.now()) : server.transport === "http" ? 30_000 : 0 };
+}
diff --git a/lib/host/project-mcp-client.ts b/lib/host/project-mcp-client.ts
index ad24f38e..da7c782f 100644
--- a/lib/host/project-mcp-client.ts
+++ b/lib/host/project-mcp-client.ts
@@ -1,173 +1,13 @@
-import { projectMcpAuthorization } from "./project-mcp-auth";
-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;
+import { withProjectMcpServer } from "./project-mcp-transport";
+import { allTools, listMcpToolPage, type ProjectMcpTool } from "./project-mcp-catalog";
+export { withProjectMcpServer } from "./project-mcp-transport";
+export type { ProjectMcpTool } from "./project-mcp-catalog";
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, deadline = Date.now() + TIMEOUT_MS) {
- if (Date.now() >= deadline) throw new Error("project MCP session timed out");
- const response = await safeProviderFetch(server.url, { method: "POST", headers: remoteHeaders(server, sessionId, protocol), body: JSON.stringify(payload), signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) });
- const text = await boundedText(response);
- if (!response.ok && response.status !== 202) throw new Error(`project MCP HTTP ${response.status}; check endpoint, connection and token scope`);
- 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 deadline = Date.now() + TIMEOUT_MS;
- 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, deadline);
- 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, deadline);
- 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;
}
-export async function withProjectMcpServer<T>(server: ProjectMcpServer, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>) => Promise<T>): Promise<T> {
- const auth = await projectMcpAuthorization(server);
- const guarded = async (rpc: (method: string, params?: unknown) => Promise<Rpc>) => work(async (method, params) => {
- if (method === "tools/call" && auth.allowed && !auth.allowed.includes(String((params as { name?: string })?.name))) throw new Error("project MCP tool is not allowed by this connection");
- // Re-resolve at each RPC: removing or changing the named connection takes effect now.
- const current = await projectMcpAuthorization(server);
- if (JSON.stringify(current.server.headers) !== JSON.stringify(auth.server.headers) || JSON.stringify(current.allowed) !== JSON.stringify(auth.allowed)) throw new Error("project MCP connection changed; rediscover before continuing");
- const row = auth.redact(await rpc(method, params)) as Rpc;
- if (method === "tools/list" && auth.allowed && row.result && typeof row.result === "object") {
- const result = row.result as { tools?: ProjectMcpTool[] };
- if (Array.isArray(result.tools)) result.tools = result.tools.filter((tool) => auth.allowed!.includes(tool.name));
- }
- return row;
- });
- try { return await (auth.server.transport === "stdio" ? withStdio(auth.server, (rpc) => guarded(rpc)) : withHttp(auth.server, guarded)); }
- catch (error) { throw new Error(String(auth.redact(error instanceof Error ? error.message : "project MCP request failed"))); }
-}
-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");
- if (tools.length > 128) throw new Error("project MCP tool page exceeds 128 tools");
- return tools.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> } : {}) }];
- });
-}
-
-async function allTools(rpc: (method: string, params?: unknown) => Promise<Rpc>): Promise<ProjectMcpTool[]> {
- const tools: ProjectMcpTool[] = [], seen = new Set<string>();
- let cursor: string | undefined;
- for (let page = 0; page < 8; page++) {
- const result = (await rpc("tools/list", cursor ? { cursor } : {})).result as { nextCursor?: unknown };
- tools.push(...publicTools(result));
- if (tools.length > 128) throw new Error("project MCP catalog exceeds 128 tools; narrow the connection allowlist");
- if (result.nextCursor === undefined) return tools;
- if (typeof result.nextCursor !== "string" || !result.nextCursor || result.nextCursor.length > 4096 || seen.has(result.nextCursor)) throw new Error("project MCP returned an invalid continuation cursor");
- cursor = result.nextCursor; seen.add(cursor);
- }
- throw new Error("project MCP catalog exceeds 8 pages; discovery is incomplete");
-}
export async function listProjectMcpTools(projectPath: string, serverName: string): Promise<ProjectMcpTool[]> {
return listMcpServerTools(await selectedServer(projectPath, serverName));
}
@@ -184,3 +24,7 @@ export async function callMcpServerTool(server: ProjectMcpServer, toolName: stri
if (Buffer.byteLength(payload) > MAX_TOOL_ARGS_BYTES) throw new Error("MCP tool arguments exceed 128 KiB");
return withProjectMcpServer(server, async (rpc) => (await rpc("tools/call", { name: toolName, arguments: args ?? {} })).result);
}
+
+export async function listProjectMcpToolPage(projectPath: string, serverName: string, options: { cursor?: string; limit?: number; refresh?: boolean } = {}) {
+ return listMcpToolPage(await selectedServer(projectPath, serverName), options);
+}
diff --git a/lib/host/project-mcp-config.ts b/lib/host/project-mcp-config.ts
index 09058cea..f050aed7 100644
--- a/lib/host/project-mcp-config.ts
+++ b/lib/host/project-mcp-config.ts
@@ -9,7 +9,7 @@ const MAX_SERVERS = 16;
const MAX_ARGV = 32;
const MAX_VALUE = 4096;
-type BaseServer = { integration?: { user: string; connection: string }; name: string; headers: Record<string, string>; oauthConfigured: boolean };
+type BaseServer = { protocolVersion?: "2026-07-28"; integration?: { user: string; connection: string }; 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 }
@@ -49,6 +49,8 @@ export async function readProjectMcpServers(projectPath: string): Promise<Projec
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;
+ if (value.protocolVersion !== undefined && value.protocolVersion !== "2026-07-28") throw new Error("project MCP protocolVersion override must be 2026-07-28");
+ const protocolVersion = value.protocolVersion as "2026-07-28" | undefined;
const headers = stringMap(value.headers);
const oauthConfigured = object(value.oauth);
let integration: BaseServer["integration"];
@@ -63,11 +65,11 @@ export async function readProjectMcpServers(projectPath: string): Promise<Projec
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 });
+ out.push({ name, protocolVersion, 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, ...(integration ? { integration } : {}) });
+ out.push({ name, protocolVersion, transport: "http", url: value.url, headers, oauthConfigured, ...(integration ? { integration } : {}) });
}
}
return out;
diff --git a/lib/host/project-mcp-headers.ts b/lib/host/project-mcp-headers.ts
new file mode 100644
index 00000000..e39d4b73
--- /dev/null
+++ b/lib/host/project-mcp-headers.ts
@@ -0,0 +1,36 @@
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+type Binding = { path: string[]; header: string; type: string };
+export function mcpHeaderValue(value: string): string {
+ return /^[\x20-\x7e\t]*$/.test(value) && value.trim() === value && !(value.startsWith("=?base64?") && value.endsWith("?="))
+ ? value : "=?base64?" + Buffer.from(value).toString("base64") + "?=";
+}
+export function mcpHeaderBindings(schema: unknown): Binding[] {
+ const out: Binding[] = [], names = new Set<string>();
+ function walk(value: unknown, route: string[] | null, depth: number) {
+ if (depth > 48) throw new Error("MCP input schema exceeds header inspection depth");
+ if (!object(value)) { if (Array.isArray(value)) value.forEach(v => walk(v, null, depth + 1)); return; }
+ if (Object.hasOwn(value, "x-mcp-header")) {
+ const header = value["x-mcp-header"];
+ if (!route?.length || typeof header !== "string" || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(header) || names.has(header.toLowerCase()) ||
+ !["string", "integer", "boolean"].includes(String(value.type))) throw new Error("invalid x-mcp-header annotation");
+ names.add(header.toLowerCase()); out.push({ path: route, header: "Mcp-Param-" + header, type: String(value.type) });
+ }
+ for (const [key, child] of Object.entries(value)) {
+ if (key === "properties" && object(child)) {
+ for (const [property, spec] of Object.entries(child)) walk(spec, route ? [...route, property] : null, depth + 1);
+ } else if (key !== "x-mcp-header") walk(child, null, depth + 1);
+ }
+ }
+ walk(schema, [], 0); return out;
+}
+export function mcpArgumentHeaders(bindings: Binding[], args: unknown): Record<string, string> {
+ const headers: Record<string, string> = {};
+ for (const binding of bindings) {
+ let value = args;
+ for (const key of binding.path) { value = object(value) && Object.hasOwn(value, key) ? value[key] : undefined; }
+ if (value === undefined) continue;
+ if (binding.type === "integer" ? typeof value !== "number" || !Number.isSafeInteger(value) : typeof value !== binding.type) throw new Error("invalid MCP header parameter: " + binding.path.join("."));
+ headers[binding.header] = mcpHeaderValue(String(value));
+ }
+ return headers;
+}
diff --git a/lib/host/project-mcp-http.test.ts b/lib/host/project-mcp-http.test.ts
new file mode 100644
index 00000000..5ee5f8fd
--- /dev/null
+++ b/lib/host/project-mcp-http.test.ts
@@ -0,0 +1,31 @@
+import { beforeEach, expect, it, vi } from "vitest";
+const state = vi.hoisted(() => ({ calls: [] as Array<{ method: string; headers: Headers; params: Record<string, unknown> }>, serial: 0 }));
+vi.mock("./ssrf", () => ({ safeProviderFetch: vi.fn(async (_url, init) => {
+ const body = JSON.parse(init.body), headers = new Headers(init.headers); state.calls.push({ method: body.method, headers, params: body.params });
+ const result = body.method === "server/discover" ? { supportedVersions: ["2026-07-28"], capabilities: { tools: {} } } : body.method === "tools/list" ? { tools: [
+ { name: "echo", inputSchema: { type: "object", properties: { context: { type: "object", properties: { region: { type: "string", "x-mcp-header": "Region" } } } } } },
+ { name: "bad", inputSchema: { type: "object", properties: { amount: { type: "number", "x-mcp-header": "Amount" } } } },
+ ] } : { content: [{ type: "text", text: "done" }], isError: false };
+ return Response.json({ jsonrpc: "2.0", id: body.id, result: { resultType: "complete", ...result } });
+}) }));
+import { withHttp } from "./project-mcp-http";
+import { mcpHeaderBindings, mcpArgumentHeaders } from "./project-mcp-headers";
+beforeEach(() => { state.calls = []; state.serial++; });
+it("negotiates modern HTTP once, filters invalid header schemas and mirrors nested Unicode arguments", async () => {
+ const server = { name: "modern", transport: "http" as const, url: "https://example.test/mcp/" + state.serial, headers: {}, oauthConfigured: false };
+ const list = await withHttp(server, rpc => rpc("tools/list", {}));
+ expect((list.result as { tools: unknown[] }).tools).toHaveLength(1);
+ await withHttp(server, rpc => rpc("tools/call", { name: "echo", arguments: { context: { region: " 東京 " } } }));
+ expect(state.calls.map(c => c.method)).toEqual(["server/discover", "tools/list", "tools/call"]);
+ const call = state.calls.at(-1)!;
+ expect(call.headers.get("Mcp-Param-Region")).toBe("=?base64?" + Buffer.from(" 東京 ").toString("base64") + "?=");
+ expect(call.headers.get("Mcp-Session-Id")).toBeNull();
+ expect(call.params._meta).toMatchObject({ "io.modelcontextprotocol/clientCapabilities": {} });
+});
+it("rejects duplicate/composition annotations and unsafe integer values", () => {
+ expect(() => mcpHeaderBindings({ properties: { a: { type: "string", "x-mcp-header": "X" }, b: { type: "string", "x-mcp-header": "x" } } })).toThrow();
+ expect(() => mcpHeaderBindings({ oneOf: [{ properties: { a: { type: "string", "x-mcp-header": "X" } } }] })).toThrow();
+ const binding = mcpHeaderBindings({ properties: { count: { type: "integer", "x-mcp-header": "Count" } } });
+ expect(() => mcpArgumentHeaders(binding, { count: Number.MAX_SAFE_INTEGER + 1 })).toThrow();
+ expect(mcpArgumentHeaders(binding, {})).toEqual({});
+});
diff --git a/lib/host/project-mcp-http.ts b/lib/host/project-mcp-http.ts
new file mode 100644
index 00000000..044467e1
--- /dev/null
+++ b/lib/host/project-mcp-http.ts
@@ -0,0 +1,91 @@
+import { createHash, randomUUID } from "node:crypto";
+import { safeProviderFetch } from "./ssrf";
+import { readMcpResponse, type Rpc } from "./project-mcp-wire";
+import { mcpArgumentHeaders, mcpHeaderBindings, mcpHeaderValue } from "./project-mcp-headers";
+import type { ProjectMcpServer } from "./project-mcp-config";
+const MODERN = "2026-07-28", LEGACY = "2025-11-25";
+type Server = Extract<ProjectMcpServer, { transport: "http" }>;
+type Connection = { protocol: string; sessionId?: string; until: number; tools: Map<string, ReturnType<typeof mcpHeaderBindings>> };
+const connections = new Map<string, Connection>();
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+const meta = { "io.modelcontextprotocol/protocolVersion": MODERN, "io.modelcontextprotocol/clientCapabilities": {}, "io.modelcontextprotocol/clientInfo": { name: "mso-project-mcp", version: "2" } };
+function failure(message: Rpc) { if (message.error) throw new Error("project MCP error " + message.error.code + ": " + (message.error.message ?? "request failed")); }
+async function post(server: Server, method: string, params: unknown, connection: Connection, deadline: number, bindings?: ReturnType<typeof mcpHeaderBindings>, notification = false) {
+ if (Date.now() >= deadline) throw new Error("project MCP session timed out");
+ const modern = connection.protocol === MODERN, id = notification ? undefined : randomUUID();
+ const input = object(params) ? params : {}, body = { jsonrpc: "2.0", ...(id ? { id } : {}), method, params: modern ? { ...input, _meta: { ...(object(input._meta) ? input._meta : {}), ...meta } } : input };
+ const headers = new Headers();
+ for (const [name, value] of Object.entries(server.headers)) {
+ if (["host", "content-length", "connection", "mcp-session-id", "mcp-protocol-version", "mcp-method", "mcp-name"].includes(name.toLowerCase()) || name.toLowerCase().startsWith("mcp-param-")) continue;
+ headers.set(name, value);
+ }
+ headers.set("Content-Type", "application/json"); headers.set("Accept", "application/json, text/event-stream"); headers.set("MCP-Protocol-Version", connection.protocol);
+ if (modern) {
+ headers.set("Mcp-Method", method);
+ const name = method === "resources/read" ? input.uri : input.name;
+ if (["tools/call", "resources/read", "prompts/get"].includes(method) && typeof name === "string") headers.set("Mcp-Name", mcpHeaderValue(name));
+ for (const [key, value] of Object.entries(mcpArgumentHeaders(bindings ?? [], input.arguments))) headers.set(key, value);
+ } else if (connection.sessionId) headers.set("Mcp-Session-Id", connection.sessionId);
+ const response = await safeProviderFetch(server.url, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())) });
+ const sessionId = response.headers.get("mcp-session-id") ?? undefined;
+ if (notification && response.ok) { await response.body?.cancel(); return { message: {} as Rpc, status: response.status, sessionId }; }
+ if (!response.ok && ![400, 404, 405].includes(response.status)) { await response.body?.cancel(); throw new Error("project MCP HTTP " + response.status + "; check endpoint, connection and token scope"); }
+ let message: Rpc;
+ try { message = await readMcpResponse(response, id); } catch (e) { if (response.ok) throw e; message = {}; }
+ return { message, status: response.status, sessionId };
+}
+function rememberTools(message: Rpc, connection: Connection) {
+ if (!object(message.result) || !Array.isArray(message.result.tools)) return;
+ message.result.tools = message.result.tools.filter(tool => {
+ if (!object(tool) || typeof tool.name !== "string") return false;
+ try { connection.tools.set(tool.name, mcpHeaderBindings(tool.inputSchema)); return true; }
+ catch { connection.tools.delete(tool.name); return false; }
+ });
+}
+function complete(message: Rpc) {
+ failure(message);
+ if (!object(message.result) || message.result.resultType !== "complete") throw new Error("modern MCP result must be complete; input_required is unsupported by this connection");
+}
+export async function withHttp<T>(server: Server, 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 OAuth requires a private server-side authorization connection");
+ const deadline = Date.now() + 15_000, key = createHash("sha256").update(JSON.stringify(server)).digest("hex");
+ for (const [k,c] of connections) if (c.until < Date.now()) connections.delete(k);
+ let connection = connections.get(key);
+ if (!connection) {
+ connection = { protocol: MODERN, until: Date.now() + 30_000, tools: new Map() };
+ const probe = await post(server, "server/discover", {}, connection, deadline);
+ if (probe.status >= 400 || probe.message.error && ![-32022, -32020, -32602].includes(probe.message.error.code ?? 0)) {
+ if (probe.message.error?.code === -32022) throw new Error("downstream MCP requires an unsupported modern protocol version");
+ if (![400, 404, 405].includes(probe.status) || probe.message.error && [-32020, -32602].includes(probe.message.error.code ?? 0)) failure(probe.message);
+ connection.protocol = LEGACY;
+ const init = await post(server, "initialize", { protocolVersion: LEGACY, capabilities: {}, clientInfo: { name: "mso-project-mcp", version: "2" } }, connection, deadline);
+ failure(init.message);
+ if (init.status !== 200 || !object(init.message.result) || typeof init.message.result.protocolVersion !== "string" || !["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"].includes(init.message.result.protocolVersion)) throw new Error("invalid legacy MCP initialization");
+ connection.protocol = init.message.result.protocolVersion; connection.sessionId = init.sessionId;
+ await post(server, "notifications/initialized", {}, connection, deadline, undefined, true);
+ } else complete(probe.message);
+ if (connections.size >= 16) connections.delete(connections.keys().next().value!);
+ connections.set(key, connection);
+ }
+ const active = connection;
+ async function rpc(method: string, params?: unknown): Promise<Rpc> {
+ const input = object(params) ? params : {}, modern = active.protocol === MODERN;
+ if (modern && method === "tools/call" && typeof input.name === "string" && !active.tools.has(input.name)) {
+ const seen = new Set<string>(); let cursor: string | undefined;
+ do {
+ const page = await rpc("tools/list", cursor ? { cursor } : {});
+ cursor = object(page.result) && typeof page.result.nextCursor === "string" ? page.result.nextCursor : undefined;
+ if (active.tools.has(input.name)) break;
+ if (cursor && seen.has(cursor)) throw new Error("repeated MCP catalog cursor");
+ if (cursor) seen.add(cursor);
+ } while (cursor);
+ if (!active.tools.has(input.name)) throw new Error("tool is absent or has invalid x-mcp-header annotations; rediscover the server");
+ }
+ const row = await post(server, method, params, active, deadline, active.tools.get(String(input.name)));
+ if (row.status >= 400) { connections.delete(key); failure(row.message); throw new Error("project MCP HTTP " + row.status); }
+ if (modern) complete(row.message); else failure(row.message);
+ if (modern && method === "tools/list") rememberTools(row.message, active);
+ return row.message;
+ }
+ return work(rpc);
+}
diff --git a/lib/host/project-mcp-manage.test.ts b/lib/host/project-mcp-manage.test.ts
new file mode 100644
index 00000000..88830384
--- /dev/null
+++ b/lib/host/project-mcp-manage.test.ts
@@ -0,0 +1,23 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+vi.mock("@/lib/infra/connection-service", () => ({ directConnectionValues: async () => ({ endpoint: "https://example.test/mcp", accessToken: "private-value" }) }));
+let root = "";
+afterEach(async () => { vi.unstubAllEnvs(); if (root) await fs.rm(root, { recursive: true, force: true }); });
+it("preserves existing servers, refuses stale revisions and stores only private connection references", async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-mcp-manage-"));
+ vi.stubEnv("OS_FS_WRITE_ROOTS", root); vi.stubEnv("OS_FS_READ_ROOTS", root); vi.resetModules();
+ const { inspectProjectMcp, manageProjectMcp } = await import("./project-mcp-manage");
+ const first = await inspectProjectMcp(root);
+ expect(first.revision).toBe("new");
+ const saved = await manageProjectMcp(root, { action: "upsert", server: "one", revision: first.revision, url: "https://example.test/mcp", user: "owner", connection: "private" });
+ await expect(manageProjectMcp(root, { action: "delete", server: "one", revision: "new" })).rejects.toThrow("revision changed");
+ await manageProjectMcp(root, { action: "upsert", server: "two", revision: saved.revision, url: "https://public.test/mcp" });
+ const current = await inspectProjectMcp(root);
+ expect(current.servers.map(s => s.name)).toEqual(["one", "two"]);
+ expect(await fs.readFile(path.join(root, ".mcp.json"), "utf8")).not.toContain("private-value");
+ await expect(manageProjectMcp(root, { action: "upsert", server: "bad", revision: current.revision, url: "https://other.test/mcp", user: "owner", connection: "private" })).rejects.toThrow("does not match");
+ await manageProjectMcp(root, { action: "delete", server: "one", revision: current.revision });
+ expect((await inspectProjectMcp(root)).servers.map(s => s.name)).toEqual(["two"]);
+});
diff --git a/lib/host/project-mcp-manage.ts b/lib/host/project-mcp-manage.ts
new file mode 100644
index 00000000..daea22f3
--- /dev/null
+++ b/lib/host/project-mcp-manage.ts
@@ -0,0 +1,55 @@
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { readBoundedRegularFile } from "./bounded-read";
+import { resolveReadable } from "./paths";
+import { writeFileGuarded, sha256Text } from "./fs-api";
+import { readProjectMcpServers, publicProjectMcpServers } from "./project-mcp-config";
+import { normalizeMcpEndpoint } from "@/lib/infra/mcp-policy";
+import { directConnectionValues } from "@/lib/infra/connection-service";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+async function manifest(projectPath: string) {
+ const file = path.join(projectPath, ".mcp.json");
+ const stat = await fs.lstat(file).catch((e: NodeJS.ErrnoException) => { if (e.code === "ENOENT") return null; throw e; });
+ if (!stat) return { file, data: { mcpServers: {} } as Record<string, unknown>, revision: "new" };
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("unsafe project MCP manifest");
+ await resolveReadable(file);
+ const raw = await readBoundedRegularFile(file, 64 * 1024);
+ if (raw === null) throw new Error("MCP manifest exceeds 64 KiB");
+ const data: unknown = JSON.parse(raw);
+ if (!object(data)) throw new Error("invalid MCP manifest");
+ if (data.mcpServers !== undefined && data.servers !== undefined) throw new Error("ambiguous MCP manifest; keep one servers key");
+ if (!object(data.mcpServers ?? data.servers ?? {})) throw new Error("invalid MCP servers");
+ return { file, data, revision: sha256Text(raw) };
+}
+export async function inspectProjectMcp(projectPath: string) {
+ const stored = await manifest(projectPath);
+ return { revision: stored.revision, servers: publicProjectMcpServers(await readProjectMcpServers(projectPath)) };
+}
+export async function manageProjectMcp(projectPath: string, input: { action: "upsert" | "delete"; server: string; revision: string; url?: string; user?: string; connection?: string }) {
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(input.server) || ["__proto__", "constructor", "prototype"].includes(input.server)) throw new Error("invalid MCP server alias");
+ return withSecurityStoreLock(path.join(projectPath, ".mcp.json"), async () => {
+ const stored = await manifest(projectPath);
+ if (stored.revision !== input.revision) throw new Error("MCP revision changed; inspect before editing");
+ const key = Object.hasOwn(stored.data, "servers") ? "servers" : "mcpServers";
+ const servers = { ...((stored.data[key] ?? {}) as Record<string, unknown>) };
+ if (input.action === "delete") delete servers[input.server];
+ else {
+ const url = normalizeMcpEndpoint(input.url ?? "");
+ let integration: { user: string; connection: string } | undefined;
+ if (input.user || input.connection) {
+ if (![input.user, input.connection].every(v => typeof v === "string" && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(v))) throw new Error("exact user and connection required");
+ integration = { user: input.user!, connection: input.connection! };
+ const values = await directConnectionValues("mcp", integration);
+ if (values.endpoint && normalizeMcpEndpoint(values.endpoint) !== url) throw new Error("MCP endpoint does not match the private connection");
+ }
+ servers[input.server] = { url, ...(integration ? { integration } : {}) };
+ }
+ if (Object.keys(servers).length > 16) throw new Error("project MCP limit is 16 servers");
+ const content = JSON.stringify({ ...stored.data, [key]: servers }, null, 2) + "\n";
+ if (Buffer.byteLength(content) > 64 * 1024) throw new Error("MCP manifest exceeds 64 KiB");
+ const result = await writeFileGuarded({ path: stored.file, content, ...(stored.revision === "new" ? {} : { expectedSha256: stored.revision }) });
+ return { action: input.action, server: input.server, revision: result.sha256, next: "project_mcp_tools discovers the server; credentials use integration_setup_open." };
+ });
+}
diff --git a/lib/host/project-mcp-result.test.ts b/lib/host/project-mcp-result.test.ts
new file mode 100644
index 00000000..24974003
--- /dev/null
+++ b/lib/host/project-mcp-result.test.ts
@@ -0,0 +1,9 @@
+import { expect, it } from "vitest";
+import { projectMcpResult } from "./project-mcp-result";
+it("preserves rich results and downstream errors without granting a canvas origin", () => {
+ const content = [{ type: "image", mimeType: "image/png", data: "aGVsbG8=" }, { type: "audio", mimeType: "audio/wav", data: "aGVsbG8=" }, { type: "resource_link", uri: "https://example.com/file", name: "file" }];
+ const result = projectMcpResult({ content, isError: true, structuredContent: { id: 1 }, _meta: { ui: { resourceUri: "ui://untrusted" } } });
+ expect(result.content).toEqual(content); expect(result.isError).toBe(true);
+ expect(result.meta).toEqual({ "mso/downstream": { ui: { resourceUri: "ui://untrusted" } } });
+ expect(() => projectMcpResult({ content: [{ type: "image" }] })).toThrow("malformed");
+});
diff --git a/lib/host/project-mcp-result.ts b/lib/host/project-mcp-result.ts
new file mode 100644
index 00000000..ab9e0a4b
--- /dev/null
+++ b/lib/host/project-mcp-result.ts
@@ -0,0 +1,17 @@
+import type { McpContent } from "@/lib/contracts/mcp-content";
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+export function projectMcpResult(raw: unknown) {
+ if (!object(raw) || !Array.isArray(raw.content)) throw new Error("downstream MCP returned an invalid CallToolResult");
+ const content = raw.content.map((block): McpContent => {
+ if (!object(block)) throw new Error("invalid downstream MCP content");
+ if (block.type === "text" && typeof block.text === "string") return block as McpContent;
+ if (["image", "audio"].includes(String(block.type)) && typeof block.data === "string" && typeof block.mimeType === "string") return block as McpContent;
+ if (block.type === "resource_link" && typeof block.uri === "string" && typeof block.name === "string") return block as McpContent;
+ if (block.type === "resource" && object(block.resource) && typeof block.resource.uri === "string" &&
+ (typeof block.resource.text === "string" || typeof block.resource.blob === "string")) return block as McpContent;
+ throw new Error("unsupported or malformed downstream MCP content");
+ });
+ return { content, isError: raw.isError === true, structuredContent: object(raw.structuredContent) ? raw.structuredContent : undefined,
+ // Downstream UI origins cannot grant themselves access to MSO's trusted canvas.
+ meta: object(raw._meta) ? { "mso/downstream": raw._meta } : undefined };
+}
diff --git a/lib/host/project-mcp-transport.ts b/lib/host/project-mcp-transport.ts
new file mode 100644
index 00000000..84d84277
--- /dev/null
+++ b/lib/host/project-mcp-transport.ts
@@ -0,0 +1,104 @@
+import { StringDecoder } from "node:string_decoder";
+import type { Rpc } from "./project-mcp-wire";
+import { withHttp } from "./project-mcp-http";
+import { projectMcpAuthorization } from "./project-mcp-auth";
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+import { childEnv } from "./child-env";
+import type { ProjectMcpServer } from "./project-mcp-config";
+
+const PROTOCOL = "2025-11-25";
+const TIMEOUT_MS = 15_000;
+const MAX_WIRE_BYTES = 2 * 1024 * 1024;
+
+import type { ProjectMcpTool } from "@/lib/contracts/project-mcp";
+
+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;
+ const decoder = new StringDecoder("utf8");
+ 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 += decoder.write(chunk);
+ 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++;
+ if (server.protocolVersion) params = { ...((params ?? {}) as object), _meta: { "io.modelcontextprotocol/protocolVersion": server.protocolVersion, "io.modelcontextprotocol/clientCapabilities": {} } };
+ 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 {
+ if (server.protocolVersion) {
+ const discovery = await rpc("server/discover", {});
+ const err = rpcError(discovery); if (err) throw err;
+ if ((discovery.result as { resultType?: string })?.resultType !== "complete") throw new Error("modern MCP discovery requires complete resultType");
+ } else {
+ 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(async (method, params) => {
+ const row = await rpc(method, params), error = rpcError(row); if (error) throw error;
+ if (server.protocolVersion && (row.result as { resultType?: string })?.resultType !== "complete") throw new Error("modern MCP requires complete resultType; input_required is unsupported");
+ return row;
+ }, notify); finish(undefined, value);
+ } catch (e) { finish(e instanceof Error ? e : new Error(String(e))); }
+ })();
+ });
+}
+
+export async function withProjectMcpServer<T>(server: ProjectMcpServer, work: (rpc: (method: string, params?: unknown) => Promise<Rpc>) => Promise<T>): Promise<T> {
+ const auth = await projectMcpAuthorization(server);
+ const guarded = async (rpc: (method: string, params?: unknown) => Promise<Rpc>) => work(async (method, params) => {
+ if (method === "tools/call" && auth.allowed && !auth.allowed.includes(String((params as { name?: string })?.name))) throw new Error("project MCP tool is not allowed by this connection");
+ // Re-resolve at each RPC: removing or changing the named connection takes effect now.
+ const current = await projectMcpAuthorization(server);
+ if (JSON.stringify(current.server.headers) !== JSON.stringify(auth.server.headers) || JSON.stringify(current.allowed) !== JSON.stringify(auth.allowed)) throw new Error("project MCP connection changed; rediscover before continuing");
+ const row = auth.redact(await rpc(method, params)) as Rpc;
+ if (method === "tools/list" && auth.allowed && row.result && typeof row.result === "object") {
+ const result = row.result as { tools?: ProjectMcpTool[] };
+ if (Array.isArray(result.tools)) result.tools = result.tools.filter((tool) => auth.allowed!.includes(tool.name));
+ }
+ return row;
+ });
+ try { return await (auth.server.transport === "stdio" ? withStdio(auth.server, (rpc) => guarded(rpc)) : withHttp(auth.server, guarded)); }
+ catch (error) { throw new Error(String(auth.redact(error instanceof Error ? error.message : "project MCP request failed"))); }
+}
diff --git a/lib/host/project-mcp-wire.test.ts b/lib/host/project-mcp-wire.test.ts
new file mode 100644
index 00000000..1ea9302b
--- /dev/null
+++ b/lib/host/project-mcp-wire.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import { readMcpResponse } from "./project-mcp-wire";
+
+describe("MCP HTTP framing", () => {
+ it("handles split UTF-8, CRLF, notifications, unrelated IDs and an open SSE stream", async () => {
+ const body = new TextEncoder().encode('data: {"jsonrpc":"2.0","method":"notifications/progress"}\r\n\r\ndata: {"id":2,"result":{}}\r\n\r\ndata: {"id":3,"result":{"text":"😀"}}\r\n\r\n');
+ let offset = 0, cancelled = false;
+ const stream = new ReadableStream<Uint8Array>({
+ pull(controller) { if (offset < body.length) controller.enqueue(body.slice(offset, ++offset)); },
+ cancel() { cancelled = true; },
+ });
+ expect(await readMcpResponse(new Response(stream, { headers: { "content-type": "text/event-stream" } }), 3)).toEqual({ id: 3, result: { text: "😀" } });
+ expect(cancelled).toBe(true);
+ });
+ it("rejects mismatched IDs and excessive responses", async () => {
+ await expect(readMcpResponse(new Response('{"id":2,"result":{}}'), 1)).rejects.toThrow("id mismatch");
+ await expect(readMcpResponse(new Response("x".repeat(2 * 1024 * 1024 + 1)), 1)).rejects.toThrow("exceeded limit");
+ });
+});
diff --git a/lib/host/project-mcp-wire.ts b/lib/host/project-mcp-wire.ts
new file mode 100644
index 00000000..c71129f6
--- /dev/null
+++ b/lib/host/project-mcp-wire.ts
@@ -0,0 +1,46 @@
+// Bounded JSON/SSE framing shared by project HTTP MCP calls.
+export type Rpc = { jsonrpc?: string; id?: string | number | null; result?: unknown; error?: { code?: number; message?: string } };
+const MAX_WIRE_BYTES = 2 * 1024 * 1024;
+
+function eventMessage(block: string): Rpc | undefined {
+ const data = block.split(/\r\n|\r|\n/).filter(line => line.startsWith("data:"))
+ .map(line => line.slice(5).replace(/^ /, "")).join("\n");
+ return data ? JSON.parse(data) as Rpc : undefined;
+}
+
+/** Stop as soon as our response arrives; an SSE connection need not close. */
+export async function readMcpResponse(response: Response, expectedId?: string | number): Promise<Rpc> {
+ if (!response.body) return {};
+ const sse = (response.headers.get("content-type") ?? "").includes("text/event-stream");
+ const reader = response.body.getReader(), decoder = new TextDecoder();
+ let bytes = 0, buffer = "";
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (value) {
+ bytes += value.byteLength;
+ if (bytes > MAX_WIRE_BYTES) throw new Error("project MCP HTTP response exceeded limit");
+ buffer += decoder.decode(value, { stream: true });
+ }
+ if (done) buffer += decoder.decode();
+ if (sse) {
+ let separator: RegExpExecArray | null;
+ while ((separator = /\r\n\r\n|\n\n|\r\r/.exec(buffer))) {
+ const block = buffer.slice(0, separator.index);
+ buffer = buffer.slice(separator.index + separator[0].length);
+ const message = eventMessage(block);
+ if (message && expectedId !== undefined && message.id === expectedId) return message;
+ }
+ }
+ if (!done) continue;
+ if (sse) throw new Error("project MCP SSE response contained no matching JSON-RPC result");
+ if (!buffer.trim() && expectedId === undefined) return {};
+ const message = JSON.parse(buffer) as Rpc;
+ if (expectedId !== undefined && message.id !== expectedId) throw new Error("project MCP response id mismatch");
+ return message;
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ reader.releaseLock();
+ }
+}
diff --git a/lib/host/projects-api.ts b/lib/host/projects-api.ts
index 5d4825a2..e6cdd73f 100644
--- a/lib/host/projects-api.ts
+++ b/lib/host/projects-api.ts
@@ -1,6 +1,6 @@
export { resolveProjectHint, inspectProject } from "./projects";
export type { ProjectResolution } from "./projects";
-export { projectCapabilities, runProjectFunction, readProjectMcpServers, publicProjectMcpServers, listProjectMcpTools, callProjectMcpTool } from "./project-capabilities";
+export { projectCapabilities, runProjectFunction, readProjectMcpServers, publicProjectMcpServers, listProjectMcpTools, listProjectMcpToolPage, callProjectMcpTool } from "./project-capabilities";
export type { ProjectCapabilities, PublicProjectFunction } from "./project-capabilities";
export { projectGitSnapshot, projectGitEdits, projectGitDiff, readProjectKnowledge, detectProjectConvex, PROJECT_KNOWLEDGE_REL, PROJECT_KNOWLEDGE_MAX_BYTES } from "./project-experience";
export { listProjectConvexTools, callProjectConvexTool, PROJECT_CONVEX_READ_TOOLS, PROJECT_CONVEX_WRITE_TOOLS } from "./project-convex";
diff --git a/lib/infra/clients.test.ts b/lib/infra/clients.test.ts
index 036415b7..525af341 100644
--- a/lib/infra/clients.test.ts
+++ b/lib/infra/clients.test.ts
@@ -74,12 +74,13 @@ describe("infrastructure clients", () => {
throw new Error(`unexpected ${method} ${url}`);
}));
const client = await import("./clients");
- const result = await client.upsertHostingerDns({ name: "app.example.com", type: "A", content: "203.0.113.7" });
+ const result = await client.upsertHostingerDns({ name: "app.example.com", type: "A", content: "203.0.113.1", ttl: 300 });
expect(result.action).toBe("updated");
const payload = putBody as { overwrite: boolean; zone: Array<{ name: string; type: string; records: Array<{ content: string }> }> };
expect(payload.overwrite).toBe(true);
expect(payload.zone).toHaveLength(1);
expect(payload.zone[0]).toMatchObject({ name: "app", type: "A" });
- expect(payload.zone[0].records[0].content).toBe("203.0.113.7");
+ expect(payload.zone[0].records[0].content).toBe("203.0.113.1");
+ expect((payload.zone[0] as unknown as { ttl: number }).ttl).toBe(300);
});
});
diff --git a/lib/infra/cloudflare.ts b/lib/infra/cloudflare.ts
index a3b8269c..02aac94b 100644
--- a/lib/infra/cloudflare.ts
+++ b/lib/infra/cloudflare.ts
@@ -1,6 +1,7 @@
+import { isIP } from "node:net";
import type { InfraProviderValues } from "./types";
import { readInfraProvider } from "./store";
-import { HOST_RE, IPV4_RE, obj, request } from "./http";
+import { HOST_RE, obj, request } from "./http";
const API = "https://api.cloudflare.com/client/v4";
const MAX_PAGE = 20;
@@ -53,8 +54,8 @@ async function zoneFor(fqdn: string): Promise<{ id: string; name: string; token:
function validateDns(name: string, type: string, content: string): void {
if (!HOST_RE.test(name)) throw new Error("invalid DNS hostname");
if (!["A", "AAAA", "CNAME", "TXT"].includes(type)) throw new Error("DNS type must be A, AAAA, CNAME, or TXT");
- if (type === "A" && !IPV4_RE.test(content)) throw new Error("A record content must be an IPv4 address");
- if (type === "AAAA" && (!content.includes(":") || !/^[0-9a-f:]+$/i.test(content))) throw new Error("AAAA record content must be an IPv6 address");
+ if (type === "A" && isIP(content) !== 4) throw new Error("A record content must be an IPv4 address");
+ if (type === "AAAA" && isIP(content) !== 6) throw new Error("AAAA record content must be an IPv6 address");
if (type === "CNAME" && !HOST_RE.test(content.replace(/\.$/, ""))) throw new Error("CNAME content must be a hostname");
}
@@ -63,6 +64,7 @@ export async function upsertCloudflareDns(input: { name: string; type: string; c
const type = input.type.trim().toUpperCase();
const content = input.content.trim();
validateDns(name, type, content);
+ if (input.ttl !== undefined && (!Number.isInteger(input.ttl) || input.ttl !== 1 && (input.ttl < 60 || input.ttl > 86400))) throw new Error("Cloudflare TTL must be 1 (auto) or 60-86400");
const zone = await zoneFor(name);
const base = `${API}/zones/${encodeURIComponent(zone.id)}/dns_records`;
const find = await request(`${base}?type=${encodeURIComponent(type)}&name.exact=${encodeURIComponent(name)}`, { headers: headers(zone.token) });
@@ -71,11 +73,11 @@ export async function upsertCloudflareDns(input: { name: string; type: string; c
const exact = found.result.map(obj).filter((r) => String(r.name ?? "").toLowerCase() === name && String(r.type ?? "").toUpperCase() === type);
if (exact.length > 1) throw new Error(`refusing ambiguous DNS change: ${exact.length} ${type} records already exist for ${name}`);
const proxied = ["A", "AAAA", "CNAME"].includes(type) ? input.proxied === true : undefined;
- const payload = { type, name, content, ttl: input.ttl && input.ttl >= 60 ? input.ttl : 1, ...(proxied === undefined ? {} : { proxied }) };
+ const payload = { type, name, content, ttl: proxied ? 1 : input.ttl ?? 1, ...(proxied === undefined ? {} : { proxied }) };
if (exact.length === 1) {
const current = exact[0];
const same = String(current.content ?? "").replace(/\.$/, "") === content.replace(/\.$/, "") && (proxied === undefined || Boolean(current.proxied) === proxied);
- if (same) return { action: "unchanged", id: String(current.id), name, type };
+ if (same && (input.ttl === undefined || Number(current.ttl) === payload.ttl)) return { action: "unchanged", id: String(current.id), name, type };
const id = String(current.id ?? "");
if (!id) throw new Error("Cloudflare returned a DNS record without an id");
const changed = await request(`${base}/${encodeURIComponent(id)}`, { method: "PATCH", headers: headers(zone.token), body: JSON.stringify(payload) });
diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.ts
index 3ce94abb..f4066e4d 100644
--- a/lib/infra/connection-ui.ts
+++ b/lib/infra/connection-ui.ts
@@ -1,6 +1,7 @@
+import { PROJECT_MCP_UI_SCRIPT } from "./project-mcp-ui";
export { CONNECTION_MANAGER_STYLE } from "./connection-ui-style";
import { PROVIDER_ICON_PATHS } from "./provider-icons";
-export const CONNECTION_MANAGER_SCRIPT=`const PROVIDER_ICON_PATHS=${JSON.stringify(PROVIDER_ICON_PATHS)};`+String.raw`
+export const CONNECTION_MANAGER_SCRIPT=PROJECT_MCP_UI_SCRIPT+`const PROVIDER_ICON_PATHS=${JSON.stringify(PROVIDER_ICON_PATHS)};`+String.raw`
function mountConnectionManager(root,catalog,bridge,initial={}){
let disposed=false,sequence=0,snapshot=initial.snapshot||{users:[],connections:[],bindings:[]},user=initial.user||snapshot.user||null,provider=catalog.find(p=>p.id===initial.provider)||catalog.find(p=>p.id==="github")||catalog[0];
let detail,status,container;
@@ -30,7 +31,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
function draw(){
root.replaceChildren();root.classList.add("integration","manager");
const heading=n("header",undefined,"identity-heading"),title=n("div");title.append(n(bridge.headingLevel===1?"h1":"h2","Integrations"),n("p","Connect your services. Choose the account each project uses."));heading.append(title,n("span",catalog.length+" services","identity-count"));root.append(heading);
- const toolbar=n("div",undefined,"identity-bar"),owner=choicePicker("Credential owner",snapshot.users.map(row=>({id:row.id,text:row.label+" · "+row.id+(row.isDefault?" · default":"")})),user,row=>{user=row.id;remember();void reload()});toolbar.append(owner.wrap,b("Refresh",reload));const workbench=n("div",undefined,"identity-actions identity-workbench");const usersAction=b("Users",profiles),routingAction=b("Routing",bindings);usersAction.disabled=routingAction.disabled=!bridge.manage;workbench.append(usersAction,routingAction);const transfer=b("Transfer",()=>bridge.openTransfer?bridge.openTransfer():bridge.openTransferBrowser?.());transfer.disabled=!bridge.openTransfer&&!bridge.openTransferBrowser;workbench.append(transfer);toolbar.append(workbench);root.append(toolbar);
+ const toolbar=n("div",undefined,"identity-bar"),owner=choicePicker("Credential owner",snapshot.users.map(row=>({id:row.id,text:row.label+" · "+row.id+(row.isDefault?" · default":"")})),user,row=>{user=row.id;remember();void reload()});toolbar.append(owner.wrap,b("Refresh",reload));const workbench=n("div",undefined,"identity-actions identity-workbench");const usersAction=b("Users",profiles),routingAction=b("Routing",bindings);usersAction.disabled=routingAction.disabled=!bridge.manage;workbench.append(usersAction,routingAction);const transfer=b("Transfer",()=>bridge.openTransfer?bridge.openTransfer():bridge.openTransferBrowser?.());transfer.disabled=!bridge.openTransfer&&!bridge.openTransferBrowser;workbench.append(transfer);const addMcp=b("Add MCP",()=>mountProjectMcpForm(detail,bridge,snapshot,user,status,drawProvider,{n,b,input}),"primary");addMcp.disabled=!bridge.projectMcp;workbench.append(addMcp);toolbar.append(workbench);root.append(toolbar);
if(!bridge.manage)root.append(n("p","Sign in as an MSO Owner to manage credentials. Device roles and credential users are different; the public guides remain available.","identity-readonly"));
if(snapshot.connections.length){
const summary=n("section",undefined,"identity-summary"),count=snapshot.connections.filter(ready).length,ring=n("div",undefined,"identity-ring");
diff --git a/lib/infra/hostinger.ts b/lib/infra/hostinger.ts
index 0185dbbc..7a407d81 100644
--- a/lib/infra/hostinger.ts
+++ b/lib/infra/hostinger.ts
@@ -1,6 +1,7 @@
+import { isIP } from "node:net";
import type { InfraProviderValues } from "./types";
import { readInfraProvider } from "./store";
-import { HOST_RE, IPV4_RE, obj, request } from "./http";
+import { HOST_RE, obj, request } from "./http";
import { doctorHostingerMail } from "./hostinger-mail";
const API = "https://developers.hostinger.com/api";
@@ -35,8 +36,9 @@ export async function upsertHostingerDns(input: { name: string; type: string; co
const type = input.type.trim().toUpperCase(); const content = input.content.trim();
if (!HOST_RE.test(fullDomain)) throw new Error("invalid DNS hostname");
if (!["A", "CNAME", "TXT"].includes(type)) throw new Error("Hostinger DNS type must be A, CNAME, or TXT");
- if (type === "A" && !IPV4_RE.test(content)) throw new Error("A record content must be an IPv4 address");
+ if (type === "A" && isIP(content) !== 4) throw new Error("A record content must be an IPv4 address");
if (type === "CNAME" && !HOST_RE.test(content.replace(/\.$/, ""))) throw new Error("CNAME content must be a hostname");
+ if (input.ttl !== undefined && (!Number.isInteger(input.ttl) || input.ttl < 60 || input.ttl > 2147483647)) throw new Error("Hostinger TTL must be an integer from 60 to 2147483647");
const { root, name } = await rootFor(fullDomain, values.apiToken);
const url = `${API}/dns/v1/zones/${encodeURIComponent(root)}`;
const auth = headers(values.apiToken);
@@ -50,7 +52,7 @@ export async function upsertHostingerDns(input: { name: string; type: string; co
const normalized = content.replace(/\.$/, "");
if (exact.length === 1) {
const targets = Array.isArray(exact[0].records) ? exact[0].records.map(obj).map((r) => String(r.content ?? "").replace(/\.$/, "")) : [];
- if (targets.length === 1 && targets[0] === normalized) return { action: "unchanged", name: fullDomain, type };
+ if (targets.length === 1 && targets[0] === normalized && (input.ttl === undefined || Number(exact[0].ttl) === input.ttl)) return { action: "unchanged", name: fullDomain, type };
}
const record = { name, type, ttl: input.ttl && input.ttl >= 60 ? input.ttl : 14400, records: [{ content, is_disabled: false }] };
// Hostinger's overwrite flag replaces only RRsets matching the supplied name+type.
diff --git a/lib/infra/project-mcp-ui.ts b/lib/infra/project-mcp-ui.ts
new file mode 100644
index 00000000..239a2c48
--- /dev/null
+++ b/lib/infra/project-mcp-ui.ts
@@ -0,0 +1,22 @@
+/** Shared native/embedded Add MCP form; credentials only enter the existing private setup form. */
+export const PROJECT_MCP_UI_SCRIPT = String.raw`
+function mountProjectMcpForm(detail,bridge,snapshot,user,status,back,helpers){
+ const {n,b,input}=helpers,project=input("Project id or path"),alias=input("Server alias"),url=input("HTTPS MCP endpoint");
+ project.input.maxLength=url.input.maxLength=4096;alias.input.maxLength=64;url.input.type="url";
+ const label=n("label","Private connection"),select=n("select");select.setAttribute("aria-label","Private connection");
+ const publicOption=n("option","Public MCP (no credentials)");publicOption.value="";select.append(publicOption);
+ for(const row of snapshot.connections.filter(c=>c.provider==="mcp"&&c.user===user&&c.source==="direct")){const option=n("option",row.label+" · "+row.id);option.value=row.id;select.append(option)}
+ label.append(select);detail.replaceChildren(n("h2","Add MCP to project"),n("p","Choose the project and endpoint. A private connection keeps credentials out of project files."),project.label,alias.label,url.label,label);
+ const save=b("Add MCP",async()=>{
+ save.disabled=true;
+ try{
+ if(!project.input.value.trim()||!alias.input.value.trim()||!url.input.value.trim())throw new Error("Project, alias and endpoint are required.");
+ const p=project.input.value.trim(),current=await bridge.projectMcp({action:"inspect",project:p});
+ if(current.servers.some(s=>s.name===alias.input.value.trim()))throw new Error("This alias already exists. Choose a new alias or edit its binding with project_mcp_manage.");
+ const result=await bridge.projectMcp({action:"upsert",project:p,server:alias.input.value.trim(),url:url.input.value.trim(),revision:current.revision,...(select.value?{user,connection:select.value}:{})});
+ status.textContent="MCP added to "+result.project+". Discover its tools with project_mcp_tools.";back();
+ }catch(e){status.textContent=e.message||"Could not add MCP."}finally{save.disabled=false}
+ },"primary");
+ detail.append(save,b("Cancel",back));project.input.focus();
+}
+`;
diff --git a/lib/infra/setup-browser.ts b/lib/infra/setup-browser.ts
index 1515e637..f4f0202c 100644
--- a/lib/infra/setup-browser.ts
+++ b/lib/infra/setup-browser.ts
@@ -15,6 +15,7 @@ export const INTEGRATION_BROWSER_SCRIPT=String.raw`
const bridge={headingLevel:1,remember:s=>state=s,openLink:url=>window.open(url,"_blank","noopener,noreferrer")};
if(owner){
bridge.openTransfer=openTransfer;
+ bridge.projectMcp=args=>json("/api/v1/project-mcp",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(args)});
bridge.query=args=>json("/api/v1/integrations?"+new URLSearchParams(args));
bridge.manage=args=>post("manage",args);bridge.execute=args=>post("execute",args);
bridge.openSetup=async args=>{const data=await json("/api/v1/infra/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(args)});showForm(data.setup,data.token)};
diff --git a/lib/mcp/client-budgets.test.ts b/lib/mcp/client-budgets.test.ts
new file mode 100644
index 00000000..31f57a79
--- /dev/null
+++ b/lib/mcp/client-budgets.test.ts
@@ -0,0 +1,20 @@
+import { expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+const { TOOLS } = await import("./tools");
+const { toolDescriptor } = await import("./tool-contract");
+it("checks published metadata limits separately from MSO's byte policy without inventing token limits", () => {
+ // Official OpenAI plugin reference: invocation status strings <=64 characters.
+ // MCP tool names SHOULD be <=128; MSO also meets OpenAI function-name <=64.
+ for (const tool of TOOLS) {
+ expect(tool.name.length, tool.name).toBeLessThanOrEqual(64);
+ expect(tool.name, tool.name).toMatch(/^[A-Za-z0-9_-]+$/);
+ for (const key of ["openai/toolInvocation/invoking", "openai/toolInvocation/invoked"]) {
+ const value = tool.meta?.[key];
+ if (value !== undefined) expect([...String(value)].length, tool.name + "." + key).toBeLessThanOrEqual(64);
+ }
+ }
+ const descriptors = TOOLS.map(tool => toolDescriptor(tool, "chatgpt"));
+ // Internal project budgets, NOT an OpenAI/MCP token guarantee.
+ expect(Buffer.byteLength(JSON.stringify(descriptors))).toBeLessThan(96 * 1024);
+ expect(Math.max(...descriptors.map(d => Buffer.byteLength(JSON.stringify(d))))).toBeLessThan(8 * 1024);
+});
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
index 9d095c72..e65100cb 100644
--- a/lib/mcp/dispatch.ts
+++ b/lib/mcp/dispatch.ts
@@ -5,7 +5,7 @@ import { listUiResources, readUiResource } from "./ui-resources";
import { MCP_SKILLS_EXTENSION, getMcpSkill, listMcpSkills, readMcpSkillResource } from "./skills-extension";
import { dispatchToolCall } from "./dispatch-tools";
import { toolDescriptor, visibleToolsForProfile, type McpToolProfile } from "./tool-contract";
-import { negotiateMcpProtocol } from "./protocol";
+import { MCP_PROTOCOL_LATEST, MCP_PROTOCOLS, negotiateMcpProtocol } from "./protocol";
import { rpcFail, rpcOk, type McpAgentContext, type RpcRequest } from "./dispatch-types";
export type { McpAgentContext, RpcRequest } from "./dispatch-types";
@@ -30,12 +30,20 @@ function instructions(scope: Scope, profile: McpToolProfile = "full", allowedToo
? "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.";
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.`;
+ return `${startup}${projectBoundary} Call agent_session_open for provider-neutral sessions, then send params._meta[mso/sessionId]. Use flow_catalog to inspect required inputs before flow_run; flow_status waits for completion. 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>> {
const id = req.id ?? null;
+ const modern = req.params?._meta?.["io.modelcontextprotocol/protocolVersion"] === MCP_PROTOCOL_LATEST;
+ if (modern && (req.method === "initialize" || req.method === "notifications/initialized")) return rpcFail(id, -32601, "initialize is only supported in the legacy MCP era");
switch (req.method) {
+ case "server/discover":
+ if (!modern) return rpcFail(id, -32601, "server/discover requires modern per-request metadata");
+ return rpcOk(id, { resultType: "complete", supportedVersions: [...MCP_PROTOCOLS], capabilities: { tools: {}, resources: {} },
+ _meta: { "io.modelcontextprotocol/serverInfo": { name: "mso", version: MCP_SERVER_VERSION } },
+ instructions: instructions(scope, agentContext?.toolProfile, agentContext?.allowedTools), ttlMs: 30_000, cacheScope: "private" });
+
case "initialize": {
const profile = agentContext?.toolProfile ?? "full";
const allowedTools = agentContext?.allowedTools;
diff --git a/lib/mcp/modern-http.test.ts b/lib/mcp/modern-http.test.ts
new file mode 100644
index 00000000..fa2c9cb3
--- /dev/null
+++ b/lib/mcp/modern-http.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { validateMcpRequest, modernMcpResult, decodeMcpHeader } from "./modern-http";
+const meta = { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {} };
+const req = (extra = {}) => new Request("https://mso.test/mcp", { method: "POST", headers: { "MCP-Protocol-Version": "2026-07-28", "Mcp-Method": "tools/call", "Mcp-Name": "weather", ...extra } });
+const body = { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "weather", _meta: meta } };
+describe("modern MCP HTTP", () => {
+ it("validates each independent request, header equality and required capabilities", () => {
+ expect(validateMcpRequest(req(), body)).toEqual({ modern: true });
+ expect(validateMcpRequest(req({ "Mcp-Name": "other" }), body).error).toMatchObject({ error: { code: -32020 } });
+ expect(validateMcpRequest(req(), { ...body, params: { name: "weather", _meta: {} } }).error).toMatchObject({ error: { code: -32602 } });
+ expect(validateMcpRequest(req({ "MCP-Protocol-Version": "2099-01-01" }), body).error).toMatchObject({ error: { code: -32022, data: { requested: "2099-01-01" } } });
+ expect(validateMcpRequest(new Request("https://mso.test/mcp"), {...body, params: {_meta: {...meta, "io.modelcontextprotocol/protocolVersion":"2099-01-01"}}}).error).toMatchObject({error:{code:-32022}});
+ for (const invalid of [null, [], "tools/list", { method: "tools/list", params: [] }]) expect(validateMcpRequest(req(), invalid).error).toBeDefined();
+ });
+ it("decodes sentinels and decorates only result envelopes", () => {
+ expect(decodeMcpHeader("=?base64?" + Buffer.from(" hello 世界 ").toString("base64") + "?=")).toBe(" hello 世界 ");
+ expect(decodeMcpHeader("=?base64?bad!?=")).toBeNull();
+ expect(modernMcpResult({ result: { content: [] } }, "1").result).toMatchObject({ resultType: "complete" });
+ expect(modernMcpResult({ error: { code: -32601 } }, "1")).toEqual({ error: { code: -32601 } });
+ });
+});
diff --git a/lib/mcp/modern-http.ts b/lib/mcp/modern-http.ts
new file mode 100644
index 00000000..117712da
--- /dev/null
+++ b/lib/mcp/modern-http.ts
@@ -0,0 +1,33 @@
+import { MCP_PROTOCOL_LATEST, MCP_PROTOCOLS } from "./protocol";
+import type { RpcRequest } from "./dispatch-types";
+const VERSION = "io.modelcontextprotocol/protocolVersion";
+const CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
+const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+export function decodeMcpHeader(value: string | null): string | null {
+ if (value === null || !value.startsWith("=?base64?") || !value.endsWith("?=")) return value;
+ const data = value.slice(9, -2);
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) return null;
+ try { return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(data, "base64")); } catch { return null; }
+}
+export function validateMcpRequest(req: Request, body: unknown): { modern: boolean; error?: Record<string, unknown> } {
+ const rpc = object(body) ? body as RpcRequest : {};
+ const fail = (code: number, message: string, data?: unknown) => ({ modern: false, error: { jsonrpc: "2.0", id: rpc.id ?? null, error: { code, message, ...(data ? { data } : {}) } } });
+ if (!object(body) || (rpc.jsonrpc !== undefined && rpc.jsonrpc !== "2.0") || typeof rpc.method !== "string" || !rpc.method ||
+ rpc.params !== undefined && !object(rpc.params) || rpc.id !== undefined && rpc.id !== null && !["number", "string"].includes(typeof rpc.id)) return fail(-32600, "invalid JSON-RPC request");
+ if (rpc.method === "tools/call" && rpc.params?.arguments !== undefined && !object(rpc.params.arguments)) return fail(-32602, "tool arguments must be an object");
+ const header = req.headers.get("MCP-Protocol-Version"), meta = rpc.params?._meta;
+ const version = object(meta) ? meta[VERSION] : undefined;
+ const modern = header === MCP_PROTOCOL_LATEST || version === MCP_PROTOCOL_LATEST;
+ if (header && !(MCP_PROTOCOLS as readonly string[]).includes(header) && rpc.method !== "initialize") return fail(-32022, "unsupported MCP protocol version", { supported: [...MCP_PROTOCOLS], requested: header });
+ if (version !== undefined && !(MCP_PROTOCOLS as readonly unknown[]).includes(version)) return fail(-32022, "unsupported MCP protocol version", { supported: [...MCP_PROTOCOLS], requested: version });
+ if (!modern) return { modern: false };
+ if (rpc.jsonrpc !== "2.0" || typeof version !== "string" || !object(meta?.[CAPABILITIES])) return fail(-32602, "modern requests require protocolVersion and clientCapabilities in params._meta");
+ if (version !== header || req.headers.get("Mcp-Method") !== rpc.method) return fail(-32020, "MCP protocol/method header does not match the request body");
+ const name = rpc.method === "resources/read" ? rpc.params?.uri : ["tools/call", "prompts/get"].includes(rpc.method) ? rpc.params?.name : undefined;
+ if (["tools/call", "resources/read", "prompts/get"].includes(rpc.method) && (typeof name !== "string" || decodeMcpHeader(req.headers.get("Mcp-Name")) !== name)) return fail(-32020, "Mcp-Name header does not match the request body");
+ return { modern: true };
+}
+export function modernMcpResult(value: Record<string, unknown>, serverVersion: string) {
+ if (!object(value.result)) return value;
+ return { ...value, result: { ...value.result, resultType: "complete", _meta: { ...(object(value.result._meta) ? value.result._meta : {}), "io.modelcontextprotocol/serverInfo": { name: "mso", version: serverVersion } } } };
+}
diff --git a/lib/mcp/origin.ts b/lib/mcp/origin.ts
index 81794dde..6635066b 100644
--- a/lib/mcp/origin.ts
+++ b/lib/mcp/origin.ts
@@ -92,7 +92,7 @@ export function mcpCorsHeaders(req: Request): Record<string, string> {
return {
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
- "Access-Control-Allow-Headers": "Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version, Mcp-Method, Mcp-Name",
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, Mso-Session-Id, Mcp-Session-Id, MCP-Protocol-Version, Mcp-Method, Mcp-Name",
"Access-Control-Expose-Headers": "Mcp-Session-Id, WWW-Authenticate",
"Access-Control-Max-Age": "86400",
Vary: "Origin",
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 57a8d1e8..9a23179d 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -21,6 +21,13 @@ const ALFA_ONLY: Record<string, string> = {
};
const MCP_ONLY: Record<string, string> = {
+ "flow.catalog": "Project API/MCP automation belongs to the external/CLI session context; Alfa has its own browser workflow identity.",
+ "flow.run": "Provider mutations require the durable external principal, exact connection, and idempotency receipt; owner CLI shares this executor.",
+ "flow.status": "Flow receipts belong to their authenticated external/CLI principal; Alfa must not inherit that principal.",
+ "flow.manage": "Project-local automation definitions configure the external/CLI executor, not an Alfa browser thread.",
+ "agent.session.open": "Provider-neutral bootstrap for the external durable session store; Alfa already owns a separate browser thread.",
+ "project.mcp.manage": "External MCP and native owner Integrations share project binding CRUD; Alfa delegates to that owner surface.",
+ "project.asset.attach": "Source artifacts are owned by a durable external/CLI session and cannot be claimed by Alfa's browser identity.",
"integration.query":"Native credential profiles are managed by owner browser/CLI and external agents; Alfa has no independent credential-owner identity and must not invent one",
"integration.manage":"Same credential-owner boundary; browser and CLI use the shared native action service with confirmation rather than duplicating it in Alfa",
"integration.execute":"External deployment agents require explicit account selection; the native owner UI/CLI share the executor without exposing keys to Alfa",
@@ -157,6 +164,7 @@ describe("MCP rate limits mirror the routes", () => {
"fs.delete": 60, "fs.upload": 20, "exec": 60, "managed-app": 12, "camoufox": 12,
};
const MCP_NATIVE_LIMITS: Record<string, number> = {
+ "flow.run": 20, "flow.manage": 20, "agent.session.open": 20, "project.mcp.manage": 20, "project.asset.attach": 20,
// Native capabilities have independent bounded buckets (no matching HTTP route).
"screen.capture": 10,
"session.artifacts": 60,
diff --git a/lib/mcp/protocol.test.ts b/lib/mcp/protocol.test.ts
index 81efa0cb..38515830 100644
--- a/lib/mcp/protocol.test.ts
+++ b/lib/mcp/protocol.test.ts
@@ -2,10 +2,10 @@ import { describe, expect, it } from "vitest";
import { MCP_PROTOCOL_LATEST, MCP_PROTOCOLS, negotiateMcpProtocol, supportedMcpProtocol } from "./protocol";
describe("MCP protocol era", () => {
- it("advertises only initialize-capable revisions", () => {
- expect(MCP_PROTOCOL_LATEST).toBe("2025-06-18");
- expect(MCP_PROTOCOLS).toEqual(["2025-06-18", "2025-03-26", "2024-11-05"]);
- expect(supportedMcpProtocol("2026-07-28")).toBe(false);
+ it("advertises both eras without counter-offering modern initialize", () => {
+ expect(MCP_PROTOCOL_LATEST).toBe("2026-07-28");
+ expect(MCP_PROTOCOLS).toEqual(["2026-07-28", "2025-06-18", "2025-03-26", "2024-11-05"]);
+ expect(supportedMcpProtocol("2026-07-28")).toBe(true);
});
it("never counter-offers the stateless revision from initialize", () => {
diff --git a/lib/mcp/protocol.ts b/lib/mcp/protocol.ts
index a03cb075..541af705 100644
--- a/lib/mcp/protocol.ts
+++ b/lib/mcp/protocol.ts
@@ -1,13 +1,9 @@
-// MSO currently serves the initialize/session-era MCP wire contract.
-// Do not advertise the 2026-07-28 stateless era until server/discover,
-// per-request metadata and modern Streamable HTTP headers are implemented as
-// one coherent transport. A modern HTTP client can probe 2026-07-28, receive
-// an explicit 400 from app/mcp/route.ts, then fall back to this legacy ceiling.
-export const MCP_PROTOCOL_LATEST = "2025-06-18";
-export const MCP_PROTOCOLS = [MCP_PROTOCOL_LATEST, "2025-03-26", "2024-11-05"] as const;
-
+// Both wire eras share capabilities; initialize never negotiates a stateless version.
+export const MCP_PROTOCOL_LATEST = "2026-07-28";
+export const MCP_LEGACY_LATEST = "2025-06-18";
+export const MCP_PROTOCOLS = [MCP_PROTOCOL_LATEST, MCP_LEGACY_LATEST, "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;
+ return requested && requested !== MCP_PROTOCOL_LATEST && (MCP_PROTOCOLS as readonly string[]).includes(requested) ? requested : MCP_LEGACY_LATEST;
}
export function supportedMcpProtocol(value: string): boolean {
return (MCP_PROTOCOLS as readonly string[]).includes(value);
diff --git a/lib/mcp/session-context.test.ts b/lib/mcp/session-context.test.ts
index 486e0ef2..e59639b4 100644
--- a/lib/mcp/session-context.test.ts
+++ b/lib/mcp/session-context.test.ts
@@ -1,10 +1,10 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
- findOrCreate: vi.fn(),
+ findOrCreate: vi.fn(), get: vi.fn(),
newId: vi.fn(() => "20260901_120000_11223344"),
}));
-vi.mock("@/lib/agent/session-store", () => ({ findOrCreateAgentSessionForConversation: mocks.findOrCreate }));
+vi.mock("@/lib/agent/session-store", () => ({ findOrCreateAgentSessionForConversation: mocks.findOrCreate, getAgentSession: mocks.get }));
vi.mock("@/lib/agent/session-files", () => ({ newAgentSessionId: mocks.newId }));
const { resolveMcpSession } = await import("./session-context");
@@ -58,3 +58,13 @@ describe("MCP conversation/session correlation", () => {
expect(mocks.findOrCreate).not.toHaveBeenCalled();
});
});
+
+it("bootstraps without transport state and rejects a foreign explicit application session", async () => {
+ const bare = new Request("https://mso.test/mcp");
+ expect(await resolveMcpSession(bare, { method: "tools/call", params: { name: "agent_session_open" } }, "mcp-client:x", "")).toMatchObject({ conversationBound: false });
+ mocks.get.mockResolvedValueOnce(null);
+ const denied = await resolveMcpSession(bare, { method: "tools/call", params: { name: "sys_stats", _meta: { "mso/sessionId": "foreign" } } }, "mcp-client:x", "");
+ expect("response" in denied && denied.response.status).toBe(403);
+ mocks.get.mockResolvedValueOnce({ id: "owned" });
+ expect(await resolveMcpSession(bare, { method: "tools/call", params: { name: "sys_stats", _meta: { "mso/sessionId": "owned" } } }, "mcp-client:x", "")).toMatchObject({ agentSessionId: "owned" });
+});
diff --git a/lib/mcp/session-context.ts b/lib/mcp/session-context.ts
index 973214f9..754ef98a 100644
--- a/lib/mcp/session-context.ts
+++ b/lib/mcp/session-context.ts
@@ -1,4 +1,4 @@
-import { findOrCreateAgentSessionForConversation } from "@/lib/agent/session-store";
+import { findOrCreateAgentSessionForConversation, getAgentSession } from "@/lib/agent/session-store";
import { newAgentSessionId } from "@/lib/agent/session-files";
import { conversationHash } from "@/lib/agent/session-policy";
@@ -8,7 +8,7 @@ type RpcLike = {
id?: string | number | null;
method?: string;
_meta?: Record<string, unknown>;
- params?: { _meta?: Record<string, unknown> };
+ params?: { name?: string; _meta?: Record<string, unknown> };
};
export interface ResolvedMcpSession {
@@ -31,17 +31,33 @@ function errorResponse(rpc: RpcLike, status: number, message: string): Response
}
export async function resolveMcpSession(req: Request, rpc: RpcLike, principal: string, label: string): Promise<ResolvedMcpSession | { response: Response }> {
- const transportId = (req.headers.get(MCP_SESSION_HEADER) ?? "").trim() || undefined;
+ const modern = mcpClientMeta(rpc)["io.modelcontextprotocol/protocolVersion"] === "2026-07-28";
+ const transportId = modern ? undefined : (req.headers.get(MCP_SESSION_HEADER) ?? "").trim() || undefined;
if (rpc.method === "initialize") return { responseSessionId: newAgentSessionId(), conversationBound: false };
if (rpc.method !== "tools/call") return { responseSessionId: transportId, conversationBound: false };
+ const explicitMeta = mcpClientMeta(rpc)["mso/sessionId"], explicitHeader = req.headers.get("Mso-Session-Id");
+ if (explicitMeta !== undefined || explicitHeader) {
+ if (explicitMeta !== undefined && typeof explicitMeta !== "string" || explicitHeader && explicitMeta !== undefined && explicitHeader !== explicitMeta) return { response: errorResponse(rpc, 400, "conflicting or invalid MSO session id") };
+ const id = (explicitMeta ?? explicitHeader) as string;
+ const session = await getAgentSession(principal, id).catch(() => null);
+ if (!session) return { response: errorResponse(rpc, 403, "MSO session not found for this principal") };
+ return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: true };
+ }
+ if (rpc.params?.name === "agent_session_open") return { responseSessionId: transportId, conversationBound: false };
+ const generic = mcpClientMeta(rpc)["mso/conversationKey"];
+ if (generic !== undefined) {
+ if (typeof generic !== "string" || !generic.trim() || generic.length > 256) return { response: errorResponse(rpc, 400, "invalid mso/conversationKey") };
+ const session = await findOrCreateAgentSessionForConversation(principal, conversationHash(principal, "agent:" + generic), "Agent · MSO");
+ return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: true };
+ }
const conversation = openAiSession(rpc);
if (conversation) {
const session = await findOrCreateAgentSessionForConversation(principal, conversationHash(principal, conversation), `ChatGPT · ${label || "MSO"}`);
return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: true };
}
- if (!transportId) return { response: errorResponse(rpc, 400, "missing ChatGPT conversation metadata or legacy MCP session id") };
+ if (!transportId) return { response: errorResponse(rpc, 400, "missing MSO session: call agent_session_open, then send params._meta[mso/sessionId]; ChatGPT metadata and legacy Mcp-Session-Id remain supported") };
const legacyHash = conversationHash(principal, `legacy:${transportId}`);
const session = await findOrCreateAgentSessionForConversation(principal, legacyHash, `MCP legacy · ${label || "MSO"}`);
return { responseSessionId: transportId, agentSessionId: session.id, conversationBound: false };
diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.ts
index 5840d0fe..b666743c 100644
--- a/lib/mcp/tool-contract.ts
+++ b/lib/mcp/tool-contract.ts
@@ -82,7 +82,7 @@ export function completeToolAnnotations(tool: McpTool): McpToolAnnotations {
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 } : {}),
+ ...(supplied.idempotentHint === true ? { idempotentHint: true } : {}),
};
}
@@ -94,12 +94,12 @@ export function toolAllowedForProfile(_name: string, _profile: McpToolProfile =
return true;
}
-function compactText(value: string, max = 125): string {
+function compactText(value: string, max = 80): 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()}…`;
+ return `${(sentence > max * 0.8 ? cut.slice(0, sentence + 1) : cut).trim()}…`;
}
function compactSchema(value: unknown): unknown {
@@ -107,8 +107,9 @@ function compactSchema(value: unknown): unknown {
if (!value || typeof value !== "object") return value;
const out: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
+ if (key === "additionalProperties" && item === true || key === "required" && Array.isArray(item) && item.length === 0) continue;
if (key === "workflow_id" && item && typeof item === "object") out[key] = { type:"string" };
- else if (key === "description" && typeof item === "string") out[key] = compactText(item, 72);
+ else if (key === "description" && typeof item === "string") out[key] = compactText(item, 40);
else out[key] = compactSchema(item);
}
return out;
diff --git a/lib/mcp/tools-agent-open.ts b/lib/mcp/tools-agent-open.ts
new file mode 100644
index 00000000..105f23a1
--- /dev/null
+++ b/lib/mcp/tools-agent-open.ts
@@ -0,0 +1,23 @@
+import { agentSessionSummary, findOrCreateAgentSessionForConversation, updateAgentSessionLocation } from "@/lib/agent/session-store";
+import { conversationHash } from "@/lib/agent/session-policy";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import { type McpTool, S, str } from "./tool-kit";
+export const AGENT_OPEN_TOOLS: McpTool[] = [{
+ name: "agent_session_open", title: "Open Agent Session", scope: "write",
+ description: "Bootstrap an MSO application session for any AI provider. Reuse a unique conversation_key per conversation; this is metadata, never a secret. Send returned session.id as params._meta[mso/sessionId] or Mso-Session-Id on later calls. Optional exact project binds its working directory. The session is isolated to the authenticated principal.",
+ chatgptDescription: "Open/resume a provider-neutral session using a stable conversation_key. Send session.id as _meta[mso/sessionId] on later calls.",
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true },
+ audit: { action: "agent.session" }, limit: { key: "agent.session.open", max: 20, windowMs: 60_000 },
+ inputSchema: S({ conversation_key: { type: "string", minLength: 1, maxLength: 256 }, project: { type: "string", description: "Optional exact project id/path/name." } }, ["conversation_key"]),
+ run: async (a, context) => {
+ if (!context.principal) throw new Error("authenticated principal required");
+ const key = str(a, "conversation_key");
+ if (!key.trim() || key.length > 256 || /[\x00-\x1f]/.test(key)) throw new Error("invalid conversation_key");
+ const project = a.project ? await resolveProjectHint(str(a, "project")) : null;
+ if (a.project && (!project || project.matchedBy === "fuzzy")) throw new Error("exact project required");
+ let session = await findOrCreateAgentSessionForConversation(context.principal, conversationHash(context.principal, "agent:" + key), "Agent · MSO");
+ if (project && session.cwd !== project.path) session = await updateAgentSessionLocation(context.principal, session.id, project.path);
+ return { session: agentSessionSummary(session), ...(project ? { project: project.id } : {}),
+ next: { meta: { "mso/sessionId": session.id }, flow: "flow_catalog → flow_run → flow_status", projectMcp: "project_capabilities → project_mcp_tools → project_mcp_call" } };
+ },
+}];
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
new file mode 100644
index 00000000..fe3c735a
--- /dev/null
+++ b/lib/mcp/tools-flows.ts
@@ -0,0 +1,44 @@
+import { flowCatalog } from "@/lib/workflow/automation-catalog";
+import { startFlow, flowStatus } from "@/lib/workflow/automation-engine";
+import { BUILTIN_FLOWS } from "@/lib/workflow/automation-builtins";
+import { manageProjectFlow } from "@/lib/host/project-flow-manifest";
+import { type McpTool, S, str } from "./tool-kit";
+const project = { type: "string", maxLength: 4096, description: "Exact project id/path/name." };
+const flow = { type: "string", maxLength: 64, description: "Flow id from flow_catalog." };
+export const FLOW_TOOLS: McpTool[] = [
+ { name: "flow_catalog", title: "Discover Automation Flows", scope: "read",
+ description: "Discover reusable API/MCP flows for an exact project. Returns input schema, ordered steps, account context and required scope. Inspect a flow before flow_run; project flows live in .mso/flows.json.",
+ chatgptDescription: "Discover project automation flows, required inputs and ordered steps. Inspect before flow_run.",
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
+ inputSchema: S({ project, flow }, ["project"]),
+ run: async a => { const { project: p, flows, revision } = await flowCatalog(str(a, "project"), typeof a.flow === "string" ? a.flow : undefined); return { project: p.id, revision, flows }; } },
+ { name: "flow_run", title: "Run Automation Flow", scope: "exec",
+ description: "Start one inspected API/MCP flow with exact project, input and idempotency_key. Child tools retain scope, connection guards and audits. Same key/input returns the existing receipt; changed input is refused. Returns durable run id; use flow_status for progress. Never auto-retries a failed mutation.",
+ chatgptDescription: "Run an inspected flow for exact project/input/idempotency_key. Returns a run id; flow_status reads progress.",
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, audit: { action: "exec.run", targetArg: "flow" },
+ limit: { key: "flow.run", max: 20, windowMs: 60_000 },
+ inputSchema: S({ project, flow, input: { type: "object", additionalProperties: true }, idempotency_key: { type: "string", minLength: 1, maxLength: 128 } }, ["project", "flow", "input", "idempotency_key"]),
+ run: async (a, context) => {
+ const catalog = await flowCatalog(str(a, "project"), str(a, "flow"));
+ const { TOOLS_BY_NAME } = await import("./tools");
+ return startFlow(catalog.definitions[0], catalog.project.id, a.input, str(a, "idempotency_key"), context, name => TOOLS_BY_NAME.get(name));
+ } },
+ { name: "flow_status", title: "Automation Flow Status", scope: "read",
+ description: "Read a durable flow receipt owned by this authenticated principal. Optional wait_ms (0-25000) reduces client polling. Reports step results and interrupted outcomes; never replays work.",
+ chatgptDescription: "Read a flow run's step results. wait_ms up to 25000 reduces polling. Interrupted writes need outcome inspection.",
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
+ inputSchema: S({ run_id: { type: "string", pattern: "^[a-f0-9]{32}$" }, wait_ms: { type: "integer", minimum: 0, maximum: 25_000 } }, ["run_id"]),
+ run: (a, context) => flowStatus(str(a, "run_id"), context, Number(a.wait_ms) || 0) },
+ { name: "flow_manage", limit: { key: "flow.manage", max: 20, windowMs: 60_000 }, title: "Save Project Automation", scope: "write",
+ description: "Create/update/delete one project flow in .mso/flows.json using the revision from flow_catalog (new for absent manifest). Built-ins cannot be overwritten. Definitions contain metadata and exact API/MCP tool steps; credentials are forbidden.",
+ chatgptDescription: "Save or delete a project flow with revision from flow_catalog. Never include credentials; built-ins are immutable.",
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }, audit: { action: "fs.write", targetArg: "project" },
+ inputSchema: S({ project, flow, action: { type: "string", enum: ["upsert", "delete"] }, revision: { type: "string" }, definition: { type: "object", additionalProperties: true } }, ["project", "flow", "action", "revision"]),
+ run: async a => {
+ const id = str(a, "flow");
+ if (BUILTIN_FLOWS.some(flow => flow.id === id)) throw new Error("built-in flow is immutable");
+ if (a.action !== "upsert" && a.action !== "delete") throw new Error("action must be upsert or delete");
+ const catalog = await flowCatalog(str(a, "project"));
+ return manageProjectFlow(catalog.project.path, { action: a.action, id, flow: a.definition, revision: str(a, "revision") });
+ } },
+];
diff --git a/lib/mcp/tools-integrations.ts b/lib/mcp/tools-integrations.ts
index 395b5e56..d2d44da4 100644
--- a/lib/mcp/tools-integrations.ts
+++ b/lib/mcp/tools-integrations.ts
@@ -8,20 +8,20 @@ const OUTPUT={type:"object",properties:{result:{type:"object"}},required:["resul
export const INTEGRATION_TOOLS:McpTool[]=[
{name:"integration_query",title:"Inspect Integration Connections",scope:"read",annotations:{readOnlyHint:true,idempotentHint:true,openWorldHint:false},
description:"Read native MSO credential users, providers, named connections, source/auth guidance and directory resolution. Never returns keys. User profiles are credential owners, not device roles. Resolve before acting when multiple accounts or deployments exist.",
- chatgptDescription:"Inspect.",
+ chatgptDescription:"Inspect users, providers and connections. Use view=request for setup or view=resolve before an exact operation.",
inputSchema:S({...BASE,view:{type:"string",enum:["snapshot","catalog","users","connections","which","resolve","request"]},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64}}),outputSchema:OUTPUT,
meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await queryIntegrationAction(a)}),
},
{name:"integration_manage",title:"Manage Integrations",scope:"write",annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:true},audit:{action:"infra.write",targetArg:"user"},limit:{key:"integration.manage",max:30,windowMs:60000},
description:"Manage native credential users, directory bindings and named provider connections. Actions require confirm=true. Direct credential values are forbidden: use integration_setup_open with user/provider/connection. Composio authorization keeps only external IDs/status and returns its transient URL privately to the UI. Native MCP authorization stays provider-owned.",
- chatgptDescription:"Manage.",
+ chatgptDescription:"Create or update connection metadata with action and confirm=true. Credentials use integration_setup_open.",
inputSchema:S({...BASE,action:{type:"string",enum:[...INTEGRATION_ACTIONS,"connection.authorize","connection.import-convex-cli"]},confirm:{type:"boolean",const:true},target:{type:"string",maxLength:64},label:{type:"string",maxLength:120},path:{type:"string",maxLength:4096},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64},copyCredentials:{type:"boolean",description:"Duplicate with credentials."},makeDefault:{type:"boolean"},key:{type:"string",maxLength:64},authConfigId:{type:"string",maxLength:64},brokerConnection:{type:"string",maxLength:64},createManaged:{type:"boolean"}},["action","confirm"]),outputSchema:OUTPUT,
meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},
run:async a=>{const out=await manageIntegrationAction(a);if("privateUrl" in out){const{privateUrl,...safe}=out;return mcpDirect([{type:"text",text:"Authorization link available in the private integration UI."}],false,{result:safe},{integrationAuthorization:{url:privateUrl}});}return{result:out};},
},
{name:"integration_execute",title:"Use an Exact Integration Connection",scope:"exec",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true},audit:{action:"infra.write",targetArg:"connection"},limit:{key:"integration.execute",max:30,windowMs:60000},
description:"Execute using an explicit user/provider/named connection. Verify or inspect its route; bounded direct operations reject external backends. Composio tool execution requires an ACTIVE connected account and a toolkit-prefixed tool. Native-MCP returns the provider route without copying OAuth tokens. Non-verification operations require confirm=true. No credentials in arguments.",
- chatgptDescription:"Execute.",
+ chatgptDescription:"Run an operation for exact user/provider/connection. Route or verify first; mutations need confirm=true.",
inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.applications.list","dokploy.gitProviders.list","dokploy.github.repositories.list","dokploy.application.ensureGithub","dokploy.domain.ensure","dokploy.deployments.list","dokploy.deployment.logs","dokploy.git.recover","dokploy.application.deploy","dokploy.dockerfile","dokploy.application.publicEnv.upsert","dokploy.project.ensure","convex.customDomains.list","convex.customDomain.ensure","convex.canonical.get","convex.env.presence","convex.canonical.set","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","hostinger.mail.orders.list","hostinger.mail.plan.get","hostinger.mail.list","hostinger.mail.logs.list","hostinger.mail.mutate","composio.tool"]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,
meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await executeIntegrationAction(a)}),
},
diff --git a/lib/mcp/tools-project-assets.ts b/lib/mcp/tools-project-assets.ts
new file mode 100644
index 00000000..9bba96a1
--- /dev/null
+++ b/lib/mcp/tools-project-assets.ts
@@ -0,0 +1,21 @@
+import { ownedArtifactSession } from "@/lib/agent/artifact-session";
+import { readSessionArtifact } from "@/lib/agent/artifacts";
+import { attachProjectAsset } from "@/lib/host/project-assets";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import { type McpTool, S, str, opt } from "./tool-kit";
+export const PROJECT_ASSET_TOOLS: McpTool[] = [{
+ name: "project_asset_attach", title: "Attach Asset to Project", scope: "write",
+ description: "Copy one owned session image/JSON artifact into an exact project at relative_path. Verifies source checksum and creates the destination atomically; same bytes are idempotent, different existing bytes are refused. Project copy survives session cleanup. Preview with session_artifacts; manage project files with fs_*.",
+ chatgptDescription: "Save a session image/JSON permanently into an exact project. Requires artifact_id and relative_path; never overwrites different content.",
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: true },
+ limit: { key: "project.asset.attach", max: 20, windowMs: 60_000 },
+ audit: { action: "fs.write", targetArg: "relative_path" },
+ inputSchema: S({ project: { type: "string" }, artifact_id: { type: "string" }, relative_path: { type: "string", maxLength: 1024 }, session_id: { type: "string", description: "Optional source session owned by this principal; defaults to current." } }, ["project", "artifact_id", "relative_path"]),
+ run: async (a, context) => {
+ const project = await resolveProjectHint(str(a, "project"));
+ if (!project || project.matchedBy === "fuzzy") throw new Error("exact project required");
+ const owner = await ownedArtifactSession(context.principal, opt(a, "session_id") || context.sessionId);
+ const source = await readSessionArtifact(owner, str(a, "artifact_id"));
+ return { project: project.id, artifactId: source.entry.id, ...await attachProjectAsset(project.path, str(a, "relative_path"), source.bytes, source.entry.mimeType) };
+ },
+}];
diff --git a/lib/mcp/tools-project-mcp-manage.ts b/lib/mcp/tools-project-mcp-manage.ts
new file mode 100644
index 00000000..b61cbbd6
--- /dev/null
+++ b/lib/mcp/tools-project-mcp-manage.ts
@@ -0,0 +1,29 @@
+import { inspectProjectMcp, manageProjectMcp } from "@/lib/host/project-mcp-manage";
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import { type McpTool, S, str } from "./tool-kit";
+export const PROJECT_MCP_MANAGE_TOOLS: McpTool[] = [{
+ name: "project_mcp_manage", title: "Add or Manage Project MCP", scope: "write",
+ description: "Inspect/add/update/remove one HTTP MCP binding in an exact project's .mcp.json. Inspect first for revision; pass it for upsert/delete. Other servers are preserved. Optional exact user/connection references private MCP credentials; never put credentials in url or arguments. Discover with project_mcp_tools after setup.",
+ chatgptDescription: "Add or manage a project's HTTP MCP. Inspect for revision, then upsert/delete. Credentials stay in a private connection.",
+ meta: { ui: { visibility: ["model", "app"] }, "openai/widgetAccessible": true },
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },
+ limit: { key: "project.mcp.manage", max: 20, windowMs: 60_000 },
+ audit: { action: "fs.write", targetArg: "project" },
+ inputSchema: S({
+ project: { type: "string", description: "Exact project id/path/name." },
+ action: { type: "string", enum: ["inspect", "upsert", "delete"] },
+ server: { type: "string", maxLength: 64, description: "Project-local server alias. Required for mutations." },
+ revision: { type: "string", description: "Revision from inspect. Required for mutations." },
+ url: { type: "string", maxLength: 4096, description: "HTTPS endpoint without credentials/query/fragment. Required for upsert." },
+ user: { type: "string", description: "Exact credential owner; use together with connection." },
+ connection: { type: "string", description: "Exact private MCP connection; omit both for public MCP." },
+ }, ["project", "action"]),
+ run: async a => {
+ const project = await resolveProjectHint(str(a, "project"));
+ if (!project || project.matchedBy === "fuzzy") throw new Error("exact project required");
+ if (a.action === "inspect") return { project: project.id, ...await inspectProjectMcp(project.path) };
+ if (a.action !== "upsert" && a.action !== "delete") throw new Error("invalid MCP action");
+ return { project: project.id, ...await manageProjectMcp(project.path, { action: a.action, server: str(a, "server"), revision: str(a, "revision"),
+ url: typeof a.url === "string" ? a.url : undefined, user: typeof a.user === "string" ? a.user : undefined, connection: typeof a.connection === "string" ? a.connection : undefined }) };
+ },
+}];
diff --git a/lib/mcp/tools-project-mcp.ts b/lib/mcp/tools-project-mcp.ts
index a1b4fce6..37efd8ae 100644
--- a/lib/mcp/tools-project-mcp.ts
+++ b/lib/mcp/tools-project-mcp.ts
@@ -1,9 +1,11 @@
-import { callProjectMcpTool, listProjectMcpTools, publicProjectMcpServers, readProjectMcpServers, resolveProjectHint } from "@/lib/host/projects-api";
-import { type McpTool, S, str } from "./tool-kit";
+import { projectMcpResult } from "@/lib/host/project-mcp-result";
+import { callProjectMcpTool, listProjectMcpToolPage, publicProjectMcpServers, readProjectMcpServers, resolveProjectHint } from "@/lib/host/projects-api";
+import { type McpTool, S, str, mcpDirect } from "./tool-kit";
export const PROJECT_MCP_TOOLS: McpTool[] = [
{
name: "project_mcp_tools",
+ result: { maxTextBytes: 64 * 1024, overflowHint: "Use limit=1 for a narrower descriptor page; preserve the exact nextCursor." },
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: "Discover a declared project MCP through its private connection. Dynamic tools stay project-scoped.",
@@ -14,12 +16,14 @@ export const PROJECT_MCP_TOOLS: McpTool[] = [
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." },
+ cursor: { type: "string", maxLength: 8192, description: "Exact nextCursor from the previous page." },
+ limit: { type: "integer", minimum: 1, maximum: 100 }, refresh: { type: "boolean", description: "Bypass the 30-second HTTP descriptor cache." },
}, ["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) };
+ return { project: { id: project.id, name: project.name }, server: selected, ...await listProjectMcpToolPage(project.path, selected.name, { cursor: typeof a.cursor === "string" ? a.cursor : undefined, limit: Number(a.limit) || 50, refresh: a.refresh === true }) };
},
},
{
@@ -28,6 +32,7 @@ export const PROJECT_MCP_TOOLS: McpTool[] = [
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",
+ outputSchema: { type: "object", properties: { result: { type: "object" } }, required: ["result"], additionalProperties: false },
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" },
@@ -40,7 +45,8 @@ export const PROJECT_MCP_TOOLS: McpTool[] = [
}, ["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 ?? {}) };
+ const out = projectMcpResult(await callProjectMcpTool(project.path, str(a, "server"), str(a, "tool"), a.arguments ?? {}));
+ return mcpDirect(out.content, out.isError, { result: { project: project.id, server: str(a, "server"), tool: str(a, "tool"), ...(out.structuredContent ? { structuredContent: out.structuredContent } : {}) } }, out.meta);
},
},
];
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index bac51c44..6ab673cb 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -1,3 +1,7 @@
+import { AGENT_OPEN_TOOLS } from "./tools-agent-open";
+import { PROJECT_ASSET_TOOLS } from "./tools-project-assets";
+import { PROJECT_MCP_MANAGE_TOOLS } from "./tools-project-mcp-manage";
+import { FLOW_TOOLS } from "./tools-flows";
import { withWorkflowContext } from "./tool-context";
import { A2A_TOOLS } from "./tools-a2a";
import { AGENT_TOOLS } from "./tools-agent";
@@ -20,4 +24,4 @@ import { BLOCK_TOOLS, SURFACE_TOOLS } from "./tools-ui";
import type { McpTool } from "./tool-kit";
import { MUTATE_TOOLS } from "./tools-mutate";
-export const TOOLS: McpTool[] = [...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
+export const TOOLS: McpTool[] = [...FLOW_TOOLS, ...AGENT_OPEN_TOOLS, ...PROJECT_ASSET_TOOLS, ...PROJECT_MCP_MANAGE_TOOLS, ...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_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.ts
index 33736f6a..459c13d6 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -3,9 +3,9 @@ import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
import { toolDescriptor, type McpToolProfile } from "./tool-contract";
-export const MCP_SERVER_VERSION = "1.12.3";
-export const MCP_TOOLSET_VERSION = "2026.09.10.1";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-10T02:40:00Z";
+export const MCP_SERVER_VERSION = "1.13.0";
+export const MCP_TOOLSET_VERSION = "2026.09.12.1";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-12T12:55:00Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/mcp/ui-page-integrations.ts b/lib/mcp/ui-page-integrations.ts
index c69e103b..8855846d 100644
--- a/lib/mcp/ui-page-integrations.ts
+++ b/lib/mcp/ui-page-integrations.ts
@@ -22,6 +22,7 @@ function renderIntegrations(){
const bridge={openTransferBrowser:()=>openIntegrationReference(INTEGRATION_BROWSER+"?transfer=1"),remember:s=>integrationSelection=s,openLink:openIntegrationReference,
query:async args=>(await integrationTool("integration_query",args)).data,
manage:async args=>{const{response,data}=await integrationTool("integration_manage",args);const meta=privateIntegrationMeta(response,"integrationAuthorization")||privateIntegrationMeta(window.openai?.toolResponseMetadata,"integrationAuthorization");return{...data,...(meta?.url?{privateUrl:meta.url}:{})}},
+ projectMcp:async args=>(await integrationTool("project_mcp_manage",args)).data,
execute:async args=>(await integrationTool("integration_execute",args)).data,
openSetup:async args=>{const{response}=await integrationTool("integration_setup_open",args);captureIntegrationAccess(response);captureIntegrationAccess(window.openai?.toolResponseMetadata);if(!acceptPageResult(response))throw new Error("The host did not return a valid setup Page. Use Open in MSO or refresh this connector.")},
};
diff --git a/lib/orchestration/capability-catalog.mjs b/lib/orchestration/capability-catalog.mjs
index b481a9af..fce71c58 100644
--- a/lib/orchestration/capability-catalog.mjs
+++ b/lib/orchestration/capability-catalog.mjs
@@ -1,4 +1,7 @@
const ROUTES = [
+ { id: "automation-flow", priority: 105, patterns: [/\b(automation flow|flow_catalog|flow_run|mso flow|reusable flow|alur otomatis|otomasi provider)\b/i], tools: ["flow_catalog", "flow_run", "flow_status", "flow_manage", "integration_query"], budget: 10_000 },
+ { id: "project-mcp-add", priority: 105, patterns: [/\b(add|connect|tambah|pasang)\b.{0,30}\bmcp\b/i], tools: ["project_mcp_manage", "project_mcp_tools", "integration_query", "integration_setup_open"], budget: 10_000 },
+ { id: "project-asset", priority: 105, patterns: [/\b(attach|save|kirim|simpan)\b.{0,40}\b(asset|image|gambar)\b.{0,30}\b(project|proyek)\b/i], tools: ["session_artifacts", "project_asset_attach"], budget: 8_000 },
{ id: "managed-app-diagnostics", priority: 100, patterns: [/\b(hermes|openclaw|managed app|service)\b.*\b(down|error|crash|logs?|journal|status)\b/i, /\b(logs?|journal)\b.*\b(hermes|openclaw|service)\b/i], tools: ["apps_list", "apps_logs"], budget: 8_000 },
{ id: "managed-app-power", priority: 100, patterns: [/\b(start|stop|restart|backup)\b.*\b(hermes|openclaw|managed app|service)\b/i], tools: ["apps_list", "apps_power"], budget: 8_000 },
{ id: "server-health", priority: 95, patterns: [/\b(vps|server|host)\b.*\b(health|cpu|ram|memory|disk|uptime|load|process)\b/i, /\b(cpu|ram|disk|uptime|top processes?)\b/i], tools: ["sys_stats", "sys_processes"], budget: 8_000 },
diff --git a/lib/workflow/automation-builtins.ts b/lib/workflow/automation-builtins.ts
new file mode 100644
index 00000000..6d6c9eff
--- /dev/null
+++ b/lib/workflow/automation-builtins.ts
@@ -0,0 +1,20 @@
+import type { AutomationFlow } from "@/lib/contracts/automation";
+const ref = (name: string) => ({ $ref: "input." + name });
+export const BUILTIN_FLOWS: AutomationFlow[] = ["cloudflare", "hostinger"].map(provider => ({
+ id: provider + ".dns.ensure",
+ description: "Verify one exact " + provider + " account, then create/update one DNS record. Existing unrelated records are preserved; propagation is separate.",
+ inputs: {
+ user: { type: "string", required: true, description: "Credential owner from integration_query." },
+ connection: { type: "string", required: true, description: "Exact named direct provider connection." },
+ name: { type: "string", required: true, description: "Fully-qualified DNS hostname." },
+ type: { type: "string", required: true, description: "DNS record type.", enum: provider === "cloudflare" ? ["A", "AAAA", "CNAME", "TXT"] : ["A", "CNAME", "TXT"] },
+ content: { type: "string", required: true, description: "Record target or text." },
+ ttl: { type: "integer", default: provider === "cloudflare" ? 1 : 14400, description: "TTL in seconds; Cloudflare 1 means automatic." },
+ ...(provider === "cloudflare" ? { proxied: { type: "boolean" as const, default: false, description: "Enable Cloudflare proxy for A/AAAA/CNAME." } } : {}),
+ },
+ steps: [
+ { id: "verify", tool: "integration_execute", arguments: { user: ref("user"), provider, connection: ref("connection"), operation: "verify" }, expect: { path: "result.ok", equals: true } },
+ { id: "dns", tool: "integration_execute", arguments: { user: ref("user"), provider, connection: ref("connection"), operation: provider + ".dns.upsert", confirm: true,
+ arguments: { name: ref("name"), type: ref("type"), content: ref("content"), ttl: ref("ttl"), ...(provider === "cloudflare" ? { proxied: ref("proxied") } : {}) } } },
+ ],
+}));
diff --git a/lib/workflow/automation-catalog.ts b/lib/workflow/automation-catalog.ts
new file mode 100644
index 00000000..da172ee4
--- /dev/null
+++ b/lib/workflow/automation-catalog.ts
@@ -0,0 +1,19 @@
+import { resolveProjectHint } from "@/lib/host/projects-api";
+import { readProjectFlows } from "@/lib/host/project-flow-manifest";
+import { BUILTIN_FLOWS } from "./automation-builtins";
+import { flowInputSchema } from "./automation-schema";
+
+export async function flowCatalog(projectHint: string, id?: string) {
+ const project = await resolveProjectHint(projectHint);
+ if (!project || project.matchedBy === "fuzzy") throw new Error("exact project id/path/name required");
+ const stored = await readProjectFlows(project.path);
+ if (stored.flows.some(flow => BUILTIN_FLOWS.some(b => b.id === flow.id))) throw new Error("project flow cannot shadow a built-in flow");
+ const all = [...BUILTIN_FLOWS, ...stored.flows];
+ const flows = id ? all.filter(flow => flow.id === id) : all;
+ if (id && !flows.length) throw new Error("unknown flow: " + id);
+ return { project, revision: stored.revision, definitions: flows,
+ flows: flows.map(flow => !id ? { id: flow.id, description: flow.description, inputs: Object.keys(flow.inputs), requiredScope: "exec", next: "flow_catalog with this flow id returns the complete input schema and steps." } : ({ id: flow.id, description: flow.description, inputSchema: flowInputSchema(flow), steps: flow.steps,
+ source: BUILTIN_FLOWS.some(b => b.id === flow.id) ? "builtin" : ".mso/flows.json", requiredScope: "exec",
+ context: ["project", "authenticated session", "idempotency_key", "exact user/provider/connection for API steps; server alias for project MCP"],
+ execution: "flow_run starts one receipt; flow_status waits up to 25 seconds. Failed/uncertain mutations are never auto-replayed." })) };
+}
diff --git a/lib/workflow/automation-engine.ts b/lib/workflow/automation-engine.ts
new file mode 100644
index 00000000..eb034e3e
--- /dev/null
+++ b/lib/workflow/automation-engine.ts
@@ -0,0 +1,106 @@
+import { capabilityReportedFailure } from "@/lib/capabilities/result-outcome";
+import { randomUUID } from "node:crypto";
+import { executeCapabilityCall } from "@/lib/capabilities/execute";
+import { isCapabilityDirectResult, type CapabilityRunContext, type CapabilityTool } from "@/lib/capabilities/tool";
+import { boundedResultText } from "@/lib/capabilities/result-budget";
+import { redactText } from "@/lib/security/redact-text";
+import type { AutomationFlow, FlowRun } from "@/lib/contracts/automation";
+import { flowInputs, flowStepArgs, flowValue, object } from "./automation-schema";
+import { flowHash, flowOwner, lockFlowOwner, lockFlowRun, pruneFlowReceipts, publicFlowRun, readFlowRun, writeFlowRun } from "./automation-store";
+
+const state = globalThis as typeof globalThis & { msoFlowInstance?: string; msoFlowPending?: Map<string, Promise<void>> };
+const INSTANCE = state.msoFlowInstance ??= randomUUID();
+const pending = state.msoFlowPending ??= new Map<string, Promise<void>>();
+type Resolver = (name: string) => CapabilityTool | undefined;
+function principal(context: CapabilityRunContext) {
+ if (!context.principal) throw new Error("flow requires an authenticated agent session");
+ return context.principal;
+}
+function canonical(v: unknown): string {
+ return JSON.stringify(v && typeof v === "object" ? Array.isArray(v) ? v.map(x => JSON.parse(canonical(x))) :
+ Object.fromEntries(Object.entries(v).sort(([a],[b]) => a.localeCompare(b)).map(([k,x]) => [k, JSON.parse(canonical(x))])) : v);
+}
+function resultData(result: unknown) {
+ if (capabilityReportedFailure(result)) throw new Error("downstream tool reported an error");
+ if (!isCapabilityDirectResult(result)) return result;
+ if (result.isError) throw new Error("downstream tool reported an error");
+ if (result.structuredContent) return result.structuredContent;
+ const text = result.content.filter(c => c.type === "text").map(c => c.text).join("\n");
+ try { return JSON.parse(text); } catch { return { text }; }
+}
+async function execute(run: FlowRun, flow: AutomationFlow, input: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver) {
+ const steps: Record<string, unknown> = {};
+ try {
+ for (const step of flow.steps) {
+ if (Date.now() - Date.parse(run.startedAt) > 10 * 60_000) throw new Error("flow exceeded 10 minutes; later steps were not started");
+ const tool = resolve(step.tool);
+ if (!tool) throw new Error("flow tool unavailable: " + step.tool);
+ const args = flowStepArgs(step, { input, steps, project: run.project }, context.workflowId);
+ const row: FlowRun["steps"][number] = { id: step.id, tool: step.tool, state: "running" };
+ run.steps.push(row); run.updatedAt = new Date().toISOString(); await writeFlowRun(run);
+ const started = Date.now();
+ try {
+ const outcome = await executeCapabilityCall({ tool, args, scope: context.scope, actor: context.actor, context });
+ if (outcome.kind !== "success") throw new Error(outcome.message);
+ const data = resultData(outcome.result);
+ if (step.expect && canonical(flowValue(data, step.expect.path)) !== canonical(step.expect.equals)) throw new Error("flow expectation failed: " + step.expect.path);
+ const value = JSON.parse(boundedResultText(typeof data === "string" ? { text: data } : data, { maxTextBytes: 12 * 1024, overflowHint: "Read the provider/project result directly for full details." }));
+ steps[step.id] = data; row.result = value; row.state = "completed";
+ } catch (error) {
+ row.state = "failed"; row.error = redactText(error instanceof Error ? error.message : "step failed", 500); throw error;
+ } finally { row.durationMs = Date.now() - started; run.updatedAt = new Date().toISOString(); await writeFlowRun(run); }
+ }
+ run.state = "completed";
+ } catch (error) { run.state = "failed"; run.error = redactText(error instanceof Error ? error.message : "flow failed", 500); }
+ run.finishedAt = run.updatedAt = new Date().toISOString(); await writeFlowRun(run);
+}
+export async function startFlow(flow: AutomationFlow, project: string, raw: unknown, key: string, context: CapabilityRunContext, resolve: Resolver) {
+ if (!context.sessionId) throw new Error("flow requires an authenticated agent session");
+ const owner = flowOwner(principal(context));
+ if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(key)) throw new Error("idempotency_key must be 1-128 simple characters");
+ const input = flowInputs(flow, raw), fingerprint = flowHash(canonical({ flow, input, project }));
+ const id = flowHash(owner + ":" + key).slice(0, 32);
+ return lockFlowOwner(owner, () => lockFlowRun(owner, id, async () => {
+ const existing = await readFlowRun(owner, id);
+ if (existing) {
+ if (existing.fingerprint !== fingerprint) throw new Error("idempotency_key already identifies different flow/input/project");
+ return publicFlowRun(existing);
+ }
+ for (const step of flow.steps) {
+ const tool = resolve(step.tool);
+ if (!tool || (context.allowedTools && !context.allowedTools.includes(step.tool)) || ({ read: 0, write: 1, exec: 2 }[tool.scope] > { read: 0, write: 1, exec: 2 }[context.scope])) throw new Error("flow step not permitted: " + step.tool);
+ }
+ // Resolve every input reference before any step can mutate external state.
+ function preflight(value: unknown) {
+ if (!value || typeof value !== "object") return;
+ if (object(value) && typeof value.$ref === "string" && value.$ref.startsWith("input.")) flowValue({ input }, value.$ref);
+ Object.values(value).forEach(preflight);
+ }
+ flow.steps.forEach(step => preflight(step.arguments));
+ await pruneFlowReceipts(owner);
+ const run: FlowRun = { version: 1, id, owner, sessionId: context.sessionId!, project, flow: flow.id, fingerprint, pid: process.pid, instance: INSTANCE,
+ state: "running", startedAt: new Date().toISOString(), updatedAt: new Date().toISOString(), steps: [] };
+ await writeFlowRun(run);
+ const work = execute(run, flow, input, context, resolve).catch(() => undefined).finally(() => pending.delete(id));
+ pending.set(id, work);
+ return publicFlowRun(run);
+ }));
+}
+export async function flowStatus(id: string, context: CapabilityRunContext, waitMs = 0) {
+ const owner = flowOwner(principal(context));
+ let run = await readFlowRun(owner, id);
+ if (!run) throw new Error("flow run not found for this principal");
+ if (run.state === "running" && pending.has(id) && waitMs > 0) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([pending.get(id), new Promise(resolve => { timer = setTimeout(resolve, Math.min(25_000, waitMs)); })]);
+ clearTimeout(timer); run = await readFlowRun(owner, id) ?? run;
+ }
+ if (run.state === "running" && run.instance !== INSTANCE) {
+ let gone = false;
+ try { process.kill(run.pid, 0); } catch (e) { gone = (e as NodeJS.ErrnoException).code === "ESRCH"; }
+ if (gone) {
+ run.state = "interrupted"; run.updatedAt = new Date().toISOString();
+ }
+ }
+ return publicFlowRun(run);
+}
diff --git a/lib/workflow/automation-schema.ts b/lib/workflow/automation-schema.ts
new file mode 100644
index 00000000..04d1e265
--- /dev/null
+++ b/lib/workflow/automation-schema.ts
@@ -0,0 +1,114 @@
+import type { AutomationFlow, FlowInput, FlowStep } from "@/lib/contracts/automation";
+
+function metadataOnly(value: unknown, depth = 0): void {
+ if (depth > 12) throw new Error("flow metadata too deep");
+ if (!value || typeof value !== "object") return;
+ for (const [key, child] of Object.entries(value)) {
+ if (/^(secrets?|secretValue|password|passphrase|token|apiKey|apiToken|accessToken|refreshToken|authorization|headers|__proto__|constructor|prototype)$/i.test(key)) throw new Error("secret_input_forbidden");
+ metadataOnly(child, depth + 1);
+ }
+}
+const NAME = /^[a-z][a-z0-9_-]{0,63}$/;
+const ID = /^[a-z][a-z0-9_.-]{0,63}$/;
+const TOOLS = new Set(["integration_execute", "project_mcp_call", "project_function_call"]);
+const TYPES = new Set(["string", "number", "integer", "boolean", "object", "array"]);
+export const object = (v: unknown): v is Record<string, unknown> => Boolean(v && typeof v === "object" && !Array.isArray(v));
+function keys(value: Record<string, unknown>, allowed: string[]) {
+ const invalid = Object.keys(value).find(k => !allowed.includes(k));
+ if (invalid) throw new Error("unknown flow field: " + invalid);
+}
+function text(v: unknown, max: number): v is string { return typeof v === "string" && v.trim().length > 0 && v.length <= max; }
+export function parseFlow(raw: unknown): AutomationFlow {
+ if (!object(raw) || Buffer.byteLength(JSON.stringify(raw)) > 64 * 1024) throw new Error("flow must be an object up to 64 KiB");
+ keys(raw, ["id", "description", "inputs", "steps"]);
+ if (!text(raw.id, 64) || !ID.test(raw.id) || !text(raw.description, 600)) throw new Error("flow id/description invalid");
+ if (!object(raw.inputs) || Object.keys(raw.inputs).length > 32) throw new Error("flow inputs must have at most 32 fields");
+ metadataOnly(raw);
+ for (const [name, field] of Object.entries(raw.inputs)) {
+ if (!NAME.test(name) || !object(field)) throw new Error("invalid flow input: " + name);
+ keys(field, ["type", "description", "required", "default", "enum"]);
+ if (!TYPES.has(String(field.type)) || !text(field.description, 300)) throw new Error("invalid input type/description: " + name);
+ if (field.default !== undefined && !matches(field as FlowInput, field.default)) throw new Error("default does not match input type");
+ if (field.required !== undefined && typeof field.required !== "boolean") throw new Error("invalid required flag");
+ if (field.enum !== undefined && (!Array.isArray(field.enum) || field.enum.length > 64 ||
+ field.enum.some(v => !["string", "number", "boolean"].includes(typeof v)))) throw new Error("invalid input enum");
+ }
+ if (!Array.isArray(raw.steps) || !raw.steps.length || raw.steps.length > 12) throw new Error("flow needs 1-12 steps");
+ const inputNames = new Set(Object.keys(raw.inputs));
+ const seen = new Set<string>();
+ for (const step of raw.steps) {
+ if (!object(step)) throw new Error("invalid flow step");
+ keys(step, ["id", "tool", "arguments", "expect"]);
+ if (!text(step.id, 64) || !NAME.test(step.id) || seen.has(step.id) || !TOOLS.has(String(step.tool)) || !object(step.arguments)) throw new Error("invalid/duplicate flow step");
+ function references(value: unknown) {
+ if (!value || typeof value !== "object") return;
+ if (object(value) && Object.hasOwn(value, "$ref")) {
+ if (Object.keys(value).length !== 1 || typeof value.$ref !== "string") throw new Error("invalid flow reference");
+ const [kind, name, ...tail] = value.$ref.split(".");
+ if (kind === "project" ? name !== undefined : kind === "input" ? !name || !inputNames.has(name) : kind === "steps" ? !name || !seen.has(name) : true) throw new Error("unknown or forward flow reference");
+ if (tail.some(k => !/^[A-Za-z0-9_-]+$/.test(k) || ["__proto__", "constructor", "prototype"].includes(k))) throw new Error("invalid flow reference");
+ return;
+ }
+ Object.values(value).forEach(references);
+ }
+ references(step.arguments);
+ seen.add(step.id);
+ if (Object.hasOwn(step.arguments, "workflow_id")) throw new Error("flow steps inherit workflow_id");
+ if (step.expect !== undefined) {
+ if (!object(step.expect)) throw new Error("invalid flow expectation");
+ keys(step.expect, ["path", "equals"]);
+ if (!text(step.expect.path, 256) || !Object.hasOwn(step.expect, "equals")) throw new Error("invalid flow expectation");
+ }
+ }
+ return raw as unknown as AutomationFlow;
+}
+export function flowInputSchema(flow: AutomationFlow) {
+ return { type: "object", additionalProperties: false,
+ properties: Object.fromEntries(Object.entries(flow.inputs).map(([name, { required: _required, ...field }]) => [name, field])),
+ required: Object.entries(flow.inputs).filter(([,field]) => field.required).map(([name]) => name) };
+}
+function matches(field: FlowInput, value: unknown): boolean {
+ return field.type === "object" ? object(value) : field.type === "array" ? Array.isArray(value) :
+ field.type === "integer" ? typeof value === "number" && Number.isSafeInteger(value) :
+ field.type === "number" ? typeof value === "number" && Number.isFinite(value) : typeof value === field.type;
+}
+export function flowInputs(flow: AutomationFlow, raw: unknown): Record<string, unknown> {
+ if (!object(raw) || Buffer.byteLength(JSON.stringify(raw)) > 32 * 1024) throw new Error("flow input must be an object up to 32 KiB");
+ metadataOnly(raw); keys(raw, Object.keys(flow.inputs));
+ const input = { ...raw };
+ for (const [name, field] of Object.entries(flow.inputs)) {
+ if (!Object.hasOwn(input, name) && field.default !== undefined) input[name] = field.default;
+ if (input[name] === undefined) { if (field.required) throw new Error("missing input." + name); continue; }
+ if (!matches(field, input[name]) || (field.enum && !field.enum.includes(input[name] as string))) throw new Error("invalid input." + name);
+ }
+ return input;
+}
+export function flowValue(root: unknown, path: string): unknown {
+ let value = root;
+ const parts = path.split(".");
+ if (parts.length > 12 || parts.some(key => !/^[A-Za-z0-9_-]+$/.test(key) || ["__proto__", "constructor", "prototype"].includes(key))) throw new Error("invalid flow reference");
+ for (const key of parts) {
+ if ((!object(value) && !Array.isArray(value)) || !Object.hasOwn(value, key)) throw new Error("unresolved flow reference: " + path);
+ value = (value as Record<string, unknown>)[key];
+ }
+ return structuredClone(value);
+}
+export function bindFlowValue(value: unknown, context: unknown, depth = 0): unknown {
+ if (depth > 12) throw new Error("flow references too deep");
+ if (Array.isArray(value)) return value.map(v => bindFlowValue(v, context, depth + 1));
+ if (!object(value)) return value;
+ if (Object.hasOwn(value, "$ref")) {
+ if (Object.keys(value).length !== 1 || typeof value.$ref !== "string") throw new Error("flow $ref must be the whole value");
+ return flowValue(context, value.$ref);
+ }
+ return Object.fromEntries(Object.entries(value).map(([k,v]) => [k, bindFlowValue(v, context, depth + 1)]));
+}
+export function flowStepArgs(step: FlowStep, context: { input: unknown; steps: unknown; project: string }, workflowId?: string) {
+ const args = bindFlowValue(step.arguments, context) as Record<string, unknown>;
+ if (step.tool.startsWith("project_")) {
+ if (args.project !== undefined && args.project !== context.project) throw new Error("flow step cannot switch project");
+ args.project = context.project;
+ }
+ if (workflowId) args.workflow_id = workflowId;
+ return args;
+}
diff --git a/lib/workflow/automation-store.ts b/lib/workflow/automation-store.ts
new file mode 100644
index 00000000..55332bee
--- /dev/null
+++ b/lib/workflow/automation-store.ts
@@ -0,0 +1,68 @@
+import { createHash, randomUUID } from "node:crypto";
+import { constants, promises as fs } from "node:fs";
+import path from "node:path";
+import { agentSessionsDir } from "@/lib/agent/session-paths";
+import { pinSecurityStorePath } from "@/lib/security-store-path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import type { FlowRun } from "@/lib/contracts/automation";
+
+export const flowHash = (value: string) => createHash("sha256").update(value).digest("hex");
+export const flowOwner = (principal: string) => flowHash(principal);
+const ROOT = () => path.join(agentSessionsDir(), ".flow-runs");
+function file(owner: string, id: string) {
+ if (!/^[a-f0-9]{64}$/.test(owner) || !/^[a-f0-9]{32}$/.test(id)) throw new Error("invalid flow run identity");
+ return path.join(ROOT(), owner, id + ".json");
+}
+export async function readFlowRun(owner: string, id: string): Promise<FlowRun | null> {
+ const pinned = await pinSecurityStorePath(file(owner, id));
+ let handle;
+ try {
+ handle = await fs.open(pinned.file, constants.O_RDONLY | constants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size > 256 * 1024 || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error("unsafe flow run");
+ const run = JSON.parse(await handle.readFile("utf8")) as FlowRun;
+ if (run.version !== 1 || run.owner !== owner || run.id !== id || !Array.isArray(run.steps)) throw new Error("invalid flow run");
+ return run;
+ } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return null; throw e; }
+ finally { await handle?.close(); await pinned.directory.close(); }
+}
+export async function writeFlowRun(run: FlowRun) {
+ const pinned = await pinSecurityStorePath(file(run.owner, run.id)), tmp = pinned.file + "." + randomUUID() + ".tmp";
+ try {
+ const text = JSON.stringify(run);
+ if (Buffer.byteLength(text) > 256 * 1024) throw new Error("flow receipt exceeds 256 KiB");
+ await fs.writeFile(tmp, text, { flag: "wx", mode: 0o600 });
+ await fs.rename(tmp, pinned.file);
+ } finally { await fs.unlink(tmp).catch(() => undefined); await pinned.directory.close(); }
+}
+export function lockFlowRun<T>(owner: string, id: string, fn: () => Promise<T>) {
+ return withSecurityStoreLock(file(owner, id), fn);
+}
+export function lockFlowOwner<T>(owner: string, fn: () => Promise<T>) {
+ return withSecurityStoreLock(path.join(ROOT(), owner, ".quota"), fn);
+}
+export async function pruneFlowReceipts(owner: string) {
+ const directory = path.join(ROOT(), owner), entries = await fs.readdir(directory);
+ let retained = 0, running = 0;
+ for (const entry of entries) {
+ const id = entry.replace(/\.json$/, "");
+ if (!/^[a-f0-9]{32}$/.test(id)) continue;
+ const run = await readFlowRun(owner, id);
+ if (!run) continue;
+ if (run.state === "running") {
+ let gone = false;
+ try { process.kill(run.pid, 0); } catch (e) { gone = (e as NodeJS.ErrnoException).code === "ESRCH"; }
+ if (gone) { run.state = "interrupted"; run.finishedAt = run.updatedAt = new Date().toISOString(); await writeFlowRun(run); }
+ }
+ if (run.state !== "running" && Date.now() - Date.parse(run.updatedAt) > 30 * 86400_000) {
+ const pinned = await pinSecurityStorePath(file(owner, id));
+ try { await fs.unlink(pinned.file); } finally { await pinned.directory.close(); }
+ } else { retained++; if (run.state === "running") running++; }
+ }
+ // ponytail: per-owner quota bounds normal storage to 1,000 receipts; index if this measured scan becomes material.
+ if (retained >= 1000 || running >= 4) throw new Error("flow capacity reached (1,000 receipts / 4 running per owner)");
+}
+export function publicFlowRun({ owner: _owner, fingerprint: _fingerprint, pid: _pid, instance: _instance, ...run }: FlowRun) {
+ return { ...run, pollAfterMs: run.state === "running" ? 2000 : 0,
+ ...(run.state === "interrupted" ? { nextAction: "Inspect the provider outcome; never replay an uncertain mutation automatically." } : {}) };
+}
diff --git a/lib/workflow/automation.test.ts b/lib/workflow/automation.test.ts
new file mode 100644
index 00000000..8f469608
--- /dev/null
+++ b/lib/workflow/automation.test.ts
@@ -0,0 +1,52 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { mkdtemp, rm } from "node:fs/promises";
+import path from "node:path";
+import os from "node:os";
+import type { CapabilityTool } from "@/lib/capabilities/tool";
+vi.mock("@/lib/capabilities/execute", () => ({ executeCapabilityCall: async ({ tool, args, context }: { tool: CapabilityTool; args: Record<string, unknown>; context: never }) => {
+ try { return { kind: "success", result: await tool.run(args, context) }; } catch (e) { return { kind: "error", message: String(e) }; }
+} }));
+const directory = await mkdtemp(path.join(os.tmpdir(), "mso-flow-test-"));
+process.env.OS_AGENT_SESSIONS_DIR = directory;
+const { parseFlow, flowInputs, bindFlowValue } = await import("./automation-schema");
+const { startFlow, flowStatus } = await import("./automation-engine");
+const { readFlowRun, writeFlowRun, flowOwner } = await import("./automation-store");
+const context = { principal: "test-flow-owner", sessionId: "test-session", scope: "exec" as const };
+const flow = parseFlow({ id: "echo", description: "Echo two steps", inputs: { name: { type: "string", required: true, description: "Name" } }, steps: [
+ { id: "first", tool: "project_mcp_call", arguments: { server: "fixture", tool: "echo", arguments: { name: { $ref: "input.name" } } } },
+ { id: "second", tool: "project_mcp_call", arguments: { server: "fixture", tool: "echo", arguments: { previous: { $ref: "steps.first.echo" } } }, expect: { path: "ok", equals: true } },
+] });
+afterAll(() => rm(directory, { recursive: true, force: true }));
+
+describe("reusable project flows", () => {
+ it("runs ordered references once, binds project, rejects replay changes and isolates owners", async () => {
+ const calls: Record<string, unknown>[] = [];
+ const tool: CapabilityTool = { name: "project_mcp_call", scope: "exec", description: "fixture", inputSchema: { type: "object", properties: {} },
+ run: async args => { calls.push(args); return { ok: true, echo: "hello" }; } };
+ const first = await startFlow(flow, "project-a", { name: "hello" }, "once", context, () => tool);
+ const done = await flowStatus(first.id, context, 5000);
+ expect(done.state).toBe("completed"); expect(calls).toHaveLength(2);
+ expect(calls[0].project).toBe("project-a"); expect(calls[1].arguments).toEqual({ previous: "hello" });
+ expect((await startFlow(flow, "project-a", { name: "hello" }, "once", context, () => tool)).id).toBe(first.id);
+ expect(calls).toHaveLength(2);
+ await expect(startFlow(flow, "project-a", { name: "different" }, "once", context, () => tool)).rejects.toThrow("different flow");
+ await expect(flowStatus(first.id, { ...context, principal: "another-owner" })).rejects.toThrow("not found");
+ });
+ it("stops after an error and retains the receipt across a simulated process exit", async () => {
+ let calls = 0;
+ const tool: CapabilityTool = { name: "project_mcp_call", scope: "exec", description: "fixture", inputSchema: { type: "object", properties: {} }, run: async () => { calls++; throw new Error("provider rejected"); } };
+ const started = await startFlow(flow, "project-a", { name: "hello" }, "failure", context, () => tool);
+ expect((await flowStatus(started.id, context, 5000)).state).toBe("failed"); expect(calls).toBe(1);
+ const run = (await readFlowRun(flowOwner(context.principal), started.id))!;
+ run.state = "running"; run.pid = 2147483647; run.instance = "old-process"; await writeFlowRun(run);
+ expect((await flowStatus(started.id, context)).state).toBe("interrupted");
+ expect(calls).toBe(1);
+ });
+ it("rejects missing inputs, raw shell, secret fields, prototype paths and insufficient grants", async () => {
+ expect(() => flowInputs(flow, {})).toThrow("missing input.name");
+ expect(() => flowInputs(flow, { name: "a", token: "secret" })).toThrow("secret_input");
+ expect(() => parseFlow({ ...flow, steps: [{ id: "bad", tool: "exec_run", arguments: { command: "echo x" } }] })).toThrow("invalid");
+ expect(() => bindFlowValue({ $ref: "input.__proto__" }, { input: {} })).toThrow("invalid flow reference");
+ await expect(startFlow(flow, "project-a", { name: "a" }, "denied", { ...context, allowedTools: ["flow_run"] }, () => ({ name: "project_mcp_call", scope: "exec" } as CapabilityTool))).rejects.toThrow("not permitted");
+ });
+});
diff --git a/lib/workflow/contention.ts b/lib/workflow/contention.ts
index af0802f2..74aee4d0 100644
--- a/lib/workflow/contention.ts
+++ b/lib/workflow/contention.ts
@@ -38,7 +38,7 @@ export async function summarizeProjectContention(
if (conflict) conflictingWorkflowCount += 1;
}
}
- if (changed) await persistWorkflowStore(store);
+ if (changed) await persistWorkflowStore(store, true);
return {
activeWorkflowCount, conflictingWorkflowCount,
overlappingPaths: [...overlappingPaths].slice(0, 80),
diff --git a/lib/workflow/lifecycle.ts b/lib/workflow/lifecycle.ts
index 0088e897..89cd8c73 100644
--- a/lib/workflow/lifecycle.ts
+++ b/lib/workflow/lifecycle.ts
@@ -33,7 +33,7 @@ export async function startWorkflow(input: {
startedAt: new Date().toISOString(), steps: [],
};
(store.active[actor] ??= {})[workflow.id] = workflow;
- await persistWorkflowStore(store);
+ await persistWorkflowStore(store, true);
return { workflow, activeWorkflowCount: Object.keys(store.active[actor]).length };
}
@@ -43,7 +43,7 @@ export async function activeWorkflowForActor(actor?: string, workflowId?: string
const changed = pruneStaleWorkflows(store, actor);
const bucket = store.active[actor];
const workflow = workflowId ? bucket?.[workflowId] ?? null : (bucket && Object.keys(bucket).length === 1 ? Object.values(bucket)[0] : null);
- if (changed) await persistWorkflowStore(store);
+ if (changed) await persistWorkflowStore(store, true);
return workflow;
}
@@ -56,7 +56,7 @@ export async function recordWorkflowStep(actor: string | undefined, workflowId:
if (!sanitized) return;
workflow.steps.push(sanitized);
if (workflow.steps.length > 300) workflow.steps.splice(0, workflow.steps.length - 300);
- await persistWorkflowStore(store);
+ await persistWorkflowStore(store, true);
}
export async function cancelWorkflow(input: { actor?: string; workflowId: string; reason?: string }): Promise<CancelWorkflowResult> {
@@ -65,7 +65,7 @@ export async function cancelWorkflow(input: { actor?: string; workflowId: string
const workflow = workflowFor(store, actor, input.workflowId);
if (!workflow) throw new Error("workflow_id was not found for this MSO session");
removeActiveWorkflow(store, actor, input.workflowId);
- await persistWorkflowStore(store);
+ await persistWorkflowStore(store, true);
const reason = input.reason ? safeMemoryText(input.reason, 500) || undefined : undefined;
return { workflow, ...(reason ? { reason } : {}) };
}
diff --git a/lib/workflow/storage-checkpoint.test.ts b/lib/workflow/storage-checkpoint.test.ts
new file mode 100644
index 00000000..e73973ca
--- /dev/null
+++ b/lib/workflow/storage-checkpoint.test.ts
@@ -0,0 +1,23 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { loadWorkflowStore, persistWorkflowStore, resetWorkflowStoreCache } from "./storage";
+let root = "";
+afterEach(async () => { resetWorkflowStoreCache(); vi.unstubAllEnvs(); if (root) await fs.rm(root, { recursive: true, force: true }); });
+it("checkpoints active state without rewriting recipes and recovers after restart/base replacement", async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-workflow-checkpoint-"));
+ const file = path.join(root, "memory.json"); vi.stubEnv("OS_SKILL_MEMORY_STORE", file);
+ const store = await loadWorkflowStore(); await persistWorkflowStore(store);
+ const base = await fs.readFile(file, "utf8");
+ await persistWorkflowStore(store, true);
+ expect(await fs.readFile(file, "utf8")).toBe(base);
+ expect((await fs.stat(file + ".active.json")).mode & 0o777).toBe(0o600);
+ resetWorkflowStoreCache(); expect(await loadWorkflowStore()).toEqual(store);
+ await persistWorkflowStore(store);
+ expect(await fs.stat(file + ".active.json").catch(() => null)).toBeNull();
+ const current = await fs.readFile(file, "utf8");
+ await fs.writeFile(file + ".active.json", JSON.stringify({ version: 1, baseSnapshot: JSON.parse(base).snapshotId, active: { stale: {} } }));
+ resetWorkflowStoreCache(); expect((await loadWorkflowStore()).active).toEqual({});
+ expect(current).not.toBe(base);
+});
diff --git a/lib/workflow/storage.ts b/lib/workflow/storage.ts
index 1f3bc4e3..0616e1bd 100644
--- a/lib/workflow/storage.ts
+++ b/lib/workflow/storage.ts
@@ -1,71 +1,65 @@
-// Host-owned runtime data is not a build asset; tracing exclusions preserve runtime guards.
+// One runtime process owns this in-memory store; active checkpoints avoid rewriting recipes.
import { promises as fs } from "node:fs";
+import { createHash, randomUUID } from "node:crypto";
import os from "node:os";
import path from "node:path";
import { normalizeActive, normalizeRecipes } from "./sanitize";
import type { WorkflowStoreState } from "./types";
-
const EMPTY = (): WorkflowStoreState => ({ version: 3, active: {}, recipes: {} });
-let cache: WorkflowStoreState | null = null;
-let cachePath = "";
+let cache: WorkflowStoreState | null = null, cachePath = "", baseSnapshot = "";
+let needsMigration = false;
const loadInFlight = new Map<string, Promise<WorkflowStoreState>>();
let writeChain: Promise<unknown> = Promise.resolve();
-
function storePath(): string {
const env = process.env.OS_SKILL_MEMORY_STORE?.trim();
if (process.env.VITEST && !env) return path.join(os.tmpdir(), `mso-skill-memory-test-${process.pid}.json`);
return (env || path.join(os.homedir(), ".mso", "skill-memory.json")).replace(/^~(?=$|\/)/, os.homedir());
}
-
-/** The only module that reads/writes the workflow/recipe persistence file. */
+function legacySnapshot(raw: string) { return "legacy:" + createHash("sha256").update(raw).digest("hex"); }
+/** The base file remains a complete version-3 snapshot. Matching sidecar supersedes only active state. */
export async function loadWorkflowStore(): Promise<WorkflowStoreState> {
const file = storePath();
if (cache && cachePath === file) return cache;
- const current = loadInFlight.get(file);
- if (current) return current;
-
+ const current = loadInFlight.get(file); if (current) return current;
const pending = (async () => {
let raw: string;
- try {
- raw = await fs.readFile(/* turbopackIgnore: true */ file, "utf8");
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
- cache = EMPTY();
- cachePath = file;
- return cache;
- }
- throw error;
+ try { raw = await fs.readFile(/* turbopackIgnore: true */ file, "utf8"); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ cache = EMPTY(); cachePath = file; baseSnapshot = ""; return cache;
}
- const parsed = JSON.parse(raw) as { active?: unknown; recipes?: unknown };
+ const parsed = JSON.parse(raw) as { active?: unknown; recipes?: unknown; snapshotId?: string; version?: number };
+ baseSnapshot = parsed.snapshotId ?? legacySnapshot(raw); needsMigration = parsed.version !== 3;
cache = { version: 3, active: normalizeActive(parsed.active), recipes: normalizeRecipes(parsed.recipes) };
- cachePath = file;
- return cache;
+ try {
+ const overlay = JSON.parse(await fs.readFile(/* turbopackIgnore: true */ file + ".active.json", "utf8"));
+ if (overlay.version === 1 && overlay.baseSnapshot === baseSnapshot) cache.active = normalizeActive(overlay.active);
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
+ cachePath = file; return cache;
})();
loadInFlight.set(file, pending);
+ try { return await pending; } finally { if (loadInFlight.get(file) === pending) loadInFlight.delete(file); }
+}
+async function atomic(file: string, snapshot: string) {
+ const tmp = file + "." + randomUUID() + ".tmp";
try {
- return await pending;
- } finally {
- if (loadInFlight.get(file) === pending) loadInFlight.delete(file);
- }
+ await fs.writeFile(tmp, snapshot, { encoding: "utf8", mode: 0o600, flag: "wx" });
+ await fs.rename(tmp, file);
+ } finally { await fs.unlink(tmp).catch(() => undefined); }
}
-
-export async function persistWorkflowStore(store: WorkflowStoreState): Promise<void> {
- const file = storePath();
- const snapshot = JSON.stringify(store, null, 2);
+export async function persistWorkflowStore(store: WorkflowStoreState, activeOnly = false): Promise<void> {
+ const file = storePath(), partial = activeOnly && Boolean(baseSnapshot) && !needsMigration;
+ // Capture bytes now, before callers mutate the shared object again.
+ if (!partial) { baseSnapshot = randomUUID(); needsMigration = false; }
+ const snapshot = partial ? JSON.stringify({ version: 1, baseSnapshot, active: store.active }) : JSON.stringify({ ...store, snapshotId: baseSnapshot });
const run = writeChain.then(async () => {
await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
- const tmp = `${file}.tmp`;
- await fs.writeFile(tmp, snapshot, { encoding: "utf8", mode: 0o600 });
- await fs.rename(tmp, file);
+ await atomic(partial ? file + ".active.json" : file, snapshot);
+ if (!partial) await fs.unlink(file + ".active.json").catch((e: NodeJS.ErrnoException) => { if (e.code !== "ENOENT") throw e; });
});
- writeChain = run.catch(() => undefined);
- await run;
+ writeChain = run.catch(() => undefined); await run;
}
-
-/** Test-only cache reset; public compatibility maps the historical name. */
+/** Test-only cache reset. */
export function resetWorkflowStoreCache(): void {
- cache = null;
- cachePath = "";
- loadInFlight.clear();
- writeChain = Promise.resolve();
+ cache = null; cachePath = ""; baseSnapshot = ""; loadInFlight.clear(); writeChain = Promise.resolve();
}
diff --git a/scripts/bench-cognitive-runtime.mjs b/scripts/bench-cognitive-runtime.mjs
index ef55e33f..06f69a4d 100755
--- a/scripts/bench-cognitive-runtime.mjs
+++ b/scripts/bench-cognitive-runtime.mjs
@@ -9,6 +9,9 @@ mock.module("server-only", () => ({}));
const { TOOLS } = await import("../lib/mcp/tools.ts");
const scenarios = [
+ { id: "automation-flow", prompt: "Run a repeatable automation flow for my project through provider APIs and MCP.", required: ["flow_catalog", "flow_run", "flow_status"] },
+ { id: "project-add-mcp", prompt: "Add MCP to this project.", required: ["project_mcp_manage"] },
+ { id: "project-asset", prompt: "Attach a generated image asset to the project.", required: ["project_asset_attach", "session_artifacts"] },
{ id: "app-logs", prompt: "Hermes is down. Check managed app state and inspect its recent logs.", required: ["apps_list", "apps_logs"] },
{ id: "server-health", prompt: "How is the VPS doing? Check cpu, ram, disk and top processes.", required: ["sys_stats", "sys_processes"] },
{ id: "safe-edit", prompt: "Inspect README then safely update that file without overwriting concurrent changes.", required: ["fs_read", "fs_write"] },
diff --git a/scripts/check-mcp-budgets.mjs b/scripts/check-mcp-budgets.mjs
new file mode 100644
index 00000000..a81fb431
--- /dev/null
+++ b/scripts/check-mcp-budgets.mjs
@@ -0,0 +1,5 @@
+#!/usr/bin/env node
+// Repeatable release check; byte counts are not tokenizer counts.
+import { spawnSync } from "node:child_process";
+const run = spawnSync("bun", ["run", "test", "lib/mcp/client-budgets.test.ts", "lib/mcp/chatgpt-profile.test.ts"], { stdio: "inherit", env: { ...process.env, MSO_PROFILE_METRICS: "1" } });
+process.exit(run.status ?? 1);
diff --git a/scripts/cli/commands-admin.sh b/scripts/cli/commands-admin.sh
index 36b4c3d5..b6341fad 100755
--- a/scripts/cli/commands-admin.sh
+++ b/scripts/cli/commands-admin.sh
@@ -38,6 +38,7 @@ case "$cmd" in
mcp)
case "${1:-list}" in
list) jget "/api/mcp/tokens" ;;
+ project) jpost "/api/v1/project-mcp" "${2:?project MCP JSON required}" ;;
activity) jget "/api/mcp/activity?limit=${2:-80}" ;;
service-token) bun "$ROOT/scripts/mcp-service-token.ts" "${@:2}" ;;
revoke) [ -n "${2-}" ] || die "usage: mso mcp revoke <id|all> (ids: mso mcp list)"
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
index 43c7a583..a1df26ec 100755
--- a/scripts/cli/commands-runtime.sh
+++ b/scripts/cli/commands-runtime.sh
@@ -10,6 +10,7 @@ case "$cmd" in
setup) run_onboard "${1-}" ;;
onboard) run_onboard "${1-}" ;;
integrations) run_integrations "$@" ;;
+ flow) source "$ROOT/scripts/cli/flows.sh"; run_flow "$@" ;;
provider|providers) run_provider "$@" ;;
# ── local/public gateway + browser launcher ───────────────────────────────
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 2787d568..36106f2d 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -24,6 +24,7 @@ verbs() {
U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
U_doctor="doctor [--fix]"
+U_flow="flow list|inspect <id> [--project <project>]|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|save|delete <id> --revision <revision> [--input <JSON|@file>]"
U_integrations="integrations [interactive]|transfer|status|users|catalog|connections [user] [provider]|which [folder]|request|resolve <user> <provider> [connection]|create-user <id> [label]|create-connection <user> <provider> <id> <source> <auth>|manage <JSON>|setup|verify <user> <provider> <connection>|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute <JSON>"
U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"
U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
@@ -46,7 +47,7 @@ U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm
U_prefs="prefs show|set <json>"
U_models="models [status|list|add|auth <provider>|rm <provider>|catalog [provider]|test]"
U_skills="skills list|read <id>|search <query…>|available|info <id>|install <id…> [-y] [--force]|remove <id…> [-y]"
-U_mcp="mcp list|activity [n]|service-token --label <label> --client-id <id> --scope <read|write|exec> --tools <name,name> [--constraints-json <json>]|revoke <id>|revoke all"
+U_mcp="mcp project <JSON>|list|activity [n]|service-token --label <label> --client-id <id> --scope <read|write|exec> --tools <name,name> [--constraints-json <json>]|revoke <id>|revoke all"
U_oauth="oauth <provider> start|poll OAuth currently: openai (ChatGPT Codex)"
# Command families are sourced here so bin/mso remains only bootstrap + entrypoint.
# shellcheck source=commands-host.sh
@@ -90,7 +91,7 @@ mso_cli_main() {
case "$cmd" in
version|--version|-V|-v|ls|cat|raw|share|usage|search|write|mkdir|rm|mv|cp|zip|upload|exec|stats|ps|units|unit|packages|cleanup|status|health|doctor)
mso_cmd_host "$cmd" "$@" ;;
- agent|chat|model|setup|onboard|provider|providers|integrations|gateway|web|camoufox|apps|mapp|term)
+ agent|chat|model|setup|onboard|provider|providers|integrations|flow|gateway|web|camoufox|apps|mapp|term)
mso_cmd_runtime "$cmd" "$@" ;;
ai|cockpit|threads|agent-sessions|agents|a2a|memory|config|prefs|models|skills|changelog|stock)
mso_cmd_state "$cmd" "$@" ;;
diff --git a/scripts/cli/flows.sh b/scripts/cli/flows.sh
new file mode 100644
index 00000000..3b4154c5
--- /dev/null
+++ b/scripts/cli/flows.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+# Flows share the owner API/capability kernel used by MCP.
+run_flow() {
+ local sub="${1:-list}" id="" project="$PWD" input='{}' key="" wait=0 revision="" body result
+ shift || true
+ case "$sub" in inspect|run|status|save|delete) id="${1:?flow/run id required}"; shift ;; esac
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --project) project="${2:?project required}"; shift 2 ;;
+ --input) input="${2:?JSON or @file required}"; shift 2 ;;
+ --key) key="${2:?idempotency key required}"; shift 2 ;;
+ --revision) revision="${2:?revision required}"; shift 2 ;;
+ --wait) wait=1; shift ;;
+ *) die "unknown flow option: $1" ;;
+ esac
+ done
+ case "$input" in @*) input=$(cat -- "${input#@}") ;; esac
+ case "$sub" in
+ list|inspect) jget "/api/v1/flows?project=$(enc "$project")&flow=$(enc "$id")"; return ;;
+ status) result=$(jget "/api/v1/flows?run_id=$(enc "$id")&wait_ms=$((wait * 25000))") ;;
+ run)
+ [ -n "$key" ] || die "flow run requires --key <unique-operation-id>; retries must reuse it"
+ body=$(jq -n --arg project "$project" --arg flow "$id" --arg key "$key" --argjson input "$input" '{action:"run",project:$project,flow:$flow,input:$input,idempotency_key:$key}')
+ result=$(jpost "/api/v1/flows" "$body"); id=$(jq -er .id <<<"$result") ;;
+ save|delete)
+ [ -n "$revision" ] || die "use --revision from mso flow list (new for absent manifest)"
+ local action=upsert; [ "$sub" = delete ] && action=delete
+ body=$(jq -n --arg action "$action" --arg project "$project" --arg flow "$id" --arg revision "$revision" --argjson definition "$input" '{action:$action,project:$project,flow:$flow,revision:$revision,definition:$definition}')
+ jpost "/api/v1/flows" "$body"; return ;;
+ *) die "usage: mso $U_flow" ;;
+ esac
+ while [ "$wait" -eq 1 ] && [ "$(jq -r .state <<<"$result")" = running ]; do
+ result=$(jget "/api/v1/flows?run_id=$(enc "$id")&wait_ms=25000")
+ done
+ printf '%s\n' "$result"
+ case "$(jq -r .state <<<"$result")" in failed|interrupted) return 1 ;; esac
+}
diff --git a/scripts/cli/flows.test.ts b/scripts/cli/flows.test.ts
new file mode 100644
index 00000000..d76aff68
--- /dev/null
+++ b/scripts/cli/flows.test.ts
@@ -0,0 +1,15 @@
+import { execFileSync } from "node:child_process";
+import { expect, it } from "vitest";
+it("runs a quoted JSON flow through the shared API and waits for its receipt", () => {
+ const script = `
+set -euo pipefail
+source scripts/cli/flows.sh
+die(){ echo "$*" >&2; exit 2; }
+enc(){ printf '%s' "$1"; }
+jpost(){ [ "$1" = /api/v1/flows ]; jq -e '.project=="project one" and .flow=="custom.echo" and .input.message=="hello world" and .idempotency_key=="once-1"' <<<"$2" >/dev/null; printf '{"id":"abc","state":"running"}'; }
+jget(){ [ "$1" = '/api/v1/flows?run_id=abc&wait_ms=25000' ]; printf '{"id":"abc","state":"completed"}'; }
+run_flow run custom.echo --project "project one" --input '{"message":"hello world"}' --key once-1 --wait
+`;
+ expect(JSON.parse(execFileSync("bash", ["-c", script], { encoding: "utf8" }))).toMatchObject({ id: "abc", state: "completed" });
+ expect(() => execFileSync("bash", ["-c", script.replace("--key once-1", "")], { encoding: "utf8", stdio: "pipe" })).toThrow();
+});
diff --git a/scripts/e2e/automation.mjs b/scripts/e2e/automation.mjs
new file mode 100644
index 00000000..56324261
--- /dev/null
+++ b/scripts/e2e/automation.mjs
@@ -0,0 +1,72 @@
+import { mkdir, writeFile, readFile, chmod } from "node:fs/promises";
+import { execFileSync } from "node:child_process";
+import path from "node:path";
+import { expect } from "@playwright/test";
+
+export async function automationJourney(page, fixture) {
+ await fixture.seedMcp("exec");
+ const meta = {"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}};
+ const rpc = async (method, params = {}) => {
+ const response = await fetch(fixture.base+"/mcp", {method:"POST",headers:{authorization:"Bearer "+fixture.mcpToken,"content-type":"application/json","MCP-Protocol-Version":"2026-07-28","Mcp-Method":method,...(params.name?{"Mcp-Name":params.name}:{})},body:JSON.stringify({jsonrpc:"2.0",id:1,method,params:{...params,_meta:{...meta,...params._meta}}})});
+ return {status:response.status,session:response.headers.get("Mcp-Session-Id"),body:await response.json()};
+ };
+ const discovered = await rpc("server/discover");
+ expect(discovered.status).toBe(200); expect(discovered.session).toBeNull();
+ expect(discovered.body.result.resultType).toBe("complete");
+ expect((await rpc("method/unknown")).status).toBe(404);
+ const opened = await rpc("tools/call",{name:"agent_session_open",arguments:{conversation_key:"release-modern"}});
+ expect(opened.status).toBe(200); expect(opened.body.result.isError).not.toBe(true);
+ expect(opened.body.result.resultType).toBe("complete");
+ const project = path.join(fixture.dir, "automation-project");
+ await mkdir(project, { mode: 0o700 });
+ const script = path.join(project, "fixture.cjs");
+ await writeFile(script, `require("node:readline").createInterface({input:process.stdin}).on("line",line=>{
+ const r=JSON.parse(line);if(r.id===undefined)return;
+ const result=r.method==="initialize"?{protocolVersion:"2025-11-25",capabilities:{tools:{}},serverInfo:{name:"fixture",version:"1"}}:
+ r.method==="tools/list"?{tools:[{name:"echo",inputSchema:{type:"object",properties:{message:{type:"string"}}}}]}:
+ {content:[{type:"text",text:"echo"}],structuredContent:{message:r.params.arguments.message}};
+ process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:r.id,result})+"\\n");
+ });`);
+ await writeFile(path.join(project, ".mcp.json"), JSON.stringify({mcpServers:{fixture:{command:process.execPath,args:[script]}}}), { mode: 0o600 });
+ const call = (route, body) => page.evaluate(async ([route,body]) => {
+ const response = await fetch(route, body ? {method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(body)} : {});
+ return {status:response.status,body:await response.json()};
+ }, [route,body]);
+ await page.goto(fixture.base + "/integrations");
+ await page.getByRole("button", {name:"Add MCP",exact:true}).click();
+ await page.getByLabel("Project id or path").fill(project);
+ await page.getByLabel("Server alias", {exact:true}).fill("public-fixture");
+ await page.getByLabel("HTTPS MCP endpoint").fill("https://example.com/mcp");
+ if (process.env.MSO_SCREENSHOT_DIR) {
+ const screenshot = path.join(process.env.MSO_SCREENSHOT_DIR, "add-project-mcp.png");
+ await page.screenshot({path:screenshot}); await chmod(screenshot,0o600);
+ }
+ await page.getByRole("button", {name:"Add MCP",exact:true}).last().click();
+ await expect(page.getByRole("status")).toContainText("MCP added to");
+ const config = JSON.parse(await readFile(path.join(project,".mcp.json"),"utf8"));
+ expect(Object.keys(config.mcpServers).sort()).toEqual(["fixture","public-fixture"]);
+ const catalog = await call("/api/v1/flows?project="+encodeURIComponent(project));
+ expect(catalog.status).toBe(200);
+ const definition = {id:"fixture.echo",description:"Echo a supplied message through the project MCP.",inputs:{message:{type:"string",description:"Message to echo",required:true}},steps:[{id:"echo",tool:"project_mcp_call",arguments:{server:"fixture",tool:"echo",arguments:{message:{$ref:"input.message"}}}}]};
+ const saved = await call("/api/v1/flows",{action:"upsert",project,flow:definition.id,definition,revision:catalog.body.revision});
+ expect(saved.status).toBe(200);
+ const input = {action:"run",project,flow:definition.id,input:{message:"verified flow ✓"},idempotency_key:"release-fixture-echo"};
+ const run = await call("/api/v1/flows",input);
+ expect(run.status).toBe(200);
+ const receipt = run.body.result ?? run.body;
+ expect(receipt.id).toBeTruthy();
+ const finished = await call("/api/v1/flows?run_id="+receipt.id+"&wait_ms=25000");
+ expect(finished.status).toBe(200);
+ expect(finished.body.state).toBe("completed");
+ expect(JSON.stringify(finished.body)).toContain("verified flow ✓");
+ const duplicate = await call("/api/v1/flows",input);
+ expect((duplicate.body.result ?? duplicate.body).id).toBe(receipt.id);
+ const cli = execFileSync("bash", ["bin/mso","--base",fixture.base,"flow","run",definition.id,"--project",project,"--input",JSON.stringify({message:"CLI verified"}),"--key","release-cli","--wait"],{encoding:"utf8",timeout:30000,env:{...process.env,MSO_PASSWORD:fixture.password,MSO_DEVICE:fixture.device,MSO_PRIVATE_STATE_DIR:path.join(fixture.dir,"cli-private")}});
+ expect(JSON.parse(cli).state).toBe("completed");
+ expect(cli).toContain("CLI verified");
+ const current = await call("/api/v1/flows?project="+encodeURIComponent(project));
+ expect((await call("/api/v1/flows",{action:"delete",project,flow:definition.id,revision:current.body.revision})).status).toBe(200);
+ const binding = await call("/api/v1/project-mcp",{action:"inspect",project});
+ expect((await call("/api/v1/project-mcp",{action:"delete",project,server:"public-fixture",revision:binding.body.revision})).status).toBe(200);
+ console.log("PASS Add MCP, preserved binding, project flow CRUD, execution, Unicode result and idempotent replay");
+}
diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjs
index a8280692..252512f0 100644
--- a/scripts/e2e/release-fixture.mjs
+++ b/scripts/e2e/release-fixture.mjs
@@ -3,7 +3,7 @@ import { mkdtemp, writeFile, rm, readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { createServer } from "node:http";
-import { randomUUID, randomBytes } from "node:crypto";
+import { createHash, randomUUID, randomBytes } from "node:crypto";
import { spawn } from "node:child_process";
export async function releaseFixture({ live = false } = {}) {
@@ -42,9 +42,10 @@ export async function releaseFixture({ live = false } = {}) {
OS_SESSION_SECRET: randomBytes(32).toString("hex"), OS_FS_READ_ROOTS: dir, OS_FS_WRITE_ROOTS: dir,
OS_MCP_ENABLED: "1", NEXT_PUBLIC_OS_DEMO: "0", NEXT_TELEMETRY_DISABLED: "1",
});
- const seedMcp = async () => {
+ const mcpToken = randomBytes(32).toString("hex");
+ const seedMcp = async (scope = "read") => {
await writeFile(env.OS_MCP_STORE, JSON.stringify({ clients: {}, codes: {}, refreshTokens: {}, tokens: {
- ["a".repeat(64)]: { label: "Fixture client", clientId: "fixture-client", scope: "read", createdAt: Date.now(), expiresAt: Date.now() + 3600_000 },
+ [createHash("sha256").update(mcpToken).digest("hex")]: { label: "Fixture client", clientId: "fixture-client", scope, createdAt: Date.now(), expiresAt: Date.now() + 3600_000 },
} }), { mode: 0o600 });
};
await seedMcp();
@@ -74,6 +75,6 @@ export async function releaseFixture({ live = false } = {}) {
await new Promise(resolve => setTimeout(resolve, 250));
}
if (!ready) throw new Error("Fixture server did not become ready: " + logs);
- return { dir, base, device, password, setRole, seedMcp, seedSessions: () => seedSessionMonitor(env), revokeProvider: () => { providerStatus = 401; }, close };
+ return { dir, base, device, password, setRole, seedMcp, mcpToken, seedSessions: () => seedSessionMonitor(env), revokeProvider: () => { providerStatus = 401; }, close };
} catch (error) { await close(); throw error; }
}
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index 22a5a17f..813e8971 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -4,6 +4,7 @@ import { execFileSync } from "node:child_process";
import { chromium, expect } from "@playwright/test";
import AxeBuilder from "@axe-core/playwright";
import { mcpOwnerJourneys, mcpPublicJourney, settingsAccessibilityJourney } from "./mcp-settings.mjs";
+import { automationJourney } from "./automation.mjs";
import { releaseFixture } from "./release-fixture.mjs";
const fixture = await releaseFixture();
@@ -88,6 +89,7 @@ try {
expect((await call("/api/v1/exec/run", { cmd: "exit 0", cwd: fixture.dir + "/missing" })).status).not.toBe(200);
expect((await call("/api/v1/fs/list?path=" + encodeURIComponent(fixture.dir))).status).toBe(200);
await mcpOwnerJourneys(page, fixture);
+ await automationJourney(page, fixture);
await fixture.setRole("viewer");
expect((await call("/api/v1/agent-sessions?view=monitor")).status).toBe(403);
expect((await call("/api/v1/integrations")).status).toBe(403);
diff --git a/scripts/mso-agent-tool-router.mjs b/scripts/mso-agent-tool-router.mjs
index bddab67a..5a50e5fa 100644
--- a/scripts/mso-agent-tool-router.mjs
+++ b/scripts/mso-agent-tool-router.mjs
@@ -4,6 +4,9 @@ export const MAX_ACTIVE_TOOLS = 10;
const FALLBACK_TOOL_LIMIT = 3;
const DEPENDENCIES = new Map([
+ ["flow_run", ["flow_catalog", "flow_status"]],
+ ["project_asset_attach", ["session_artifacts"]],
+ ["project_mcp_call", ["project_mcp_tools"]],
["apps_logs", ["apps_list"]],
["apps_power", ["apps_list"]],
["project_function_call", ["project_capabilities"]],
@@ -22,6 +25,8 @@ const DEPENDENCIES = new Map([
]);
const LIFECYCLE = new Map([
+ ["flow_catalog", ["flow_run", "flow_status"]],
+ ["flow_run", ["flow_status"]],
["workflow_start", ["workflow_finish", "workflow_cancel", "skills_read", "project_script_run"]],
["exec_job_start", ["exec_job_status", "exec_job_cancel"]],
["skills_search", ["skills_read"]],