@amoree-code/ocean 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/application/clients/clients.js +122 -6
  2. package/dist/infrastructure/mcp/remote-mcp-client.js +46 -0
  3. package/dist/interfaces/cli/clients-command.js +39 -2
  4. package/dist/interfaces/cli/command-registry.js +7 -3
  5. package/dist/interfaces/cli/gateway-findings.js +32 -0
  6. package/dist/interfaces/cli/help-command.js +3 -3
  7. package/dist/interfaces/cli/market-command.js +142 -5
  8. package/dist/interfaces/cli/mcp-gateway-command.js +28 -11
  9. package/dist/interfaces/cli/mcp-status-command.js +135 -0
  10. package/dist/interfaces/cli/onboard-command.js +6 -2
  11. package/market/mcp/chrome-devtools/ocean.capability.json +15 -12
  12. package/node_modules/@ocean/brain/package.json +1 -1
  13. package/node_modules/@ocean/context/package.json +1 -1
  14. package/node_modules/@ocean/core/package.json +1 -1
  15. package/node_modules/@ocean/loop/package.json +1 -1
  16. package/node_modules/@ocean/market/dist/adapters/mcp-adapter.js +13 -2
  17. package/node_modules/@ocean/market/dist/install/default-marketplace.js +1 -0
  18. package/node_modules/@ocean/market/dist/install/own-server.js +110 -0
  19. package/node_modules/@ocean/market/dist/mcp/mcp-gateway.js +113 -10
  20. package/node_modules/@ocean/market/dist/mcp/mcp-launch.js +167 -23
  21. package/node_modules/@ocean/market/dist/mcp/mcp-runner.js +6 -1
  22. package/node_modules/@ocean/market/dist/registry/official-registry.js +76 -0
  23. package/node_modules/@ocean/market/dist/security/secrets.js +66 -0
  24. package/node_modules/@ocean/market/package.json +1 -1
  25. package/node_modules/@ocean/services/package.json +1 -1
  26. package/ocean-marketplace.json +34 -48
  27. package/package.json +7 -7
@@ -0,0 +1,135 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { marketplacePaths } from "@ocean/market/install/default-marketplace.js";
4
+ import { canSee, gatewayMembers, readGatewayAccess, sensitivityOf, } from "@ocean/market/mcp/mcp-gateway.js";
5
+ import { launchInputs, stdioPackage, } from "@ocean/market/mcp/mcp-launch.js";
6
+ import { keychainStore } from "@ocean/market/security/secrets.js";
7
+ import { gatewayDefault, readGatewayClients, } from "../../application/clients/clients.js";
8
+ import { CLIENT_ADAPTERS } from "../../application/clients/registry.js";
9
+ import { oceanVersion } from "../../version.js";
10
+ import { gatewayClientFor } from "./mcp-gateway-command.js";
11
+ const errorMessage = (error) => error instanceof Error ? error.message : String(error);
12
+ async function installedServers(root) {
13
+ let files = [];
14
+ try {
15
+ files = (await readdir(root)).filter((file) => file.endsWith(".json"));
16
+ }
17
+ catch {
18
+ return [];
19
+ }
20
+ const servers = [];
21
+ for (const file of files.sort())
22
+ try {
23
+ servers.push(JSON.parse(await readFile(path.join(root, file), "utf8")));
24
+ }
25
+ catch {
26
+ // A broken file shows up in the gateway's own log.
27
+ }
28
+ return servers;
29
+ }
30
+ async function check(member, version, timeoutMs) {
31
+ const client = gatewayClientFor(member, version, `ocean mcp status [${member.capability}]`);
32
+ let timer;
33
+ try {
34
+ const tools = await Promise.race([
35
+ client.connect().then(() => client.listTools()),
36
+ new Promise((_, reject) => {
37
+ timer = setTimeout(() => reject(new Error(`no answer within ${timeoutMs} ms`)), timeoutMs);
38
+ }),
39
+ ]);
40
+ return { tools: tools.length };
41
+ }
42
+ catch (error) {
43
+ return { error: errorMessage(error) };
44
+ }
45
+ finally {
46
+ clearTimeout(timer);
47
+ client.close();
48
+ }
49
+ }
50
+ // `ocean mcp status [--check] [--json]`: every installed MCP server in one view — how it runs,
51
+ // whether it can start and why not, the values it needs and where each comes from, and which
52
+ // clients reach it. `--check` starts each one and counts its tools.
53
+ export async function mcpStatus(options = {}) {
54
+ const paths = marketplacePaths();
55
+ const store = keychainStore();
56
+ const { members, skipped } = await gatewayMembers({
57
+ serversRoot: paths.mcpServers,
58
+ stateRoot: paths.mcpState,
59
+ firstParty: false,
60
+ secrets: store,
61
+ });
62
+ const access = await readGatewayAccess(paths.gatewayAccess);
63
+ const wired = [...readGatewayClients()].sort();
64
+ const perServer = CLIENT_ADAPTERS.filter((adapter) => adapter.config && !wired.includes(adapter.id)).map((adapter) => adapter.id);
65
+ const version = await oceanVersion();
66
+ const servers = [];
67
+ for (const installed of await installedServers(paths.mcpServers)) {
68
+ const name = installed.capability;
69
+ const member = members.find((each) => each.capability === name);
70
+ const stdio = stdioPackage(installed.server);
71
+ const remote = installed.server.remotes?.[0];
72
+ const status = {
73
+ name,
74
+ version: installed.version,
75
+ runs: stdio
76
+ ? String(stdio.registryType)
77
+ : remote
78
+ ? `remote ${String(remote.type ?? "streamable-http")}`
79
+ : "?",
80
+ ready: Boolean(member),
81
+ ...(member
82
+ ? {}
83
+ : {
84
+ problem: skipped.find((skip) => skip.capability === name)?.reason ??
85
+ "not routed",
86
+ }),
87
+ ...(sensitivityOf(installed)
88
+ ? { sensitive: sensitivityOf(installed) }
89
+ : {}),
90
+ values: launchInputs(installed.server).map((input) => ({
91
+ name: input.name,
92
+ required: input.required,
93
+ from: process.env[input.name] !== undefined
94
+ ? "environment"
95
+ : store.get(name, input.name) !== undefined
96
+ ? store.name
97
+ : "missing",
98
+ })),
99
+ gatewayClients: member
100
+ ? wired.filter((client) => canSee(access, client, member))
101
+ : [],
102
+ // `ocean clients apply` gives a per-server entry only to servers with a stdio package.
103
+ perServerClients: stdio ? perServer : [],
104
+ };
105
+ if (options.check && member)
106
+ status.check = await check(member, version, options.timeoutMs ?? 15_000);
107
+ servers.push(status);
108
+ }
109
+ return { gatewayDefault: gatewayDefault(), gatewayClients: wired, servers };
110
+ }
111
+ export async function runMcpStatusCommand(args) {
112
+ const report = await mcpStatus({ check: args.includes("--check") });
113
+ if (args.includes("--json")) {
114
+ console.log(JSON.stringify(report, null, 2));
115
+ return;
116
+ }
117
+ console.log(`gateway: default ${report.gatewayDefault}; wired: ${report.gatewayClients.join(", ") || "no client"}`);
118
+ if (!report.servers.length)
119
+ console.log("No MCP server installed. Find one with `ocean market search <term>`.");
120
+ for (const server of report.servers) {
121
+ const missing = server.values.filter((value) => value.from === "missing");
122
+ console.log(`\n${server.name}@${server.version} [${server.runs}${server.sensitive ? `, ${server.sensitive}` : ""}]`);
123
+ console.log(` ${server.ready ? "ready" : `not starting: ${server.problem}`}`);
124
+ if (server.values.length)
125
+ console.log(` values: ${server.values.map((value) => `${value.name} (${value.from})`).join(", ")}`);
126
+ if (missing.length)
127
+ console.log(` set with: ${missing.map((value) => `ocean market secret set ${server.name} ${value.name}`).join("; ")}`);
128
+ console.log(` through the gateway: ${server.gatewayClients.join(", ") || "no client"}${server.sensitive && server.ready ? ` (allow with: ocean clients allow <client> ${server.name})` : ""}`);
129
+ if (server.perServerClients.length)
130
+ console.log(` own entry (after ocean clients apply): ${server.perServerClients.join(", ")}`);
131
+ if (server.check)
132
+ console.log(` check: ${"tools" in server.check ? `${server.check.tools} tools` : `failed: ${server.check.error}`}`);
133
+ }
134
+ }
135
+ //# sourceMappingURL=mcp-status-command.js.map
@@ -1,5 +1,5 @@
1
1
  import { createInterface } from "node:readline/promises";
2
- import { applyClients, planClients, readClientState, recordVerification, verifyClient, } from "../../application/clients/clients.js";
2
+ import { applyClients, defaultToGatewayOnFreshSetup, planClients, readClientState, recordVerification, verifyClient, } from "../../application/clients/clients.js";
3
3
  import { applyHooks, planHooks } from "../../application/clients/hooks.js";
4
4
  import { applyNative, planNative } from "../../application/clients/native.js";
5
5
  import { loadOnboardingState, saveOnboardingState, } from "../../application/onboarding/state.js";
@@ -17,7 +17,11 @@ const stepDependencies = () => ({
17
17
  },
18
18
  clients: {
19
19
  plan: () => planClients(),
20
- apply: (clients) => applyClients({ clients }),
20
+ // A fresh machine starts with every client going through the one gateway entry (T-309).
21
+ apply: async (clients) => {
22
+ await defaultToGatewayOnFreshSetup();
23
+ return applyClients({ clients });
24
+ },
21
25
  verify: async (client) => {
22
26
  const check = await verifyClient(client);
23
27
  await recordVerification(client, check.ok);
@@ -1,28 +1,31 @@
1
1
  {
2
2
  "kind": "mcp",
3
3
  "name": "dev.ocean/chrome-devtools",
4
- "description": "Control the owner's real, signed-in Chrome through Chrome DevTools MCP: tabs, navigation, clicks, forms, screenshots, console and network errors. Reads every open tab and acts inside any signed-in session of the attached profile, for every client that uses the Ocean gateway. The filesystem permission is declared for consent but not enforced at runtime, and the npm package is pinned by version, not by digest.",
4
+ "description": "Control the owner's real, signed-in Chrome through the ocean-browser-mcp package (pinned Chrome DevTools MCP): tabs, navigation, clicks, forms, uploads, screenshots, console and network errors. Reads every open tab and acts inside any signed-in session of the attached Chrome, for every client wired to it. Chrome asks to allow each new connection. The filesystem permission is declared for consent but not enforced at runtime, and the npm package is pinned by version, not by digest.",
5
5
  "permissions": {
6
- "filesystem": { "read": ["~/Library/Application Support/Google/Chrome"] },
6
+ "filesystem": {
7
+ "read": ["~/Library/Application Support/Google/Chrome"]
8
+ },
7
9
  "network": ["registry.npmjs.org", "localhost", "127.0.0.1"],
8
10
  "exec": ["npx"]
9
11
  },
10
12
  "server": {
11
13
  "name": "dev.ocean/chrome-devtools",
12
- "description": "Chrome DevTools MCP attached to the owner's running Chrome. Usage statistics and CrUX lookups are off, so page URLs stay on this machine.",
14
+ "description": "ocean-browser-mcp runs Chrome DevTools MCP 1.12.0 attached to the owner's running Chrome, with usage statistics and CrUX lookups off, so page URLs stay on this machine.",
13
15
  "packages": [
14
16
  {
15
17
  "registryType": "npm",
16
- "identifier": "chrome-devtools-mcp",
17
- "version": "1.12.0",
18
- "transport": { "type": "stdio" },
19
- "packageArguments": [
20
- { "type": "positional", "value": "--autoConnect" },
21
- { "type": "positional", "value": "--no-usage-statistics" },
22
- { "type": "positional", "value": "--no-performance-crux" }
23
- ]
18
+ "identifier": "ocean-browser-mcp",
19
+ "version": "0.1.0",
20
+ "transport": {
21
+ "type": "stdio"
22
+ }
24
23
  }
25
24
  ],
26
- "_meta": { "dev.ocean": { "clientKey": "chrome-devtools" } }
25
+ "_meta": {
26
+ "dev.ocean": {
27
+ "clientKey": "chrome-devtools"
28
+ }
29
+ }
27
30
  }
28
31
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/brain",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/context",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/core",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ocean/loop",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,15 @@
1
1
  import { mkdir, rm, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { expectRecord } from "./owned-directory.js";
4
+ // A remote endpoint Ocean will talk to: https anywhere, plain http only on this machine.
5
+ export function remoteUrlAllowed(url) {
6
+ if (url.protocol === "https:")
7
+ return true;
8
+ return (url.protocol === "http:" &&
9
+ (url.hostname === "localhost" ||
10
+ url.hostname === "[::1]" ||
11
+ /^127(\.\d{1,3}){3}$/.test(url.hostname)));
12
+ }
4
13
  function records(value, field) {
5
14
  if (value === undefined)
6
15
  return undefined;
@@ -28,8 +37,10 @@ export function createMcpAdapter(serversRoot) {
28
37
  typeof item.identifier !== "string")
29
38
  throw new Error("server.json packages need registryType and identifier");
30
39
  for (const item of remotes ?? [])
31
- if (typeof item.url !== "string" || !item.url.startsWith("https://"))
32
- throw new Error("server.json remotes need an https url");
40
+ if (typeof item.url !== "string" ||
41
+ !URL.canParse(item.url) ||
42
+ !remoteUrlAllowed(new URL(item.url)))
43
+ throw new Error("server.json remotes need an https url (or http on loopback)");
33
44
  return record;
34
45
  },
35
46
  async install({ manifest, spec }) {
@@ -14,6 +14,7 @@ export const marketplacePaths = () => ({
14
14
  mcpServers: oceanPath(SYSTEM_DIR, "market", "mcp"),
15
15
  plugins: oceanPath(SYSTEM_DIR, "market", "plugins"),
16
16
  mcpState: oceanPath(SYSTEM_DIR, "market", "state"),
17
+ gatewayAccess: oceanPath(SYSTEM_DIR, "market", "gateway-access.json"),
17
18
  lock: oceanPath(SYSTEM_DIR, "installed", "ocean.lock"),
18
19
  });
19
20
  // The owner's own index under bridge/ first (it wins on a name@version clash), then the one the
@@ -0,0 +1,110 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, readdir, readFile, rename, rm, writeFile, } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { capabilityNameSchema, marketplaceIndexSchema, semverPattern, } from "@ocean/core/domain/capabilities/capability-manifest.js";
5
+ import { createMcpAdapter, } from "../adapters/mcp-adapter.js";
6
+ import { contentDigest } from "../capability/content-digest.js";
7
+ import { launchInputs, runnerCommand, stdioPackage, } from "../mcp/mcp-launch.js";
8
+ // Names the engine ships; an owner's server may not shadow them in the owner's index, which
9
+ // wins on a name@version clash.
10
+ const RESERVED = /^dev\.ocean(\.|\/)/;
11
+ // The permissions a server.json needs to launch, exactly what the launcher checks: its runner or
12
+ // its remote's host, and every value it is given (environment variables, `{placeholders}` in its
13
+ // arguments or headers, secret headers). Nothing is added "just in case".
14
+ export function permissionsFor(server) {
15
+ const permissions = {
16
+ filesystem: { read: [], write: [] },
17
+ network: [],
18
+ env: launchInputs(server).map((input) => input.name),
19
+ exec: [],
20
+ };
21
+ const stdio = stdioPackage(server);
22
+ if (stdio) {
23
+ permissions.exec.push(runnerCommand(String(stdio.registryType)));
24
+ return permissions;
25
+ }
26
+ const remote = server.remotes?.[0];
27
+ if (remote && typeof remote.url === "string" && URL.canParse(remote.url))
28
+ permissions.network.push(new URL(remote.url).hostname);
29
+ return permissions;
30
+ }
31
+ async function readIndex(indexFile) {
32
+ try {
33
+ return marketplaceIndexSchema.parse(JSON.parse(await readFile(indexFile, "utf8")));
34
+ }
35
+ catch (error) {
36
+ if (error.code === "ENOENT")
37
+ return { schemaVersion: 1, name: "owner", capabilities: [] };
38
+ throw error;
39
+ }
40
+ }
41
+ // `ocean market add <server.json>`: the owner's own MCP server joins the way every other server
42
+ // does. It becomes an entry in the owner's index (`bridge/market/ocean-marketplace.json`) with
43
+ // the permissions it needs and a pinned digest, then goes through the one install path: the
44
+ // description scan, consent, the lock. If any step refuses, the entry and its payload are
45
+ // removed again, so a refused server is never installed and never started.
46
+ export async function addOwnMcpServer(options) {
47
+ const server = createMcpAdapter(() => "").parseSpec(options.server);
48
+ // Registry names may carry capitals; a capability name is lowercase.
49
+ const name = capabilityNameSchema.parse(server.name.toLowerCase());
50
+ if (RESERVED.test(name))
51
+ throw new Error(`${name}: dev.ocean names are reserved for the engine`);
52
+ const version = typeof server.version === "string" && semverPattern.test(server.version)
53
+ ? server.version
54
+ : "0.0.0";
55
+ // The payload is the server.json itself, under a directory named by its digest so an older
56
+ // entry's payload stays intact until the new one is installed.
57
+ const indexDir = path.dirname(options.indexFile);
58
+ const slug = name.replace(/[^a-z0-9._-]/g, "__");
59
+ const ownDir = path.join(indexDir, "own");
60
+ const staging = path.join(ownDir, `.staging-${randomUUID()}`);
61
+ await mkdir(staging, { recursive: true });
62
+ await writeFile(path.join(staging, "server.json"), `${JSON.stringify(server, null, 2)}\n`);
63
+ const sha256 = await contentDigest(staging);
64
+ const payload = `${slug}-${sha256.slice(0, 12)}`;
65
+ await rm(path.join(ownDir, payload), { recursive: true, force: true });
66
+ await rename(staging, path.join(ownDir, payload));
67
+ const manifest = {
68
+ kind: "mcp",
69
+ name,
70
+ version,
71
+ description: `Added by the owner with \`ocean market add\` from ${options.from}. A stdio server runs as an ordinary process of this user; only the values listed here are passed to it.`,
72
+ engines: { ocean: `>=${options.oceanVersion}` },
73
+ source: { type: "path", path: `own/${payload}` },
74
+ integrity: { sha256 },
75
+ permissions: permissionsFor(server),
76
+ spec: server,
77
+ };
78
+ let before;
79
+ try {
80
+ before = await readFile(options.indexFile, "utf8");
81
+ }
82
+ catch {
83
+ // No owner index yet.
84
+ }
85
+ const index = await readIndex(options.indexFile);
86
+ index.capabilities = [
87
+ ...index.capabilities.filter((entry) => entry.name !== name),
88
+ manifest,
89
+ ];
90
+ await mkdir(indexDir, { recursive: true });
91
+ await writeFile(options.indexFile, `${JSON.stringify(index, null, 2)}\n`);
92
+ try {
93
+ const result = await options.marketplace().install(name, version);
94
+ // Older payloads of this server are no longer named by the index.
95
+ for (const entry of await readdir(ownDir))
96
+ if (entry.startsWith(`${slug}-`) && entry !== payload)
97
+ await rm(path.join(ownDir, entry), { recursive: true, force: true });
98
+ return result;
99
+ }
100
+ catch (error) {
101
+ if (before === undefined)
102
+ await rm(options.indexFile, { force: true });
103
+ else
104
+ await writeFile(options.indexFile, before);
105
+ if (!before?.includes(`"own/${payload}"`))
106
+ await rm(path.join(ownDir, payload), { recursive: true, force: true });
107
+ throw error;
108
+ }
109
+ }
110
+ //# sourceMappingURL=own-server.js.map
@@ -1,4 +1,4 @@
1
- import { mkdir, readdir, readFile } from "node:fs/promises";
1
+ import { mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { marketplaceIndexSchema } from "@ocean/core/domain/capabilities/capability-manifest.js";
4
4
  import { engineRoot } from "@ocean/core/shared/paths.js";
@@ -16,6 +16,70 @@ function namespaceFor(capability, taken) {
16
16
  taken.add(prefix);
17
17
  return prefix;
18
18
  }
19
+ const BROWSER = /(^|[^a-z])(browser|chrome|chromium|devtools|playwright|puppeteer|selenium|webdriver)([^a-z]|$)/i;
20
+ // Why an installed server is hidden from a client that was not allowed it by name, or nothing.
21
+ // Declared file writes count; so does driving a browser, recognised by name, since a browser
22
+ // server reads and acts inside every signed-in session whatever it declares.
23
+ export function sensitivityOf(installed) {
24
+ if (installed.permissions.filesystem.write.length)
25
+ return "writes files";
26
+ const names = [
27
+ installed.capability,
28
+ ...(installed.server.packages ?? []).map((item) => String(item.identifier)),
29
+ ];
30
+ if (names.some((name) => BROWSER.test(name)))
31
+ return "controls a browser";
32
+ return undefined;
33
+ }
34
+ export function canSee(access, client, member) {
35
+ const rule = client === undefined ? undefined : access.clients[client];
36
+ if (rule?.deny?.includes(member.capability))
37
+ return false;
38
+ if (!member.sensitive)
39
+ return true;
40
+ return Boolean(rule?.allow?.includes(member.capability) || rule?.allow?.includes("*"));
41
+ }
42
+ // `ocean clients allow|deny|unset <client> <capability>`: one rule changed, the rest kept.
43
+ export async function updateGatewayAccess(file, client, capability, change) {
44
+ const access = await readGatewayAccess(file);
45
+ const rule = access.clients[client] ?? {};
46
+ const without = (list) => (list ?? []).filter((item) => item !== capability);
47
+ const next = { allow: without(rule.allow), deny: without(rule.deny) };
48
+ if (change === "allow")
49
+ next.allow.push(capability);
50
+ if (change === "deny")
51
+ next.deny.push(capability);
52
+ if (next.allow.length || next.deny.length)
53
+ access.clients[client] = {
54
+ ...(next.allow.length ? { allow: next.allow.sort() } : {}),
55
+ ...(next.deny.length ? { deny: next.deny.sort() } : {}),
56
+ };
57
+ else
58
+ delete access.clients[client];
59
+ await mkdir(path.dirname(file), { recursive: true });
60
+ const temp = `${file}.${process.pid}.tmp`;
61
+ await writeFile(temp, `${JSON.stringify(access, null, 2)}\n`);
62
+ await rename(temp, file);
63
+ return access;
64
+ }
65
+ export async function readGatewayAccess(file) {
66
+ let raw;
67
+ try {
68
+ raw = JSON.parse(await readFile(file, "utf8"));
69
+ }
70
+ catch (error) {
71
+ if (error.code === "ENOENT")
72
+ return { clients: {} };
73
+ throw new Error(`Cannot read ${file}: ${errorMessage(error)}`);
74
+ }
75
+ const clients = isRecord(raw) ? raw.clients : undefined;
76
+ const list = (value) => value === undefined ||
77
+ (Array.isArray(value) && value.every((item) => typeof item === "string"));
78
+ if (!isRecord(clients) ||
79
+ !Object.values(clients).every((rule) => isRecord(rule) && list(rule.allow) && list(rule.deny)))
80
+ throw new Error(`${file}: expected {"clients": {"<client name>": {"allow": [...], "deny": [...]}}}`);
81
+ return raw;
82
+ }
19
83
  // The servers the gateway routes: the engine's first-party ones, then every MCP server installed
20
84
  // from the marketplace, each planned by the same launcher as `ocean market exec` — declared
21
85
  // permissions, declared environment only. A third-party server joins only by
@@ -25,6 +89,7 @@ export async function gatewayMembers(options) {
25
89
  const skipped = [];
26
90
  const taken = new Set();
27
91
  const notFirstParty = [];
92
+ const firstParty = new Set();
28
93
  const index = marketplaceIndexSchema.parse(JSON.parse(await readFile(options.indexFile ?? engineIndexFile(), "utf8")));
29
94
  for (const manifest of index.capabilities) {
30
95
  if (manifest.kind !== "mcp" || manifest.name === GATEWAY_CAPABILITY)
@@ -34,6 +99,9 @@ export async function gatewayMembers(options) {
34
99
  notFirstParty.push(manifest.name);
35
100
  continue;
36
101
  }
102
+ firstParty.add(manifest.name);
103
+ if (options.firstParty === false)
104
+ continue;
37
105
  members.push({
38
106
  capability: manifest.name,
39
107
  prefix: namespaceFor(manifest.name, taken),
@@ -68,6 +136,7 @@ export async function gatewayMembers(options) {
68
136
  const name = installed.capability;
69
137
  // An installed copy of an engine server runs the same code as the member already routed.
70
138
  if (name === GATEWAY_CAPABILITY ||
139
+ firstParty.has(name) ||
71
140
  members.some((member) => member.capability === name))
72
141
  continue;
73
142
  const stateDir = path.join(options.stateRoot, path.basename(file, ".json"));
@@ -75,18 +144,29 @@ export async function gatewayMembers(options) {
75
144
  const launch = planMcpLaunch(installed, {
76
145
  stateDir,
77
146
  env: options.env,
147
+ secret: (secret) => options.secrets?.get(name, secret),
78
148
  });
149
+ const sensitive = sensitivityOf(installed);
150
+ const base = {
151
+ capability: name,
152
+ prefix: namespaceFor(name, taken),
153
+ ...(sensitive ? { sensitive } : {}),
154
+ };
79
155
  if (launch.transport === "remote") {
80
- skipped.push({
81
- capability: name,
82
- reason: `remote server (${launch.type} ${launch.url}); connect the client to it directly`,
156
+ members.push({
157
+ ...base,
158
+ transport: "remote",
159
+ type: launch.type,
160
+ url: launch.url,
161
+ ...(Object.keys(launch.headers).length
162
+ ? { headers: launch.headers }
163
+ : {}),
83
164
  });
84
165
  continue;
85
166
  }
86
167
  await mkdir(stateDir, { recursive: true });
87
168
  members.push({
88
- capability: name,
89
- prefix: namespaceFor(name, taken),
169
+ ...base,
90
170
  command: launch.command,
91
171
  args: launch.args,
92
172
  cwd: launch.cwd,
@@ -157,25 +237,37 @@ export class McpGateway {
157
237
  #tools = [];
158
238
  #clients = [];
159
239
  #started;
240
+ // Who is on the other end, from `initialize`; fixed once members start.
241
+ #client;
160
242
  constructor(members, options) {
161
243
  this.members = members;
162
244
  this.options = options;
245
+ this.#client = options.clientId;
163
246
  }
164
247
  // Starts every member at once; one that fails or hangs is left out, never the whole gateway.
165
248
  start() {
166
249
  this.#started ??= this.#connectAll();
167
250
  return this.#started;
168
251
  }
252
+ // Only the members this client may see are started at all: a hidden server never runs and its
253
+ // tools never reach the client's context.
169
254
  async #connectAll() {
170
255
  const timeoutMs = this.options.timeoutMs ?? 15_000;
171
- const clients = this.members.map((member) => this.options.client(member));
256
+ const access = this.options.access ?? { clients: {} };
257
+ const members = this.members.filter((member) => {
258
+ if (canSee(access, this.#client, member))
259
+ return true;
260
+ this.#log(`${member.capability} hidden from ${this.#client ?? "an unnamed client"}${member.sensitive ? ` (${member.sensitive}; allow it in gateway-access.json)` : " (denied in gateway-access.json)"}`);
261
+ return false;
262
+ });
263
+ const clients = members.map((member) => this.options.client(member));
172
264
  this.#clients.push(...clients);
173
- const results = await Promise.allSettled(this.members.map(async (member, index) => {
265
+ const results = await Promise.allSettled(members.map(async (member, index) => {
174
266
  await withTimeout(clients[index].connect(), timeoutMs, `${member.capability} did not start`);
175
267
  return withTimeout(clients[index].listTools(), timeoutMs, `${member.capability} did not list its tools`);
176
268
  }));
177
269
  results.forEach((result, index) => {
178
- const member = this.members[index];
270
+ const member = members[index];
179
271
  if (result.status === "rejected") {
180
272
  this.#log(`${member.capability} left out: ${errorMessage(result.reason)}`);
181
273
  clients[index].close();
@@ -243,7 +335,17 @@ export class McpGateway {
243
335
  }
244
336
  async #answer(request) {
245
337
  switch (request.method) {
246
- case "initialize":
338
+ case "initialize": {
339
+ const info = isRecord(request.params)
340
+ ? request.params.clientInfo
341
+ : undefined;
342
+ const named = isRecord(info) && typeof info.name === "string";
343
+ if (this.options.clientId)
344
+ this.#log(`client: ${this.options.clientId}${named ? ` (says ${String(info.name)})` : ""}`);
345
+ else if (!this.#started && named) {
346
+ this.#client = String(info.name);
347
+ this.#log(`client: ${this.#client}`);
348
+ }
247
349
  // Members start while the client finishes its handshake.
248
350
  void this.start();
249
351
  return {
@@ -257,6 +359,7 @@ export class McpGateway {
257
359
  ? { instructions: this.options.instructions }
258
360
  : {}),
259
361
  };
362
+ }
260
363
  case "ping":
261
364
  return {};
262
365
  case "tools/list":