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): preserve restricted project service bridge

rahmanef63b6f5224c1643
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index ba14b1df..cfb9a317 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -90,7 +90,14 @@ export async function POST(req: Request) {
void touchToken(token.hash).catch(() => {});
const actor = `mcp:${token.hash.slice(0, 16)}`;
- const agentContext = { principal, ...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}), toolProfile, capabilities: msoCapabilityRuntime };
+ const agentContext = {
+ principal,
+ ...(resolved.agentSessionId ? { sessionId: resolved.agentSessionId } : {}),
+ toolProfile,
+ ...(token.allowedTools ? { allowedTools: token.allowedTools } : {}),
+ ...(token.toolArgumentConstraints ? { toolArgumentConstraints: token.toolArgumentConstraints } : {}),
+ capabilities: msoCapabilityRuntime,
+ };
const result = await dispatch(rpc, effectiveScope, actor, agentContext);
return Response.json(result, { status: 200, headers });
}
diff --git a/lib/mcp/dispatch-tools.ts b/lib/mcp/dispatch-tools.ts
index 41de10db..1b28d7e4 100644
--- a/lib/mcp/dispatch-tools.ts
+++ b/lib/mcp/dispatch-tools.ts
@@ -1,4 +1,5 @@
import { executeCapabilityCall } from "@/lib/capabilities/execute";
+import { audit } from "@/lib/host/audit-api";
import type { Scope } from "./scope";
import { TOOLS_BY_NAME } from "./tools";
import { toolAllowedForProfile } from "./tool-contract";
@@ -10,7 +11,19 @@ export async function dispatchToolCall(req: RpcRequest, scope: Scope, actor?: st
const name = String(req.params?.name ?? ""), args = req.params?.arguments ?? {};
const tool = TOOLS_BY_NAME.get(name);
const profile = context?.toolProfile ?? "full";
- if (!tool || !toolAllowedForProfile(name, profile)) return rpcFail(id, -32602, `unknown tool: ${name}`);
+ const allowedTools = context?.allowedTools;
+ if (!tool || !toolAllowedForProfile(name, profile) || (allowedTools && !allowedTools.includes(name))) {
+ if (tool && allowedTools && !allowedTools.includes(name)) void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: "token tool allowlist" });
+ return rpcFail(id, -32602, `unknown tool: ${name}`);
+ }
+ const constraints = context?.toolArgumentConstraints?.[name];
+ if (constraints) {
+ const denied = Object.entries(constraints).find(([key, allowed]) => typeof args[key] !== "string" || !allowed.includes(args[key] as string));
+ if (denied) {
+ void audit({ action: "mcp.denied", actor, target: name, ok: false, detail: `token argument constraint: ${denied[0]}` });
+ return rpcFail(id, -32602, `tool input is not allowed for this token: ${denied[0]}`);
+ }
+ }
const outcome = await executeCapabilityCall({ tool, args, scope, actor, context });
if (outcome.kind === "protocol_error") return rpcFail(id, outcome.code, outcome.message);
if (outcome.kind === "error") return rpcOk(id, { content: [{ type: "text", text: outcome.message }], isError: true });
diff --git a/lib/mcp/dispatch-types.ts b/lib/mcp/dispatch-types.ts
index 505d5375..0039fde2 100644
--- a/lib/mcp/dispatch-types.ts
+++ b/lib/mcp/dispatch-types.ts
@@ -20,6 +20,8 @@ export interface McpAgentContext {
principal?: string;
sessionId?: string;
toolProfile?: McpToolProfile;
+ allowedTools?: readonly string[];
+ toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>;
capabilities?: CapabilityRuntime;
}
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index d1446a33..d1b2274f 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -82,6 +82,28 @@ describe("protocol", () => {
});
});
+describe("restricted service-token dispatch", () => {
+ const context = {
+ allowedTools: ["project_capabilities", "project_function_call"],
+ toolArgumentConstraints: { project_function_call: { project: ["antinrml-game"], name: ["capture_scene"] } },
+ } as const;
+
+ it("filters list-time and call-time capability exposure", async () => {
+ const listed = await dispatch({ id: 80, method: "tools/list" }, "exec", "mcp:service", context);
+ const names = ((listed.result as { tools: Array<{ name: string }> }).tools ?? []).map((row) => row.name);
+ expect(names).toEqual(["project_capabilities", "project_function_call"]);
+ const denied = await dispatch(call("exec_run", { command: "id" }), "exec", "mcp:service", context);
+ expect(denied.error).toMatchObject({ code: -32602 });
+ });
+
+ it("pins exact string arguments for the allowed project function", async () => {
+ const wrongProject = await dispatch(call("project_function_call", { project: "mso", name: "capture_scene", input: {} }), "exec", "mcp:service", context);
+ expect(wrongProject.error).toMatchObject({ code: -32602 });
+ const wrongFunction = await dispatch(call("project_function_call", { project: "antinrml-game", name: "dangerous_write", input: {} }), "exec", "mcp:service", context);
+ expect(wrongFunction.error).toMatchObject({ code: -32602 });
+ });
+});
+
describe("tools/list is scope-filtered", () => {
const names = async (scope: "read" | "write" | "exec") => {
const r = await dispatch({ id: 1, method: "tools/list" }, scope);
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
index 59384fbc..deffc66c 100644
--- a/lib/mcp/dispatch.ts
+++ b/lib/mcp/dispatch.ts
@@ -17,13 +17,18 @@ export function isNotification(body: unknown): boolean {
return b?.id == null && String(b?.method ?? "").startsWith("notifications/");
}
-const visibleTools = (scope: Scope, profile: McpToolProfile = "full") => visibleToolsForProfile(TOOLS, scope, profile);
-const toolList = (scope: Scope, profile: McpToolProfile = "full") => visibleTools(scope, profile).map((tool) => toolDescriptor(tool, profile));
+const toolAllowed = (name: string, allowedTools?: readonly string[]) => !allowedTools || allowedTools.includes(name);
+const visibleTools = (scope: Scope, profile: McpToolProfile = "full", allowedTools?: readonly string[]) =>
+ visibleToolsForProfile(TOOLS, scope, profile).filter((tool) => toolAllowed(tool.name, allowedTools));
+const toolList = (scope: Scope, profile: McpToolProfile = "full", allowedTools?: readonly string[]) =>
+ visibleTools(scope, profile, allowedTools).map((tool) => toolDescriptor(tool, profile));
-function instructions(scope: Scope, profile: McpToolProfile = "full"): string {
- const startup = scope === "read"
- ? "This token is read-only: use skills_search for capability discovery, then bounded read tools."
- : "For multi-step work call workflow_start once, pass its exact workflow_id on every operation in this conversation, verify, then workflow_finish or workflow_cancel.";
+function instructions(scope: Scope, profile: McpToolProfile = "full", allowedTools?: readonly string[]): string {
+ const startup = allowedTools
+ ? `This machine token is restricted to: ${allowedTools.join(", ")}.`
+ : scope === "read"
+ ? "This token is read-only: use skills_search for capability discovery, then bounded read tools."
+ : "For multi-step work call workflow_start once, pass its exact workflow_id on every operation in this conversation, verify, then workflow_finish or workflow_cancel.";
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.`;
}
@@ -33,11 +38,12 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, ag
switch (req.method) {
case "initialize": {
const profile = agentContext?.toolProfile ?? "full";
- const tools = visibleTools(scope, profile), toolset = toolsetInfo(tools, scope, profile);
+ const allowedTools = agentContext?.allowedTools;
+ const tools = visibleTools(scope, profile, allowedTools), toolset = toolsetInfo(tools, scope, profile);
return rpcOk(id, {
protocolVersion: negotiateMcpProtocol(req.params?.protocolVersion),
capabilities: { tools: { listChanged: false }, resources: { listChanged: false }, extensions: { [MCP_SKILLS_EXTENSION]: {} } },
- serverInfo: { name: "mso", version: MCP_SERVER_VERSION }, instructions: instructions(scope, profile),
+ serverInfo: { name: "mso", version: MCP_SERVER_VERSION }, instructions: instructions(scope, profile, allowedTools),
_meta: { toolset, ...(agentContext?.sessionId ? { agentSessionId: agentContext.sessionId } : {}) },
});
}
@@ -45,8 +51,9 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, ag
case "ping": return rpcOk(id, {});
case "tools/list": {
const profile = agentContext?.toolProfile ?? "full";
- const tools = visibleTools(scope, profile);
- return rpcOk(id, { tools: toolList(scope, profile), _meta: { toolset: toolsetInfo(tools, scope, profile) } });
+ const allowedTools = agentContext?.allowedTools;
+ const tools = visibleTools(scope, profile, allowedTools);
+ return rpcOk(id, { tools: toolList(scope, profile, allowedTools), _meta: { toolset: toolsetInfo(tools, scope, profile) } });
}
case "resources/list": return rpcOk(id, { resources: listUiResources() });
case "resources/read": {
diff --git a/lib/mcp/project-function-content.ts b/lib/mcp/project-function-content.ts
new file mode 100644
index 00000000..a875607a
--- /dev/null
+++ b/lib/mcp/project-function-content.ts
@@ -0,0 +1,56 @@
+import { mcpDirect, type McpContent, type McpDirectResult } from "./tool-kit";
+
+export const PROJECT_FUNCTION_CONTENT_PROTOCOL = "mso.project-function-content.v1" as const;
+const MAX_DIRECT_IMAGE_BYTES = 620 * 1024;
+const MAX_DIRECT_TEXT_CHARS = 32 * 1024;
+const MAX_DIRECT_CONTENT = 4;
+const IMAGE_MIME = new Set(["image/png", "image/jpeg", "image/webp"]);
+
+type ProjectFunctionResult = { code: number; stdout: string; stderr: string };
+type DirectProjectFunctionResult = McpDirectResult & { code: number };
+
+const plainObject = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value && typeof value === "object" && !Array.isArray(value));
+
+function validSignature(bytes: Buffer, mimeType: string): boolean {
+ if (mimeType === "image/png") return bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]));
+ if (mimeType === "image/jpeg") return bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
+ return bytes.length >= 12 && bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
+}
+
+function parseContent(value: unknown): McpContent[] | null {
+ if (!plainObject(value) || value.protocol !== PROJECT_FUNCTION_CONTENT_PROTOCOL || !Array.isArray(value.content)) return null;
+ if (value.content.length === 0 || value.content.length > MAX_DIRECT_CONTENT) return null;
+ let images = 0;
+ const content: McpContent[] = [];
+ for (const row of value.content) {
+ if (!plainObject(row) || typeof row.type !== "string") return null;
+ if (row.type === "text") {
+ if (typeof row.text !== "string" || row.text.length > MAX_DIRECT_TEXT_CHARS) return null;
+ content.push({ type: "text", text: row.text });
+ continue;
+ }
+ if (row.type !== "image" || typeof row.data !== "string" || typeof row.mimeType !== "string" || !IMAGE_MIME.has(row.mimeType)) return null;
+ if (++images > 1 || row.data.length > Math.ceil(MAX_DIRECT_IMAGE_BYTES * 4 / 3) + 8 || !/^[A-Za-z0-9+/]+={0,2}$/.test(row.data)) return null;
+ const bytes = Buffer.from(row.data, "base64");
+ if (bytes.length === 0 || bytes.length > MAX_DIRECT_IMAGE_BYTES || !validSignature(bytes, row.mimeType)) return null;
+ content.push({ type: "image", data: row.data, mimeType: row.mimeType });
+ }
+ return images === 1 ? content : null;
+}
+
+/**
+ * Project functions normally return their stdout/stderr envelope unchanged. A
+ * function may opt into direct MCP visual content by emitting one strict JSON
+ * document using PROJECT_FUNCTION_CONTENT_PROTOCOL. The runner's existing 1 MiB
+ * stdout cap still applies before this parser runs; this second bound keeps the
+ * decoded image comfortably below that wire limit.
+ */
+export function projectFunctionContent(result: ProjectFunctionResult): ProjectFunctionResult | DirectProjectFunctionResult {
+ if (result.code !== 0 || result.stderr.trim() !== "") return result;
+ let parsed: unknown;
+ try { parsed = JSON.parse(result.stdout); } catch { return result; }
+ const content = parseContent(parsed);
+ if (!content) return result;
+ return { ...mcpDirect(content), code: 0 };
+}
diff --git a/lib/mcp/project-functions.test.ts b/lib/mcp/project-functions.test.ts
index 4ff3110a..0a7a0758 100644
--- a/lib/mcp/project-functions.test.ts
+++ b/lib/mcp/project-functions.test.ts
@@ -41,4 +41,26 @@ describe("project function MCP bridge", () => {
}, { scope: "exec" });
expect(result).toEqual({ code: 0, stdout: JSON.stringify({ value: "hello; $(not-a-shell)" }), stderr: "" });
});
+
+ it("renders a validated project image envelope as direct MCP image content", async () => {
+ const png = Buffer.from([137,80,78,71,13,10,26,10,0]);
+ const visual = path.join(base, "visual");
+ await fs.mkdir(path.join(visual, ".mso"), { recursive: true });
+ const envelope = JSON.stringify({ protocol: "mso.project-function-content.v1", content: [
+ { type: "image", data: png.toString("base64"), mimeType: "image/png" },
+ { type: "text", text: "scene hub · r33" },
+ ] });
+ const source = `process.stdin.resume();process.stdin.on('end',()=>process.stdout.write(${JSON.stringify(envelope)}))`;
+ await fs.writeFile(path.join(visual, ".mso/functions.json"), JSON.stringify({
+ version: 1, functions: [{ name: "capture_scene", description: "Capture scene.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false }, command: [process.execPath, "-e", source] }],
+ }));
+ const result = await TOOLS_BY_NAME.get("project_function_call")!.run({ project: visual, name: "capture_scene", input: {} }, { scope: "exec" }) as {
+ __mcpDirect?: boolean; __capabilityDirect?: boolean; code?: number; content?: Array<{ type: string; mimeType?: string; text?: string }>;
+ };
+ expect(result.__mcpDirect || result.__capabilityDirect).toBe(true);
+ expect(result.code).toBe(0);
+ expect(result.content?.map((row) => row.type)).toEqual(["image", "text"]);
+ expect(result.content?.[0]?.mimeType).toBe("image/png");
+ });
});
diff --git a/lib/mcp/service-token.test.ts b/lib/mcp/service-token.test.ts
new file mode 100644
index 00000000..d0d0f6f7
--- /dev/null
+++ b/lib/mcp/service-token.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+import { normaliseServiceTokenConstraints, normaliseServiceTokenTools } from "./service-token";
+
+describe("restricted MCP service tokens", () => {
+ it("accepts only known tools within the granted scope", () => {
+ expect(normaliseServiceTokenTools(["project_capabilities", "project_function_call", "project_capabilities"], "exec"))
+ .toEqual(["project_capabilities", "project_function_call"]);
+ expect(() => normaliseServiceTokenTools(["project_function_call"], "read")).toThrow(/needs exec scope/);
+ expect(() => normaliseServiceTokenTools(["exec_run"], "exec")).toThrow(/not eligible for service tokens/);
+ const constraints=normaliseServiceTokenConstraints({project_capabilities:{project:["antinrml-game"]},project_function_call:{project:["antinrml-game"],name:["capture_scene"]}},["project_capabilities","project_function_call"]);
+ expect(constraints?.project_function_call.name).toEqual(["capture_scene"]);
+ expect(() => normaliseServiceTokenConstraints({exec_run:{command:["id"]}},["project_capabilities","project_function_call"])).toThrow(/not allowlisted/);
+ expect(() => normaliseServiceTokenConstraints(undefined,["project_function_call"])).toThrow(/constraints/);
+ expect(() => normaliseServiceTokenConstraints({project_function_call:{project:["antinrml-game"]}},["project_function_call"])).toThrow(/name/);
+ });
+});
diff --git a/lib/mcp/service-token.ts b/lib/mcp/service-token.ts
new file mode 100644
index 00000000..024a5c7b
--- /dev/null
+++ b/lib/mcp/service-token.ts
@@ -0,0 +1,65 @@
+import { randomToken } from "./pkce";
+import { allows, type Scope } from "./scope";
+import { storeToken, TOKEN_TTL_MS } from "./store";
+
+export const MAX_SERVICE_TOKEN_TOOLS = 8;
+export type ServiceTokenConstraints = Record<string, Record<string, string[]>>;
+
+const SERVICE_TOKEN_TOOL_POLICY = {
+ project_capabilities: { scope: "read" as const, constraintArgs: ["project"] as const },
+ project_function_call: { scope: "exec" as const, constraintArgs: ["project", "name"] as const },
+} as const;
+type ServiceTokenTool = keyof typeof SERVICE_TOKEN_TOOL_POLICY;
+
+export function normaliseServiceTokenTools(names: readonly string[], scope: Scope): string[] {
+ const unique = [...new Set(names.map((name) => name.trim()).filter(Boolean))];
+ if (!unique.length || unique.length > MAX_SERVICE_TOKEN_TOOLS) throw new Error(`service token needs 1..${MAX_SERVICE_TOKEN_TOOLS} allowed tools`);
+ for (const name of unique) {
+ const policy = SERVICE_TOKEN_TOOL_POLICY[name as ServiceTokenTool];
+ if (!policy) throw new Error(`tool is not eligible for service tokens: ${name}`);
+ if (!allows(scope, policy.scope)) throw new Error(`${name} needs ${policy.scope} scope`);
+ }
+ return unique;
+}
+
+export function normaliseServiceTokenConstraints(raw: unknown, allowedTools: readonly string[]): ServiceTokenConstraints | undefined {
+ if (raw === undefined) throw new Error("service token constraints are required");
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("service token constraints must be an object");
+ const result: ServiceTokenConstraints = {};
+ for (const [toolName, value] of Object.entries(raw as Record<string, unknown>)) {
+ if (!allowedTools.includes(toolName)) throw new Error(`constraint tool is not allowlisted: ${toolName}`);
+ const policy = SERVICE_TOKEN_TOOL_POLICY[toolName as ServiceTokenTool];
+ if (!policy || !value || typeof value !== "object" || Array.isArray(value)) throw new Error(`invalid constraints for ${toolName}`);
+ const constraintArgs = new Set<string>(policy.constraintArgs);
+ const row: Record<string, string[]> = {};
+ for (const [key, allowedRaw] of Object.entries(value as Record<string, unknown>)) {
+ if (!constraintArgs.has(key)) throw new Error(`unknown constrained argument: ${toolName}.${key}`);
+ if (!Array.isArray(allowedRaw) || !allowedRaw.length || allowedRaw.length > 16 || allowedRaw.some((one) => typeof one !== "string" || !one.trim() || one.length > 160)) {
+ throw new Error(`constraint ${toolName}.${key} needs 1..16 bounded string values`);
+ }
+ row[key] = [...new Set((allowedRaw as string[]).map((one) => one.trim()))];
+ }
+ if (!Object.keys(row).length) throw new Error(`constraints for ${toolName} are empty`);
+ result[toolName] = row;
+ }
+ for (const toolName of allowedTools) {
+ const policy = SERVICE_TOKEN_TOOL_POLICY[toolName as ServiceTokenTool];
+ const row = result[toolName];
+ if (!policy || !row) throw new Error(`service token needs exact constraints for ${toolName}`);
+ for (const key of policy.constraintArgs) {
+ if (!row[key]?.length) throw new Error(`service token needs exact constraint ${toolName}.${key}`);
+ }
+ }
+ return result;
+}
+
+export async function issueServiceToken(input: { label: string; clientId: string; scope: Scope; allowedTools: readonly string[]; constraints?: unknown }) {
+ const label = input.label.trim().slice(0, 80), clientId = input.clientId.trim().slice(0, 120);
+ if (!label || !clientId) throw new Error("service token label and client id are required");
+ const allowedTools = normaliseServiceTokenTools(input.allowedTools, input.scope);
+ const toolArgumentConstraints = normaliseServiceTokenConstraints(input.constraints, allowedTools);
+ const token = randomToken("mso_mcp_");
+ const now = Date.now();
+ await storeToken(token, { label, clientId, scope: input.scope, allowedTools, ...(toolArgumentConstraints ? { toolArgumentConstraints } : {}) });
+ return { token, scope: input.scope, allowedTools, toolArgumentConstraints, expiresAt: now + TOKEN_TTL_MS };
+}
diff --git a/lib/mcp/store.ts b/lib/mcp/store.ts
index 7588e48a..3a9d9169 100644
--- a/lib/mcp/store.ts
+++ b/lib/mcp/store.ts
@@ -40,6 +40,10 @@ export interface McpToken {
scope: Scope;
resource?: string;
profile?: McpToolProfile;
+ /** Optional exact tool allowlist for operator-issued machine tokens. OAuth tokens omit it. */
+ allowedTools?: string[];
+ /** Optional exact string argument constraints keyed by MCP tool then argument. */
+ toolArgumentConstraints?: Record<string, Record<string, string[]>>;
grantId?: string;
createdAt: number;
expiresAt: number;
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 0292f747..01f20737 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -134,7 +134,7 @@ const MUTATE_TOOLS: McpTool[] = [
description:
"Execute ONE function explicitly declared by a validated project's .mso/functions.json. " +
"This is project code execution and therefore requires exec scope. The manifest supplies fixed argv; model/user input is passed only as JSON on stdin and is NEVER interpolated into a shell command. " +
- "Call project_capabilities first for function names and schemas. Projects without an opt-in manifest expose nothing.",
+ "Call project_capabilities first for function names and schemas. Projects without an opt-in manifest expose nothing. A function may return a validated bounded direct-image envelope for visual debugging; invalid envelopes remain ordinary text output.",
scope: "exec",
annotations: { destructiveHint: true, openWorldHint: true },
inputSchema: S({
@@ -145,7 +145,7 @@ const MUTATE_TOOLS: McpTool[] = [
run: async (a) => {
const project = await resolveProjectHint(str(a, "project"));
if (!project) throw new Error(`project not found: ${String(a.project)}`);
- return runProjectFunction(project.path, str(a, "name"), a.input);
+ return (await import("./project-function-content")).projectFunctionContent(await runProjectFunction(project.path, str(a, "name"), a.input));
},
},
{
diff --git a/scripts/cli/commands-admin.sh b/scripts/cli/commands-admin.sh
index 69bef4ec..f7534eee 100755
--- a/scripts/cli/commands-admin.sh
+++ b/scripts/cli/commands-admin.sh
@@ -38,6 +38,7 @@ case "$cmd" in
case "${1:-list}" in
list) jget "/api/mcp/tokens" ;;
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)"
jdel "/api/mcp/tokens?id=$(enc "$2")" ;;
*) die "usage: mso $U_mcp" ;;
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 83c17f24..6c0a983c 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -43,7 +43,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]|revoke <id>|revoke all"
+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_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
diff --git a/scripts/mcp-service-token.ts b/scripts/mcp-service-token.ts
new file mode 100644
index 00000000..4fc7f128
--- /dev/null
+++ b/scripts/mcp-service-token.ts
@@ -0,0 +1,16 @@
+#!/usr/bin/env bun
+import { issueServiceToken } from "../lib/mcp/service-token";
+import type { Scope } from "../lib/mcp/scope";
+
+const argv = process.argv.slice(2);
+const value = (name: string) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; };
+const scopeRaw = value("--scope") ?? "read";
+if (scopeRaw !== "read" && scopeRaw !== "write" && scopeRaw !== "exec") throw new Error("--scope must be read, write, or exec");
+const tools = (value("--tools") ?? "").split(",").map((row) => row.trim()).filter(Boolean);
+let constraints: unknown = undefined;
+const rawConstraints=value("--constraints-json");
+if(rawConstraints){try{constraints=JSON.parse(rawConstraints)}catch{throw new Error("--constraints-json must be valid JSON")}}
+const result = await issueServiceToken({
+ label: value("--label") ?? "", clientId: value("--client-id") ?? "", scope: scopeRaw as Scope, allowedTools: tools, constraints,
+});
+process.stdout.write(JSON.stringify({ accessToken: result.token, tokenType: "Bearer", scope: result.scope, allowedTools: result.allowedTools, toolArgumentConstraints: result.toolArgumentConstraints, expiresAt: result.expiresAt }) + "\n");