@mrciphersmith/roomyx 0.3.0 → 0.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.
@@ -1,9 +1,7 @@
1
- import { createServer } from "node:http";
2
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
1
  import { createRoomMcpServer } from "./index";
4
2
  import type { RoomMcpServerOptions } from "./index";
5
-
6
- const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
3
+ import { serveMcpOverHttp } from "./http-transport";
4
+ import type { McpHttpTransportHandle } from "./http-transport";
7
5
 
8
6
  export interface ServeOptions extends RoomMcpServerOptions {
9
7
  /** Defaults to 4319 (specification.md's default). 0 selects an ephemeral port. */
@@ -12,91 +10,20 @@ export interface ServeOptions extends RoomMcpServerOptions {
12
10
  acknowledgeNonLoopback?: boolean;
13
11
  }
14
12
 
15
- export interface ServeHandle {
16
- url: string;
17
- port: number;
18
- close(): Promise<void>;
19
- }
13
+ export type ServeHandle = McpHttpTransportHandle;
20
14
 
21
15
  /**
22
- * Binds `createRoomMcpServer(logPath)` to a loopback HTTP transport
23
- * (StreamableHTTP). Supports multiple, fully independent client sessions
24
- * against one long-lived server process — a single `StreamableHTTPServerTransport`
25
- * only ever completes ONE `initialize` handshake for its whole lifetime (an
26
- * independent review reproduced this concretely: a second client, even a
27
- * short-lived liveness check, gets "Server already initialized" and the
28
- * transport is permanently unusable afterward). Each new session (a request
29
- * with no `mcp-session-id` header) gets its own transport + `McpServer` pair,
30
- * tracked by session id via `onsessioninitialized`/`onsessionclosed`;
31
- * subsequent requests carrying that header are routed to the existing pair.
32
- * Refuses non-loopback hosts unless explicitly acknowledged (mirrors `keryx
33
- * serve`'s own convention — see docs/requirements/roomyx/decisions.md D-06).
16
+ * Serves one room log over the shared loopback HTTP transport. Everything about
17
+ * sessions, binding and shutdown lives in `./http-transport`; what belongs here
18
+ * is which server a session gets and which port it defaults to.
34
19
  */
35
20
  export async function serve(logPath: string, options: ServeOptions): Promise<ServeHandle> {
36
- const host = options.host ?? "127.0.0.1";
37
- if (!LOOPBACK_HOSTS.has(host) && !options.acknowledgeNonLoopback) {
38
- throw new Error(
39
- `Refusing to bind roomyx serve to non-loopback host "${host}" without --acknowledge-non-loopback.`,
40
- );
41
- }
42
-
43
- const sessions = new Map<string, StreamableHTTPServerTransport>();
44
-
45
- async function createSession(): Promise<StreamableHTTPServerTransport> {
46
- const transport = new StreamableHTTPServerTransport({
47
- sessionIdGenerator: () => crypto.randomUUID(),
48
- onsessioninitialized: (sessionId) => {
49
- sessions.set(sessionId, transport);
50
- },
51
- onsessionclosed: (sessionId) => {
52
- sessions.delete(sessionId);
53
- },
54
- });
55
- const mcpServer = createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand });
56
- await mcpServer.connect(transport);
57
- return transport;
58
- }
59
-
60
- const httpServer = createServer((req, res) => {
61
- const sessionIdHeader = req.headers["mcp-session-id"];
62
- const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
63
- const existing = sessionId ? sessions.get(sessionId) : undefined;
64
-
65
- const transportPromise = existing ? Promise.resolve(existing) : createSession();
66
- transportPromise
67
- .then((transport) => transport.handleRequest(req, res))
68
- .catch((error) => {
69
- if (!res.headersSent) {
70
- res.writeHead(500, { "content-type": "application/json" });
71
- }
72
- res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
73
- });
21
+ return serveMcpOverHttp({
22
+ createMcpServer: () => createRoomMcpServer(logPath, { onOwnerCommand: options.onOwnerCommand }),
23
+ commandLabel: "roomyx serve",
24
+ defaultPort: 4319,
25
+ port: options.port,
26
+ host: options.host,
27
+ acknowledgeNonLoopback: options.acknowledgeNonLoopback,
74
28
  });
75
-
76
- const port = options.port ?? 4319;
77
- try {
78
- await new Promise<void>((resolve, reject) => {
79
- httpServer.once("error", reject);
80
- httpServer.listen(port, host, () => resolve());
81
- });
82
- } catch (error) {
83
- await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
84
- throw error;
85
- }
86
-
87
- const address = httpServer.address();
88
- const actualPort = typeof address === "object" && address !== null ? address.port : port;
89
-
90
- return {
91
- url: `http://${host}:${actualPort}/mcp`,
92
- port: actualPort,
93
- close: () =>
94
- new Promise<void>((resolve, reject) => {
95
- httpServer.close(async (error) => {
96
- await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
97
- if (error) reject(error);
98
- else resolve();
99
- });
100
- }),
101
- };
102
29
  }
package/src/cli/seed.ts DELETED
@@ -1,73 +0,0 @@
1
- #!/usr/bin/env bun
2
- import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import type { GoalContract, MessageEnvelope, RosterEntry } from "../log/types";
4
-
5
- /**
6
- * Manual-testing helper: initializes a room log with a state header, or
7
- * appends one message to an existing log. Not part of the MCP server itself
8
- * (D-01 in docs/requirements/roomyx/decisions.md — only the dispatcher
9
- * writes the real log; this is a standalone fixture-seeding tool for local
10
- * development, not a live dispatcher integration).
11
- *
12
- * Usage:
13
- * bun src/cli/seed.ts init <path> --goal "<goal_statement>" --roster id1:Name1,id2:Name2
14
- * bun src/cli/seed.ts append <path> --from <id> --body "<text>" [--kind pitch] [--in-reply-to N]
15
- */
16
-
17
- function parseFlags(args: string[]): Record<string, string> {
18
- const flags: Record<string, string> = {};
19
- for (let i = 0; i < args.length; i++) {
20
- const arg = args[i];
21
- if (arg?.startsWith("--")) {
22
- flags[arg.slice(2)] = args[i + 1] ?? "";
23
- i++;
24
- }
25
- }
26
- return flags;
27
- }
28
-
29
- function nextSeq(path: string): number {
30
- if (!existsSync(path)) return 1;
31
- const lines = readFileSync(path, "utf8")
32
- .split("\n")
33
- .filter((l) => l.trim().length > 0);
34
- const messageSeqs = lines
35
- .slice(1)
36
- .map((l) => (JSON.parse(l) as { seq: number }).seq);
37
- return messageSeqs.length > 0 ? Math.max(...messageSeqs) + 1 : 1;
38
- }
39
-
40
- const [command, path, ...rest] = process.argv.slice(2);
41
- const flags = parseFlags(rest);
42
-
43
- if (command === "init" && path) {
44
- const roster: RosterEntry[] = (flags.roster ?? "")
45
- .split(",")
46
- .filter(Boolean)
47
- .map((pair) => {
48
- const [id, name] = pair.split(":");
49
- return { id: id ?? "", name: name ?? id ?? "" };
50
- });
51
- const goalContract: GoalContract = {
52
- version: 1,
53
- goal_statement: flags.goal ?? "Untitled room",
54
- criteria: flags.criteria ?? "",
55
- threshold: { fail_below: 60, pass_at_or_above: 80 },
56
- };
57
- writeFileSync(path, JSON.stringify({ type: "state", goal_contract: goalContract, roster }) + "\n");
58
- console.log(`Initialized ${path} with ${roster.length} roster entries.`);
59
- } else if (command === "append" && path) {
60
- const message: MessageEnvelope & { type: "message" } = {
61
- type: "message",
62
- seq: nextSeq(path),
63
- from: flags.from ?? "unknown",
64
- body: flags.body ?? "",
65
- ...(flags.kind ? { kind: flags.kind as MessageEnvelope["kind"] } : {}),
66
- ...(flags["in-reply-to"] ? { in_reply_to: Number(flags["in-reply-to"]) } : {}),
67
- };
68
- appendFileSync(path, JSON.stringify(message) + "\n");
69
- console.log(`Appended seq ${message.seq} from ${message.from} to ${path}.`);
70
- } else {
71
- console.error("Usage: bun src/cli/seed.ts init|append <path> [--flags...]");
72
- process.exit(1);
73
- }