feat: mesh services platform — deploy MCP servers, vaults, scopes
Add the foundation for deploying and managing MCP servers on the VPS broker, with per-peer credential vaults and visibility scopes. Architecture: - One Docker container per mesh with a Node supervisor - Each MCP server runs as a child process with its own stdio pipe - claudemesh launch installs native MCP entries in ~/.claude.json - Mid-session deploys fall back to svc__* dynamic tools + list_changed New components: - DB: mesh.service + mesh.vault_entry tables, mesh.skill extensions - Broker: 19 wire protocol types, 11 message handlers, service catalog in hello_ack with scope filtering, service-manager.ts (775 lines) - CLI: 13 tool definitions, 12 WS client methods, tool call handlers, startServiceProxy() for native MCP proxy mode - Launch: catalog fetch, native MCP entry install, stale sweep, cleanup, MCP_TIMEOUT=30s, MAX_MCP_OUTPUT_TOKENS=50k Security: path sanitization on service names, column whitelist on upsertService, returning()-based delete checks, vault E2E encryption. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -14,12 +14,13 @@
|
||||
*/
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtempSync, writeFileSync, rmSync, readdirSync, statSync } from "node:fs";
|
||||
import { tmpdir, hostname } from "node:os";
|
||||
import { mkdtempSync, writeFileSync, rmSync, readdirSync, statSync, existsSync, readFileSync } from "node:fs";
|
||||
import { tmpdir, hostname, homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { loadConfig, getConfigPath } from "../state/config";
|
||||
import type { Config, JoinedMesh, GroupEntry } from "../state/config";
|
||||
import { BrokerClient } from "../ws/client";
|
||||
|
||||
// Flags as parsed by citty (index.ts is the source of truth for definitions).
|
||||
export interface LaunchFlags {
|
||||
@@ -277,6 +278,56 @@ export async function runLaunch(flags: LaunchFlags, rawArgs: string[]): Promise<
|
||||
}
|
||||
} catch { /* best effort */ }
|
||||
|
||||
// Clean up stale mesh MCP entries from crashed sessions
|
||||
try {
|
||||
const claudeConfigPath = join(homedir(), ".claude.json");
|
||||
if (existsSync(claudeConfigPath)) {
|
||||
const claudeConfig = JSON.parse(readFileSync(claudeConfigPath, "utf-8"));
|
||||
const mcpServers = claudeConfig.mcpServers ?? {};
|
||||
let cleaned = 0;
|
||||
for (const key of Object.keys(mcpServers)) {
|
||||
if (!key.startsWith("mesh:")) continue;
|
||||
const meta = mcpServers[key]?._meshSession;
|
||||
if (!meta?.pid) continue;
|
||||
// Check if the PID is still alive
|
||||
try {
|
||||
process.kill(meta.pid, 0); // signal 0 = check existence
|
||||
} catch {
|
||||
// PID is dead — remove stale entry
|
||||
delete mcpServers[key];
|
||||
cleaned++;
|
||||
}
|
||||
}
|
||||
if (cleaned > 0) {
|
||||
claudeConfig.mcpServers = mcpServers;
|
||||
writeFileSync(claudeConfigPath, JSON.stringify(claudeConfig, null, 2) + "\n", "utf-8");
|
||||
}
|
||||
}
|
||||
} catch { /* best effort */ }
|
||||
|
||||
// --- Fetch deployed services for native MCP entries ---
|
||||
let serviceCatalog: Array<{
|
||||
name: string;
|
||||
description: string;
|
||||
status: string;
|
||||
tools: Array<{ name: string; description: string; inputSchema: object }>;
|
||||
deployed_by: string;
|
||||
}> = [];
|
||||
|
||||
try {
|
||||
const tmpClient = new BrokerClient(mesh, { displayName });
|
||||
await tmpClient.connect();
|
||||
// Wait briefly for hello_ack with service catalog
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
serviceCatalog = tmpClient.serviceCatalog;
|
||||
tmpClient.close();
|
||||
} catch {
|
||||
// Non-fatal — launch without native service entries
|
||||
if (!args.quiet) {
|
||||
console.log(" (Could not fetch service catalog — mesh services won't be natively available)");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Write session config to tmpdir (isolates mesh selection).
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), "claudemesh-"));
|
||||
const sessionConfig: Config = {
|
||||
@@ -302,6 +353,59 @@ export async function runLaunch(flags: LaunchFlags, rawArgs: string[]): Promise<
|
||||
}
|
||||
}
|
||||
|
||||
// --- Install native MCP entries for deployed mesh services ---
|
||||
const meshMcpEntries: Array<{ key: string; entry: unknown }> = [];
|
||||
|
||||
if (serviceCatalog.length > 0) {
|
||||
const claudeConfigPath = join(homedir(), ".claude.json");
|
||||
|
||||
// Read-modify-write: only touch mesh:* entries in mcpServers
|
||||
let claudeConfig: Record<string, unknown> = {};
|
||||
try {
|
||||
claudeConfig = JSON.parse(readFileSync(claudeConfigPath, "utf-8"));
|
||||
} catch {
|
||||
claudeConfig = {};
|
||||
}
|
||||
|
||||
const mcpServers = (claudeConfig.mcpServers ?? {}) as Record<string, unknown>;
|
||||
|
||||
// Session-scoped key: mesh:<service>:<sessionId>
|
||||
const sessionTag = `${process.pid}`;
|
||||
|
||||
for (const svc of serviceCatalog) {
|
||||
if (svc.status !== "running") continue;
|
||||
const entryKey = `mesh:${svc.name}:${sessionTag}`;
|
||||
const entry = {
|
||||
command: "claudemesh",
|
||||
args: ["mcp", "--service", svc.name],
|
||||
env: {
|
||||
CLAUDEMESH_CONFIG_DIR: tmpDir,
|
||||
},
|
||||
_meshSession: {
|
||||
pid: process.pid,
|
||||
meshSlug: mesh.slug,
|
||||
serviceName: svc.name,
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
};
|
||||
mcpServers[entryKey] = entry;
|
||||
meshMcpEntries.push({ key: entryKey, entry });
|
||||
}
|
||||
|
||||
claudeConfig.mcpServers = mcpServers;
|
||||
writeFileSync(claudeConfigPath, JSON.stringify(claudeConfig, null, 2) + "\n", "utf-8");
|
||||
|
||||
if (!args.quiet && meshMcpEntries.length > 0) {
|
||||
console.log(` ${meshMcpEntries.length} mesh service(s) registered as native MCPs:`);
|
||||
for (const { key } of meshMcpEntries) {
|
||||
const svcName = key.split(":")[1];
|
||||
const svc = serviceCatalog.find(s => s.name === svcName);
|
||||
console.log(` ${svcName} (${svc?.tools.length ?? 0} tools)`);
|
||||
}
|
||||
console.log("");
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Spawn claude with ephemeral config + dev channel + auto-permissions.
|
||||
// Strip any user-supplied --dangerously flags to avoid duplicates.
|
||||
const filtered: string[] = [];
|
||||
@@ -333,12 +437,28 @@ export async function runLaunch(flags: LaunchFlags, rawArgs: string[]): Promise<
|
||||
...process.env,
|
||||
CLAUDEMESH_CONFIG_DIR: tmpDir,
|
||||
CLAUDEMESH_DISPLAY_NAME: displayName,
|
||||
MCP_TIMEOUT: process.env.MCP_TIMEOUT ?? "30000",
|
||||
MAX_MCP_OUTPUT_TOKENS: process.env.MAX_MCP_OUTPUT_TOKENS ?? "50000",
|
||||
...(role ? { CLAUDEMESH_ROLE: role } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
// 7. Cleanup on exit.
|
||||
const cleanup = (): void => {
|
||||
// Remove mesh MCP entries from ~/.claude.json
|
||||
if (meshMcpEntries.length > 0) {
|
||||
try {
|
||||
const claudeConfigPath = join(homedir(), ".claude.json");
|
||||
const claudeConfig = JSON.parse(readFileSync(claudeConfigPath, "utf-8"));
|
||||
const mcpServers = claudeConfig.mcpServers ?? {};
|
||||
for (const { key } of meshMcpEntries) {
|
||||
delete mcpServers[key];
|
||||
}
|
||||
claudeConfig.mcpServers = mcpServers;
|
||||
writeFileSync(claudeConfigPath, JSON.stringify(claudeConfig, null, 2) + "\n", "utf-8");
|
||||
} catch { /* best effort */ }
|
||||
}
|
||||
// Existing tmpdir cleanup
|
||||
try {
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
|
||||
@@ -22,7 +22,8 @@ import type {
|
||||
SetSummaryArgs,
|
||||
ListPeersArgs,
|
||||
} from "./types";
|
||||
import type { BrokerClient, InboundPush } from "../ws/client";
|
||||
import { BrokerClient } from "../ws/client";
|
||||
import type { InboundPush } from "../ws/client";
|
||||
|
||||
/** Compute a human-readable relative time string from an ISO timestamp. */
|
||||
function relativeTime(isoStr: string): string {
|
||||
@@ -144,6 +145,12 @@ function formatPush(p: InboundPush, meshSlug: string): string {
|
||||
}
|
||||
|
||||
export async function startMcpServer(): Promise<void> {
|
||||
// Check for --service mode (native mesh MCP proxy)
|
||||
const serviceIdx = process.argv.indexOf("--service");
|
||||
if (serviceIdx !== -1 && process.argv[serviceIdx + 1]) {
|
||||
return startServiceProxy(process.argv[serviceIdx + 1]!);
|
||||
}
|
||||
|
||||
const config = loadConfig();
|
||||
|
||||
const myName = config.displayName ?? "unnamed";
|
||||
@@ -1533,3 +1540,182 @@ Your message mode is "${messageMode}".
|
||||
process.on("SIGTERM", shutdown);
|
||||
process.on("SIGINT", shutdown);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mesh service proxy — a thin MCP server that proxies ONE deployed service.
|
||||
*
|
||||
* Spawned by Claude Code as a native MCP entry. Connects to the broker,
|
||||
* fetches tool schemas for the named service, and routes tool calls.
|
||||
*
|
||||
* If the broker WS drops, the proxy waits for reconnection (up to 10s)
|
||||
* before failing tool calls. If the proxy process itself crashes, Claude
|
||||
* Code will not auto-restart it.
|
||||
*/
|
||||
async function startServiceProxy(serviceName: string): Promise<void> {
|
||||
const config = loadConfig();
|
||||
if (config.meshes.length === 0) {
|
||||
process.stderr.write(`[mesh:${serviceName}] no meshes joined\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const mesh = config.meshes[0]!;
|
||||
const client = new BrokerClient(mesh, {
|
||||
displayName: config.displayName ?? `proxy:${serviceName}`,
|
||||
});
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
} catch (e) {
|
||||
process.stderr.write(
|
||||
`[mesh:${serviceName}] broker connect failed: ${e instanceof Error ? e.message : String(e)}\n`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Wait for hello_ack and service catalog
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
|
||||
// Fetch tool schemas for this service
|
||||
let tools: Array<{
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema: Record<string, unknown>;
|
||||
}> = [];
|
||||
try {
|
||||
const fetched = await client.getServiceTools(serviceName);
|
||||
tools = fetched as typeof tools;
|
||||
} catch {
|
||||
// Try from catalog cache
|
||||
const cached = client.serviceCatalog.find((s) => s.name === serviceName);
|
||||
if (cached) {
|
||||
tools = cached.tools as typeof tools;
|
||||
}
|
||||
}
|
||||
|
||||
if (tools.length === 0) {
|
||||
process.stderr.write(
|
||||
`[mesh:${serviceName}] no tools found — service may not be running\n`,
|
||||
);
|
||||
}
|
||||
|
||||
// Build MCP server
|
||||
const server = new Server(
|
||||
{ name: `mesh:${serviceName}`, version: "0.1.0" },
|
||||
{ capabilities: { tools: {} } },
|
||||
);
|
||||
|
||||
server.setRequestHandler(ListToolsRequestSchema, () => ({
|
||||
tools: tools.map((t) => ({
|
||||
name: t.name,
|
||||
description: `[mesh:${serviceName}] ${t.description}`,
|
||||
inputSchema: t.inputSchema as any,
|
||||
})),
|
||||
}));
|
||||
|
||||
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
||||
const toolName = req.params.name;
|
||||
const args = req.params.arguments ?? {};
|
||||
|
||||
// Wait for broker reconnection if needed
|
||||
if (client.status !== "open") {
|
||||
let waited = 0;
|
||||
while (client.status !== "open" && waited < 10_000) {
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
waited += 500;
|
||||
}
|
||||
if (client.status !== "open") {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: `Service temporarily unavailable — broker reconnecting. Retry in a few seconds.`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await client.mcpCall(
|
||||
serviceName,
|
||||
toolName,
|
||||
args as Record<string, unknown>,
|
||||
);
|
||||
if (result.error) {
|
||||
return {
|
||||
content: [{ type: "text" as const, text: `Error: ${result.error}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
const resultText =
|
||||
typeof result.result === "string"
|
||||
? result.result
|
||||
: JSON.stringify(result.result, null, 2);
|
||||
return {
|
||||
content: [{ type: "text" as const, text: resultText }],
|
||||
};
|
||||
} catch (e) {
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: `Call failed: ${e instanceof Error ? e.message : String(e)}`,
|
||||
},
|
||||
],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for service events (undeploy, update)
|
||||
client.onPush((push) => {
|
||||
if (
|
||||
push.event === "mcp_undeployed" &&
|
||||
(push.eventData as any)?.name === serviceName
|
||||
) {
|
||||
process.stderr.write(
|
||||
`[mesh:${serviceName}] service undeployed — exiting\n`,
|
||||
);
|
||||
client.close();
|
||||
process.exit(0);
|
||||
}
|
||||
if (
|
||||
push.event === "mcp_updated" &&
|
||||
(push.eventData as any)?.name === serviceName
|
||||
) {
|
||||
// Refresh tools
|
||||
const newTools = (push.eventData as any)?.tools;
|
||||
if (Array.isArray(newTools)) {
|
||||
tools = newTools;
|
||||
// Notify Claude Code that tools changed
|
||||
server
|
||||
.notification({
|
||||
method: "notifications/tools/list_changed",
|
||||
})
|
||||
.catch(() => {
|
||||
/* ignore notification errors */
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Start stdio transport
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
|
||||
// Keep event loop alive
|
||||
const keepalive = setInterval(() => {
|
||||
// Intentionally empty — prevents event loop from settling.
|
||||
}, 1_000);
|
||||
void keepalive;
|
||||
|
||||
// Graceful shutdown
|
||||
const shutdown = (): void => {
|
||||
clearInterval(keepalive);
|
||||
client.close();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on("SIGTERM", shutdown);
|
||||
process.on("SIGINT", shutdown);
|
||||
}
|
||||
|
||||
@@ -893,4 +893,82 @@ export const TOOLS: Tool[] = [
|
||||
required: ["name"],
|
||||
},
|
||||
},
|
||||
|
||||
// --- Service deployment tools ---
|
||||
|
||||
{
|
||||
name: "mesh_mcp_deploy",
|
||||
description: "Deploy an MCP server to the mesh from a zip file or git repo. Runs on the broker VPS, persists across peer sessions. Default scope: private (only you).",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
server_name: { type: "string", description: "Unique name for the server in this mesh" },
|
||||
file_id: { type: "string", description: "File ID of uploaded zip (from share_file)" },
|
||||
git_url: { type: "string", description: "Git repo URL" },
|
||||
git_branch: { type: "string", description: "Branch to clone (default: main)" },
|
||||
env: { type: "object", description: "Environment variables. Use $vault:<key> for vault secrets." },
|
||||
runtime: { type: "string", enum: ["node", "python", "bun"], description: "Runtime (auto-detected if omitted)" },
|
||||
memory_mb: { type: "number", description: "Memory limit in MB (default: 256)" },
|
||||
network_allow: { type: "array", items: { type: "string" }, description: "Allowed outbound hosts (default: none)" },
|
||||
scope: { description: "Visibility: 'peer' (default), 'mesh', or {group/groups/role/peers}" },
|
||||
},
|
||||
required: ["server_name"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mesh_mcp_undeploy",
|
||||
description: "Stop and remove a managed MCP server from the mesh.",
|
||||
inputSchema: { type: "object", properties: { server_name: { type: "string" } }, required: ["server_name"] },
|
||||
},
|
||||
{
|
||||
name: "mesh_mcp_update",
|
||||
description: "Pull latest code and restart a git-sourced MCP server.",
|
||||
inputSchema: { type: "object", properties: { server_name: { type: "string" } }, required: ["server_name"] },
|
||||
},
|
||||
{
|
||||
name: "mesh_mcp_logs",
|
||||
description: "View recent logs from a managed MCP server.",
|
||||
inputSchema: { type: "object", properties: { server_name: { type: "string" }, lines: { type: "number", description: "Lines (default: 50, max: 1000)" } }, required: ["server_name"] },
|
||||
},
|
||||
{
|
||||
name: "mesh_mcp_scope",
|
||||
description: "Get or set the visibility scope of a deployed MCP server.",
|
||||
inputSchema: { type: "object", properties: { server_name: { type: "string" }, scope: { description: "New scope to set. Omit to read current." } }, required: ["server_name"] },
|
||||
},
|
||||
{
|
||||
name: "mesh_mcp_schema",
|
||||
description: "Inspect tool schemas for a deployed MCP server.",
|
||||
inputSchema: { type: "object", properties: { server_name: { type: "string" }, tool_name: { type: "string", description: "Specific tool (omit for all)" } }, required: ["server_name"] },
|
||||
},
|
||||
{
|
||||
name: "mesh_mcp_catalog",
|
||||
description: "List all deployed services in the mesh with status, scope, and tool count.",
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
},
|
||||
|
||||
// --- Skill deployment tools ---
|
||||
|
||||
{
|
||||
name: "mesh_skill_deploy",
|
||||
description: "Deploy a multi-file skill bundle from a zip or git repo.",
|
||||
inputSchema: { type: "object", properties: { file_id: { type: "string" }, git_url: { type: "string" }, git_branch: { type: "string" } } },
|
||||
},
|
||||
|
||||
// --- Vault tools ---
|
||||
|
||||
{
|
||||
name: "vault_set",
|
||||
description: "Store an encrypted credential in your vault. Reference in mesh_mcp_deploy with $vault:<key>.",
|
||||
inputSchema: { type: "object", properties: { key: { type: "string" }, value: { type: "string", description: "Secret value or local file path (for type=file)" }, type: { type: "string", enum: ["env", "file"] }, mount_path: { type: "string" }, description: { type: "string" } }, required: ["key", "value"] },
|
||||
},
|
||||
{
|
||||
name: "vault_list",
|
||||
description: "List your vault entries (keys and metadata only, no secret values).",
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
},
|
||||
{
|
||||
name: "vault_delete",
|
||||
description: "Remove a credential from your vault.",
|
||||
inputSchema: { type: "object", properties: { key: { type: "string" } }, required: ["key"] },
|
||||
},
|
||||
];
|
||||
|
||||
@@ -22,3 +22,60 @@ export interface SetSummaryArgs {
|
||||
export interface SetStatusArgs {
|
||||
status: PeerStatus;
|
||||
}
|
||||
|
||||
// --- Service deployment types ---
|
||||
|
||||
export type ServiceScope =
|
||||
| "peer"
|
||||
| "mesh"
|
||||
| { peers: string[] }
|
||||
| { group: string }
|
||||
| { groups: string[] }
|
||||
| { role: string };
|
||||
|
||||
export interface ServiceInfo {
|
||||
name: string;
|
||||
type: "mcp" | "skill";
|
||||
description: string;
|
||||
status: string;
|
||||
tool_count: number;
|
||||
deployed_by: string;
|
||||
scope: ServiceScope;
|
||||
source_type: string;
|
||||
runtime?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ServiceToolSchema {
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface VaultEntry {
|
||||
key: string;
|
||||
entry_type: "env" | "file";
|
||||
mount_path?: string;
|
||||
description?: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface MeshMcpDeployArgs {
|
||||
server_name: string;
|
||||
file_id?: string;
|
||||
git_url?: string;
|
||||
git_branch?: string;
|
||||
env?: Record<string, string>;
|
||||
runtime?: "node" | "python" | "bun";
|
||||
memory_mb?: number;
|
||||
network_allow?: string[];
|
||||
scope?: ServiceScope;
|
||||
}
|
||||
|
||||
export interface VaultSetArgs {
|
||||
key: string;
|
||||
value: string;
|
||||
type?: "env" | "file";
|
||||
mount_path?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
@@ -114,6 +114,8 @@ export class BrokerClient {
|
||||
private peerDirResponseResolvers = new Map<string, { resolve: (result: { entries?: string[]; error?: string }) => void; timer: NodeJS.Timeout }>();
|
||||
/** Directories from which this peer serves files. Default: [process.cwd()]. */
|
||||
private sharedDirs: string[] = [process.cwd()];
|
||||
private _serviceCatalog: Array<{ name: string; description: string; status: string; tools: Array<{ name: string; description: string; inputSchema: object }>; deployed_by: string }> = [];
|
||||
get serviceCatalog() { return this._serviceCatalog; }
|
||||
private closed = false;
|
||||
private reconnectAttempt = 0;
|
||||
private helloTimer: NodeJS.Timeout | null = null;
|
||||
@@ -249,6 +251,9 @@ export class BrokerClient {
|
||||
this._statsCounters.errors = rs.errors ?? 0;
|
||||
}
|
||||
}
|
||||
if ((msg as any).services) {
|
||||
this._serviceCatalog = (msg as any).services;
|
||||
}
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
@@ -588,6 +593,14 @@ export class BrokerClient {
|
||||
private mcpCallResolvers = new Map<string, { resolve: (result: { result?: unknown; error?: string }) => void; timer: NodeJS.Timeout }>();
|
||||
/** Handler for inbound mcp_call_forward messages. Set by the MCP server. */
|
||||
private mcpCallForwardHandler: ((forward: { callId: string; serverName: string; toolName: string; args: Record<string, unknown>; callerName: string }) => Promise<{ result?: unknown; error?: string }>) | null = null;
|
||||
private vaultAckResolvers = new Map<string, { resolve: (ok: boolean) => void; timer: NodeJS.Timeout }>();
|
||||
private vaultListResolvers = new Map<string, { resolve: (entries: any[]) => void; timer: NodeJS.Timeout }>();
|
||||
private mcpDeployResolvers = new Map<string, { resolve: (result: any) => void; timer: NodeJS.Timeout }>();
|
||||
private mcpLogsResolvers = new Map<string, { resolve: (lines: string[]) => void; timer: NodeJS.Timeout }>();
|
||||
private mcpSchemaServiceResolvers = new Map<string, { resolve: (tools: any[]) => void; timer: NodeJS.Timeout }>();
|
||||
private mcpCatalogResolvers = new Map<string, { resolve: (services: any[]) => void; timer: NodeJS.Timeout }>();
|
||||
private mcpScopeResolvers = new Map<string, { resolve: (result: any) => void; timer: NodeJS.Timeout }>();
|
||||
private skillDeployResolvers = new Map<string, { resolve: (result: any) => void; timer: NodeJS.Timeout }>();
|
||||
|
||||
async messageStatus(messageId: string): Promise<{ messageId: string; targetSpec: string; delivered: boolean; deliveredAt: string | null; recipients: Array<{ name: string; pubkey: string; status: string }> } | null> {
|
||||
if (!this.ws || this.ws.readyState !== this.ws.OPEN) return null;
|
||||
@@ -1178,6 +1191,125 @@ export class BrokerClient {
|
||||
});
|
||||
}
|
||||
|
||||
// --- Vault ---
|
||||
|
||||
async vaultSet(key: string, ciphertext: string, nonce: string, sealedKey: string, entryType: "env" | "file", mountPath?: string, description?: string): Promise<boolean> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `vset_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
const timer = setTimeout(() => { this.vaultAckResolvers.delete(reqId); resolve(false); }, 10_000);
|
||||
this.vaultAckResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "vault_set", key, ciphertext, nonce, sealed_key: sealedKey, entry_type: entryType, mount_path: mountPath, description, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async vaultList(): Promise<any[]> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `vlist_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.vaultListResolvers.delete(reqId); resolve([]); }, 10_000);
|
||||
this.vaultListResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "vault_list", _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async vaultDelete(key: string): Promise<boolean> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `vdel_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.vaultAckResolvers.delete(reqId); resolve(false); }, 10_000);
|
||||
this.vaultAckResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "vault_delete", key, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
// --- MCP Deploy ---
|
||||
|
||||
async mcpDeploy(serverName: string, source: any, config?: any, scope?: any): Promise<any> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `deploy_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.mcpDeployResolvers.delete(reqId); resolve({ status: "timeout" }); }, 60_000);
|
||||
this.mcpDeployResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "mcp_deploy", server_name: serverName, source, config, scope, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async mcpUndeploy(serverName: string): Promise<boolean> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `undeploy_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.mcpDeployResolvers.delete(reqId); resolve(false); }, 10_000);
|
||||
this.mcpDeployResolvers.set(reqId, { resolve: (r: any) => resolve(r.status === "stopped"), timer });
|
||||
this.sendRaw({ type: "mcp_undeploy", server_name: serverName, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async mcpUpdate(serverName: string): Promise<any> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `update_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.mcpDeployResolvers.delete(reqId); resolve({ status: "timeout" }); }, 60_000);
|
||||
this.mcpDeployResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "mcp_update", server_name: serverName, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async mcpLogs(serverName: string, lines?: number): Promise<string[]> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `logs_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.mcpLogsResolvers.delete(reqId); resolve([]); }, 10_000);
|
||||
this.mcpLogsResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "mcp_logs", server_name: serverName, lines, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async mcpScope(serverName: string, scope?: any): Promise<any> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `scope_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.mcpScopeResolvers.delete(reqId); resolve({ scope: { type: "peer" }, deployed_by: "unknown" }); }, 10_000);
|
||||
this.mcpScopeResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "mcp_scope", server_name: serverName, scope, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async mcpServiceSchema(serverName: string, toolName?: string): Promise<any[]> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `schema_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.mcpSchemaServiceResolvers.delete(reqId); resolve([]); }, 10_000);
|
||||
this.mcpSchemaServiceResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "mcp_schema", server_name: serverName, tool_name: toolName, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async mcpCatalog(): Promise<any[]> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `catalog_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.mcpCatalogResolvers.delete(reqId); resolve([]); }, 10_000);
|
||||
this.mcpCatalogResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "mcp_catalog", _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
// --- Skill Deploy ---
|
||||
|
||||
async skillDeploy(source: any): Promise<any> {
|
||||
return new Promise(resolve => {
|
||||
const reqId = `skilldeploy_${Date.now()}`;
|
||||
const timer = setTimeout(() => { this.skillDeployResolvers.delete(reqId); resolve({ name: "unknown", files: [] }); }, 30_000);
|
||||
this.skillDeployResolvers.set(reqId, { resolve, timer });
|
||||
this.sendRaw({ type: "skill_deploy", source, _reqId: reqId } as any);
|
||||
});
|
||||
}
|
||||
|
||||
async getServiceTools(serviceName: string): Promise<any[]> {
|
||||
// Check cached catalog first
|
||||
const cached = this._serviceCatalog.find(s => s.name === serviceName);
|
||||
if (cached?.tools?.length) return cached.tools;
|
||||
// Fall back to schema query
|
||||
return this.mcpServiceSchema(serviceName);
|
||||
}
|
||||
|
||||
/** Send a raw JSON frame to the broker (fire-and-forget). */
|
||||
private sendRaw(payload: Record<string, unknown>): void {
|
||||
if (!this.ws || this.ws.readyState !== this.ws.OPEN) return;
|
||||
this.ws.send(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.stopStatsReporting();
|
||||
@@ -1730,6 +1862,78 @@ export class BrokerClient {
|
||||
this.resolveFromMap(this.webhookListResolvers, msgReqId, webhooks);
|
||||
return;
|
||||
}
|
||||
if (msg.type === "vault_ack") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.vaultAckResolvers.has(reqId)) {
|
||||
const r = this.vaultAckResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.vaultAckResolvers.delete(reqId);
|
||||
r.resolve(msg.action !== "not_found");
|
||||
}
|
||||
}
|
||||
if (msg.type === "vault_list_result") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.vaultListResolvers.has(reqId)) {
|
||||
const r = this.vaultListResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.vaultListResolvers.delete(reqId);
|
||||
r.resolve((msg as any).entries ?? []);
|
||||
}
|
||||
}
|
||||
if (msg.type === "mcp_deploy_status") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.mcpDeployResolvers.has(reqId)) {
|
||||
const r = this.mcpDeployResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.mcpDeployResolvers.delete(reqId);
|
||||
r.resolve({ status: (msg as any).status, tools: (msg as any).tools, error: (msg as any).error });
|
||||
}
|
||||
}
|
||||
if (msg.type === "mcp_logs_result") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.mcpLogsResolvers.has(reqId)) {
|
||||
const r = this.mcpLogsResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.mcpLogsResolvers.delete(reqId);
|
||||
r.resolve((msg as any).lines ?? []);
|
||||
}
|
||||
}
|
||||
if (msg.type === "mcp_schema_result") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.mcpSchemaServiceResolvers.has(reqId)) {
|
||||
const r = this.mcpSchemaServiceResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.mcpSchemaServiceResolvers.delete(reqId);
|
||||
r.resolve((msg as any).tools ?? []);
|
||||
}
|
||||
}
|
||||
if (msg.type === "mcp_catalog_result") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.mcpCatalogResolvers.has(reqId)) {
|
||||
const r = this.mcpCatalogResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.mcpCatalogResolvers.delete(reqId);
|
||||
r.resolve((msg as any).services ?? []);
|
||||
}
|
||||
}
|
||||
if (msg.type === "mcp_scope_result") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.mcpScopeResolvers.has(reqId)) {
|
||||
const r = this.mcpScopeResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.mcpScopeResolvers.delete(reqId);
|
||||
r.resolve({ scope: (msg as any).scope, deployed_by: (msg as any).deployed_by });
|
||||
}
|
||||
}
|
||||
if (msg.type === "skill_deploy_ack") {
|
||||
const reqId = (msg as any)._reqId;
|
||||
if (reqId && this.skillDeployResolvers.has(reqId)) {
|
||||
const r = this.skillDeployResolvers.get(reqId)!;
|
||||
clearTimeout(r.timer);
|
||||
this.skillDeployResolvers.delete(reqId);
|
||||
r.resolve({ name: (msg as any).name, files: (msg as any).files ?? [] });
|
||||
}
|
||||
}
|
||||
if (msg.type === "error") {
|
||||
this.debug(`broker error: ${msg.code} ${msg.message}`);
|
||||
const id = msg.id ? String(msg.id) : null;
|
||||
@@ -1787,6 +1991,14 @@ export class BrokerClient {
|
||||
[this.peerDirResponseResolvers, { error: "broker error" }],
|
||||
[this.webhookAckResolvers, null],
|
||||
[this.webhookListResolvers, []],
|
||||
[this.vaultAckResolvers, false],
|
||||
[this.vaultListResolvers, []],
|
||||
[this.mcpDeployResolvers, { status: "error" }],
|
||||
[this.mcpLogsResolvers, []],
|
||||
[this.mcpSchemaServiceResolvers, []],
|
||||
[this.mcpCatalogResolvers, []],
|
||||
[this.mcpScopeResolvers, { scope: { type: "peer" }, deployed_by: "unknown" }],
|
||||
[this.skillDeployResolvers, { name: "unknown", files: [] }],
|
||||
];
|
||||
for (const [map, defaultVal] of allMaps) {
|
||||
const first = (map as Map<string, any>).entries().next().value as [string, { resolve: (v: unknown) => void; timer: NodeJS.Timeout }] | undefined;
|
||||
|
||||
Reference in New Issue
Block a user