@mrciphersmith/roomyx 0.1.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.
@@ -0,0 +1,113 @@
1
+ import { createServer } from "node:http";
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
4
+ import { z } from "zod";
5
+ import { listLiveRooms } from "../installer/registry";
6
+ import { syncSkill } from "../installer/skill-sync";
7
+
8
+ export interface ManagementOptions {
9
+ registryPath: string;
10
+ bundledSkillPath: string;
11
+ configPath: string;
12
+ }
13
+
14
+ export interface ManagementServeOptions {
15
+ port: number;
16
+ host?: string;
17
+ }
18
+
19
+ /**
20
+ * Second, standalone MCP server (independent of the per-room server in
21
+ * ../server/index.ts) exposing skill-sync and room-listing as tools any MCP
22
+ * client (Claude Code, Codex, keryx) can call directly. See
23
+ * docs/requirements/roomyx-installer/specification.md "MCP Management
24
+ * Server".
25
+ */
26
+ export function createManagementMcpServer(options: ManagementOptions): McpServer {
27
+ const server = new McpServer({ name: "roomyx-management", version: "0.1.0" });
28
+
29
+ server.registerTool(
30
+ "roomyx.rooms.list",
31
+ {
32
+ title: "List live rooms",
33
+ description: "Rooms currently registered and confirmed live (liveness-checked, not just registry presence).",
34
+ },
35
+ async () => ({
36
+ content: [{ type: "text", text: JSON.stringify(await listLiveRooms(options.registryPath)) }],
37
+ }),
38
+ );
39
+
40
+ server.registerTool(
41
+ "roomyx.skills.sync",
42
+ {
43
+ title: "Sync the bundled startup-room skill",
44
+ description: "Diffs/backs-up/writes the bundled skill into a target path (see decisions.md D-02 for safety rules).",
45
+ inputSchema: {
46
+ targetPath: z.string().min(1),
47
+ dryRun: z.boolean().optional(),
48
+ yes: z.boolean().optional(),
49
+ },
50
+ },
51
+ async ({ targetPath, dryRun, yes }) => ({
52
+ content: [
53
+ {
54
+ type: "text",
55
+ text: JSON.stringify(
56
+ syncSkill({
57
+ bundledSkillPath: options.bundledSkillPath,
58
+ targetPath,
59
+ configPath: options.configPath,
60
+ dryRun,
61
+ yes,
62
+ }),
63
+ ),
64
+ },
65
+ ],
66
+ }),
67
+ );
68
+
69
+ return server;
70
+ }
71
+
72
+ export interface ManagementHandle {
73
+ url: string;
74
+ port: number;
75
+ close(): Promise<void>;
76
+ }
77
+
78
+ /** Binds createManagementMcpServer() to a loopback HTTP transport, same pattern as ../server/serve.ts. */
79
+ export async function serveManagement(
80
+ options: ManagementOptions,
81
+ serveOptions: ManagementServeOptions,
82
+ ): Promise<ManagementHandle> {
83
+ const host = serveOptions.host ?? "127.0.0.1";
84
+ const mcpServer = createManagementMcpServer(options);
85
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => crypto.randomUUID() });
86
+ await mcpServer.connect(transport);
87
+
88
+ const httpServer = createServer((req, res) => {
89
+ transport.handleRequest(req, res).catch((error) => {
90
+ if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
91
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
92
+ });
93
+ });
94
+
95
+ try {
96
+ await new Promise<void>((resolve, reject) => {
97
+ httpServer.once("error", reject);
98
+ httpServer.listen(serveOptions.port, host, () => resolve());
99
+ });
100
+ } catch (error) {
101
+ await mcpServer.close().catch(() => undefined);
102
+ throw error;
103
+ }
104
+
105
+ const address = httpServer.address();
106
+ const actualPort = typeof address === "object" && address !== null ? address.port : serveOptions.port;
107
+
108
+ return {
109
+ url: `http://${host}:${actualPort}/mcp`,
110
+ port: actualPort,
111
+ close: () => new Promise<void>((resolve, reject) => httpServer.close((err) => (err ? reject(err) : resolve()))),
112
+ };
113
+ }
@@ -0,0 +1,52 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { getStateTool } from "./tools/get-state";
4
+ import { getTranscriptTool } from "./tools/get-transcript";
5
+ import { getAgentDetailTool } from "./tools/get-agent-detail";
6
+
7
+ /**
8
+ * Builds the roomyx MCP server for a given room log file. Read-only: none
9
+ * of the three registered tools ever writes to `logPath` (R2-R4, AC4 —
10
+ * `room.post_owner_command`, the write path, is out of scope for this
11
+ * package; see docs/requirements/roomyx/).
12
+ */
13
+ export function createRoomMcpServer(logPath: string): McpServer {
14
+ const server = new McpServer({ name: "roomyx", version: "0.1.0" });
15
+
16
+ server.registerTool(
17
+ "room.get_state",
18
+ {
19
+ title: "Room state",
20
+ description: "Roster and current goal contract for this room.",
21
+ },
22
+ async () => ({
23
+ content: [{ type: "text", text: JSON.stringify(getStateTool(logPath)) }],
24
+ }),
25
+ );
26
+
27
+ server.registerTool(
28
+ "room.get_transcript",
29
+ {
30
+ title: "Room transcript delta",
31
+ description: "Messages with seq greater than since_seq, in order.",
32
+ inputSchema: { since_seq: z.number().int().min(0) },
33
+ },
34
+ async ({ since_seq }) => ({
35
+ content: [{ type: "text", text: JSON.stringify(getTranscriptTool(logPath, since_seq)) }],
36
+ }),
37
+ );
38
+
39
+ server.registerTool(
40
+ "room.get_agent_detail",
41
+ {
42
+ title: "Agent detail",
43
+ description: "One participant's own messages and last-seen status.",
44
+ inputSchema: { agent_id: z.string().min(1) },
45
+ },
46
+ async ({ agent_id }) => ({
47
+ content: [{ type: "text", text: JSON.stringify(getAgentDetailTool(logPath, agent_id)) }],
48
+ }),
49
+ );
50
+
51
+ return server;
52
+ }
@@ -0,0 +1,101 @@
1
+ import { createServer } from "node:http";
2
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
+ import { createRoomMcpServer } from "./index";
4
+
5
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
6
+
7
+ export interface ServeOptions {
8
+ /** Defaults to 4319 (specification.md's default). 0 selects an ephemeral port. */
9
+ port?: number;
10
+ host?: string;
11
+ acknowledgeNonLoopback?: boolean;
12
+ }
13
+
14
+ export interface ServeHandle {
15
+ url: string;
16
+ port: number;
17
+ close(): Promise<void>;
18
+ }
19
+
20
+ /**
21
+ * Binds `createRoomMcpServer(logPath)` to a loopback HTTP transport
22
+ * (StreamableHTTP). Supports multiple, fully independent client sessions
23
+ * against one long-lived server process — a single `StreamableHTTPServerTransport`
24
+ * only ever completes ONE `initialize` handshake for its whole lifetime (an
25
+ * independent review reproduced this concretely: a second client, even a
26
+ * short-lived liveness check, gets "Server already initialized" and the
27
+ * transport is permanently unusable afterward). Each new session (a request
28
+ * with no `mcp-session-id` header) gets its own transport + `McpServer` pair,
29
+ * tracked by session id via `onsessioninitialized`/`onsessionclosed`;
30
+ * subsequent requests carrying that header are routed to the existing pair.
31
+ * Refuses non-loopback hosts unless explicitly acknowledged (mirrors `keryx
32
+ * serve`'s own convention — see docs/requirements/roomyx/decisions.md D-06).
33
+ */
34
+ export async function serve(logPath: string, options: ServeOptions): Promise<ServeHandle> {
35
+ const host = options.host ?? "127.0.0.1";
36
+ if (!LOOPBACK_HOSTS.has(host) && !options.acknowledgeNonLoopback) {
37
+ throw new Error(
38
+ `Refusing to bind roomyx serve to non-loopback host "${host}" without --acknowledge-non-loopback.`,
39
+ );
40
+ }
41
+
42
+ const sessions = new Map<string, StreamableHTTPServerTransport>();
43
+
44
+ async function createSession(): Promise<StreamableHTTPServerTransport> {
45
+ const transport = new StreamableHTTPServerTransport({
46
+ sessionIdGenerator: () => crypto.randomUUID(),
47
+ onsessioninitialized: (sessionId) => {
48
+ sessions.set(sessionId, transport);
49
+ },
50
+ onsessionclosed: (sessionId) => {
51
+ sessions.delete(sessionId);
52
+ },
53
+ });
54
+ const mcpServer = createRoomMcpServer(logPath);
55
+ await mcpServer.connect(transport);
56
+ return transport;
57
+ }
58
+
59
+ const httpServer = createServer((req, res) => {
60
+ const sessionIdHeader = req.headers["mcp-session-id"];
61
+ const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
62
+ const existing = sessionId ? sessions.get(sessionId) : undefined;
63
+
64
+ const transportPromise = existing ? Promise.resolve(existing) : createSession();
65
+ transportPromise
66
+ .then((transport) => transport.handleRequest(req, res))
67
+ .catch((error) => {
68
+ if (!res.headersSent) {
69
+ res.writeHead(500, { "content-type": "application/json" });
70
+ }
71
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
72
+ });
73
+ });
74
+
75
+ const port = options.port ?? 4319;
76
+ try {
77
+ await new Promise<void>((resolve, reject) => {
78
+ httpServer.once("error", reject);
79
+ httpServer.listen(port, host, () => resolve());
80
+ });
81
+ } catch (error) {
82
+ await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
83
+ throw error;
84
+ }
85
+
86
+ const address = httpServer.address();
87
+ const actualPort = typeof address === "object" && address !== null ? address.port : port;
88
+
89
+ return {
90
+ url: `http://${host}:${actualPort}/mcp`,
91
+ port: actualPort,
92
+ close: () =>
93
+ new Promise<void>((resolve, reject) => {
94
+ httpServer.close(async (error) => {
95
+ await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
96
+ if (error) reject(error);
97
+ else resolve();
98
+ });
99
+ }),
100
+ };
101
+ }
@@ -0,0 +1,8 @@
1
+ import { getAgentDetail, loadRoomLog } from "../../log/store";
2
+ import type { AgentDetail } from "../../log/types";
3
+
4
+ /** MCP tool `room.get_agent_detail`: one participant's own messages + status. Read-only. */
5
+ export function getAgentDetailTool(logPath: string, agentId: string): AgentDetail {
6
+ const { state, messages } = loadRoomLog(logPath);
7
+ return getAgentDetail(messages, state.roster, agentId);
8
+ }
@@ -0,0 +1,8 @@
1
+ import { loadRoomLog } from "../../log/store";
2
+ import type { RoomState } from "../../log/types";
3
+
4
+ /** MCP tool `room.get_state`: roster + current goal contract. Read-only. */
5
+ export function getStateTool(logPath: string): RoomState {
6
+ const { state } = loadRoomLog(logPath);
7
+ return state;
8
+ }
@@ -0,0 +1,8 @@
1
+ import { getTranscript, loadRoomLog } from "../../log/store";
2
+ import type { MessageEnvelope } from "../../log/types";
3
+
4
+ /** MCP tool `room.get_transcript`: messages with seq > sinceSeq. Read-only. */
5
+ export function getTranscriptTool(logPath: string, sinceSeq: number): MessageEnvelope[] {
6
+ const { messages } = loadRoomLog(logPath);
7
+ return getTranscript(messages, sinceSeq);
8
+ }