@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.
- package/CHANGELOG.md +173 -0
- package/README.md +53 -13
- package/package.json +5 -4
- package/src/bin/launch.mjs +68 -0
- package/src/bin/roomyx-client.mjs +8 -0
- package/src/bin/roomyx.mjs +4 -0
- package/src/bundled-skills/startup-room/SKILL.md +177 -47
- package/src/cli/args.ts +155 -0
- package/src/cli/specs.ts +16 -0
- package/src/cli.ts +313 -150
- package/src/client/components/status-bar.ts +12 -0
- package/src/client/index.ts +78 -24
- package/src/client/mcp-client.ts +9 -0
- package/src/client/owner-prompt.ts +92 -0
- package/src/log/write.ts +80 -0
- package/src/mcp-management/server.ts +38 -97
- package/src/server/http-transport.ts +149 -0
- package/src/server/serve.ts +13 -86
- package/src/cli/seed.ts +0 -73
package/src/client/index.ts
CHANGED
|
@@ -6,26 +6,26 @@ import { ChatView } from "./screens/chat-view";
|
|
|
6
6
|
import { AgentModal } from "./screens/agent-modal";
|
|
7
7
|
import type { RosterEntry } from "../log/types";
|
|
8
8
|
import { resolveConnectionUrl } from "../installer/resolve-connection";
|
|
9
|
+
import { IDLE, ownerPromptLine, stepOwnerPrompt } from "./owner-prompt";
|
|
10
|
+
import type { OwnerPromptState } from "./owner-prompt";
|
|
11
|
+
import { ArgError, parseArgs, renderFlags } from "../cli/args";
|
|
12
|
+
import type { FlagValues } from "../cli/args";
|
|
13
|
+
import { CLIENT_FLAGS } from "../cli/specs";
|
|
9
14
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export async function runClient(argv: string[] = process.argv.slice(2)): Promise<void> {
|
|
23
|
-
const flags = parseFlags(argv);
|
|
24
|
-
const registryPath = flags["registry"] ?? join(process.cwd(), ".roomyx", "rooms", "registry.json");
|
|
15
|
+
/**
|
|
16
|
+
* Takes already-parsed flags rather than argv, so the two entry points — this
|
|
17
|
+
* file as a binary, and `roomyx client` — cannot disagree about what a flag
|
|
18
|
+
* means. They previously had one scanner each, which is how a bare
|
|
19
|
+
* `--registry` became `""` here (and `""` is not nullish, so it beat the
|
|
20
|
+
* default) while becoming `true` in the other.
|
|
21
|
+
*/
|
|
22
|
+
export async function runClient(flags: FlagValues): Promise<void> {
|
|
23
|
+
const registryPath =
|
|
24
|
+
typeof flags.registry === "string" ? flags.registry : join(process.cwd(), ".roomyx", "rooms", "registry.json");
|
|
25
25
|
|
|
26
26
|
const resolved = await resolveConnectionUrl({
|
|
27
|
-
connect: flags.connect,
|
|
28
|
-
room: flags.room,
|
|
27
|
+
connect: typeof flags.connect === "string" ? flags.connect : undefined,
|
|
28
|
+
room: typeof flags.room === "string" ? flags.room : undefined,
|
|
29
29
|
registryPath,
|
|
30
30
|
});
|
|
31
31
|
|
|
@@ -73,11 +73,48 @@ export async function runClient(argv: string[] = process.argv.slice(2)): Promise
|
|
|
73
73
|
);
|
|
74
74
|
roomClient.start();
|
|
75
75
|
|
|
76
|
+
let prompt: OwnerPromptState = IDLE;
|
|
77
|
+
|
|
78
|
+
function showPrompt(): void {
|
|
79
|
+
chatView.statusBar.setNotice(ownerPromptLine(prompt));
|
|
80
|
+
}
|
|
81
|
+
|
|
76
82
|
renderer.keyInput.on("keypress", (event) => {
|
|
77
83
|
if (modal.isVisible()) {
|
|
78
84
|
if (event.name === "escape") modal.hide();
|
|
79
85
|
return;
|
|
80
86
|
}
|
|
87
|
+
|
|
88
|
+
// The prompt owns the keyboard while it is open — otherwise typing "q"
|
|
89
|
+
// into a veto would quit the client.
|
|
90
|
+
if (prompt.stage !== "idle" || (event.name === "o" && !event.ctrl)) {
|
|
91
|
+
const stepped = stepOwnerPrompt(prompt, event);
|
|
92
|
+
prompt = stepped.state;
|
|
93
|
+
showPrompt();
|
|
94
|
+
if (stepped.action.type === "send") {
|
|
95
|
+
const { kind, body } = stepped.action;
|
|
96
|
+
chatView.statusBar.setNotice(`${kind}: sending…`);
|
|
97
|
+
void roomClient
|
|
98
|
+
.postOwnerCommand(kind, body)
|
|
99
|
+
.then((result) => {
|
|
100
|
+
chatView.statusBar.setNotice(
|
|
101
|
+
result.accepted
|
|
102
|
+
? `${kind} accepted${result.reason ? ` — ${result.reason}` : ""}`
|
|
103
|
+
: `${kind} not accepted — ${result.reason ?? "no reason given"}`,
|
|
104
|
+
);
|
|
105
|
+
})
|
|
106
|
+
.catch((error: unknown) => {
|
|
107
|
+
chatView.statusBar.setNotice(
|
|
108
|
+
`${kind} failed — ${error instanceof Error ? error.message : String(error)}`,
|
|
109
|
+
);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Any other key clears a leftover result line and falls through.
|
|
116
|
+
chatView.statusBar.setNotice(null);
|
|
117
|
+
|
|
81
118
|
if (event.name === "up") chatView.roster.moveSelection(-1);
|
|
82
119
|
else if (event.name === "down") chatView.roster.moveSelection(1);
|
|
83
120
|
else if (event.name === "return") chatView.roster.confirmSelection();
|
|
@@ -90,12 +127,29 @@ export async function runClient(argv: string[] = process.argv.slice(2)): Promise
|
|
|
90
127
|
});
|
|
91
128
|
}
|
|
92
129
|
|
|
130
|
+
const CLIENT_USAGE = ["roomyx-client [flags]", "", " attach the terminal UI to a live room", "", renderFlags(CLIENT_FLAGS)].join(
|
|
131
|
+
"\n",
|
|
132
|
+
);
|
|
133
|
+
|
|
93
134
|
if (import.meta.main) {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
135
|
+
void (async () => {
|
|
136
|
+
try {
|
|
137
|
+
const parsed = parseArgs(process.argv.slice(2), CLIENT_FLAGS);
|
|
138
|
+
if (parsed.help) {
|
|
139
|
+
console.log(CLIENT_USAGE);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
await runClient(parsed.flags);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
// The message, not the object: a stack trace dumped at someone who
|
|
145
|
+
// simply hasn't started a room yet reads as a crash, and matches how
|
|
146
|
+
// cli.ts reports its own failures.
|
|
147
|
+
if (error instanceof ArgError) {
|
|
148
|
+
console.error(error.message);
|
|
149
|
+
} else {
|
|
150
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
151
|
+
}
|
|
152
|
+
process.exit(1);
|
|
153
|
+
}
|
|
154
|
+
})();
|
|
101
155
|
}
|
package/src/client/mcp-client.ts
CHANGED
|
@@ -101,6 +101,15 @@ export class RoomClient {
|
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Sends an owner command to the room's dispatcher. Not a write to the log —
|
|
106
|
+
* the server forwards it and answers with whatever the dispatcher said,
|
|
107
|
+
* including `accepted: false` when no dispatcher is attached at all.
|
|
108
|
+
*/
|
|
109
|
+
async postOwnerCommand(kind: string, body: string): Promise<{ accepted: boolean; reason?: string }> {
|
|
110
|
+
return this.callTool<{ accepted: boolean; reason?: string }>("room.post_owner_command", { kind, body });
|
|
111
|
+
}
|
|
112
|
+
|
|
104
113
|
private async callTool<T>(name: string, args: Record<string, unknown>): Promise<T> {
|
|
105
114
|
if (!this.client) throw new Error("not connected");
|
|
106
115
|
const result = await this.client.callTool({ name, arguments: args });
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { OWNER_COMMAND_KINDS } from "../server/index";
|
|
2
|
+
import type { OwnerCommandKind } from "../server/index";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The owner-command prompt, as a pure state machine.
|
|
6
|
+
*
|
|
7
|
+
* Kept separate from `index.ts` because that file cannot run without a real
|
|
8
|
+
* terminal: it builds a renderer on import. The composing logic — which keys
|
|
9
|
+
* open the prompt, what a half-typed command looks like, when Enter actually
|
|
10
|
+
* sends — is the part worth testing, so it lives where a test can reach it.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type OwnerPromptState =
|
|
14
|
+
| { stage: "idle" }
|
|
15
|
+
| { stage: "kind" }
|
|
16
|
+
| { stage: "body"; kind: OwnerCommandKind; buffer: string };
|
|
17
|
+
|
|
18
|
+
export type OwnerPromptAction =
|
|
19
|
+
| { type: "none" }
|
|
20
|
+
| { type: "cancel" }
|
|
21
|
+
| { type: "send"; kind: OwnerCommandKind; body: string };
|
|
22
|
+
|
|
23
|
+
export interface PromptKey {
|
|
24
|
+
name: string;
|
|
25
|
+
sequence?: string;
|
|
26
|
+
ctrl?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** First letter of each kind, which is what the prompt asks for. */
|
|
30
|
+
const KIND_BY_LETTER: Record<string, OwnerCommandKind> = {
|
|
31
|
+
v: "veto",
|
|
32
|
+
c: "constraint",
|
|
33
|
+
a: "add_participant",
|
|
34
|
+
g: "goal_edit",
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const IDLE: OwnerPromptState = { stage: "idle" };
|
|
38
|
+
|
|
39
|
+
/** The status line to show for a state, or null to leave the bar alone. */
|
|
40
|
+
export function ownerPromptLine(state: OwnerPromptState): string | null {
|
|
41
|
+
if (state.stage === "idle") return null;
|
|
42
|
+
if (state.stage === "kind") {
|
|
43
|
+
return "owner command — (v)eto (c)onstraint (a)dd participant (g)oal edit, Esc to cancel";
|
|
44
|
+
}
|
|
45
|
+
return `${state.kind}: ${state.buffer}▌ (Enter to send, Esc to cancel)`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function isPrintable(key: PromptKey): boolean {
|
|
49
|
+
return !key.ctrl && typeof key.sequence === "string" && key.sequence.length === 1 && key.sequence >= " ";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function stepOwnerPrompt(
|
|
53
|
+
state: OwnerPromptState,
|
|
54
|
+
key: PromptKey,
|
|
55
|
+
): { state: OwnerPromptState; action: OwnerPromptAction } {
|
|
56
|
+
const none = (next: OwnerPromptState) => ({ state: next, action: { type: "none" } as OwnerPromptAction });
|
|
57
|
+
|
|
58
|
+
if (state.stage === "idle") {
|
|
59
|
+
// `o` opens the prompt. Everything else belongs to the view's own keys.
|
|
60
|
+
return key.name === "o" && !key.ctrl ? none({ stage: "kind" }) : none(state);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (key.name === "escape") {
|
|
64
|
+
return { state: IDLE, action: { type: "cancel" } };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (state.stage === "kind") {
|
|
68
|
+
const kind = KIND_BY_LETTER[key.sequence ?? ""];
|
|
69
|
+
// An unrecognised letter is ignored rather than cancelling: a typo should
|
|
70
|
+
// not throw away a prompt the person deliberately opened.
|
|
71
|
+
return kind ? none({ stage: "body", kind, buffer: "" }) : none(state);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (key.name === "return") {
|
|
75
|
+
// An empty body is not a command. Stay put rather than sending nothing.
|
|
76
|
+
if (state.buffer.trim().length === 0) return none(state);
|
|
77
|
+
return { state: IDLE, action: { type: "send", kind: state.kind, body: state.buffer.trim() } };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (key.name === "backspace") {
|
|
81
|
+
return none({ ...state, buffer: state.buffer.slice(0, -1) });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (isPrintable(key)) {
|
|
85
|
+
return none({ ...state, buffer: state.buffer + key.sequence });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return none(state);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export { OWNER_COMMAND_KINDS };
|
|
92
|
+
export type { OwnerCommandKind };
|
package/src/log/write.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import type { GoalContract, MessageEnvelope, RosterEntry } from "./types";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The write side of a room log, which `store.ts` reads.
|
|
8
|
+
*
|
|
9
|
+
* D-01 keeps one writer per *live* room. That constrains the server, not the
|
|
10
|
+
* package — creating a log nobody is serving takes the writer count from zero
|
|
11
|
+
* to one, and there is no race to lose. Appending to a log a dispatcher is
|
|
12
|
+
* actively writing is the case that would break the invariant, so the CLI
|
|
13
|
+
* checks the registry before doing it. See D-01a.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export interface CreateRoomLogOptions {
|
|
17
|
+
goalStatement: string;
|
|
18
|
+
criteria?: string;
|
|
19
|
+
roster: RosterEntry[];
|
|
20
|
+
threshold?: GoalContract["threshold"];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface AppendMessageOptions {
|
|
24
|
+
from: string;
|
|
25
|
+
body: string;
|
|
26
|
+
kind?: MessageEnvelope["kind"];
|
|
27
|
+
inReplyTo?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Refuses to overwrite: a room log is append-only, and clobbering one loses a session. */
|
|
31
|
+
export function createRoomLog(path: string, options: CreateRoomLogOptions): void {
|
|
32
|
+
if (existsSync(path)) {
|
|
33
|
+
throw new Error(`${path} already exists. A room log is append-only; refusing to overwrite it.`);
|
|
34
|
+
}
|
|
35
|
+
const goalContract: GoalContract = {
|
|
36
|
+
version: 1,
|
|
37
|
+
goal_statement: options.goalStatement,
|
|
38
|
+
criteria: options.criteria ?? "",
|
|
39
|
+
threshold: options.threshold ?? { fail_below: 60, pass_at_or_above: 80 },
|
|
40
|
+
};
|
|
41
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
42
|
+
writeFileSync(path, JSON.stringify({ type: "state", goal_contract: goalContract, roster: options.roster }) + "\n");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The next `seq`, derived from the log rather than tracked separately. */
|
|
46
|
+
export function nextSeq(path: string): number {
|
|
47
|
+
if (!existsSync(path)) return 1;
|
|
48
|
+
const lines = readFileSync(path, "utf8")
|
|
49
|
+
.split("\n")
|
|
50
|
+
.filter((line) => line.trim().length > 0);
|
|
51
|
+
const seqs = lines.slice(1).map((line) => (JSON.parse(line) as { seq: number }).seq);
|
|
52
|
+
return seqs.length > 0 ? Math.max(...seqs) + 1 : 1;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function appendMessage(path: string, options: AppendMessageOptions): MessageEnvelope & { type: "message" } {
|
|
56
|
+
if (!existsSync(path)) {
|
|
57
|
+
throw new Error(`${path} does not exist. Create it with \`roomyx room new\` first.`);
|
|
58
|
+
}
|
|
59
|
+
const message: MessageEnvelope & { type: "message" } = {
|
|
60
|
+
type: "message",
|
|
61
|
+
seq: nextSeq(path),
|
|
62
|
+
from: options.from,
|
|
63
|
+
body: options.body,
|
|
64
|
+
...(options.kind ? { kind: options.kind } : {}),
|
|
65
|
+
...(options.inReplyTo !== undefined ? { in_reply_to: options.inReplyTo } : {}),
|
|
66
|
+
};
|
|
67
|
+
appendFileSync(path, JSON.stringify(message) + "\n");
|
|
68
|
+
return message;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** `id:Name,id2:Name2` — the shape the CLI takes and the log stores. */
|
|
72
|
+
export function parseRoster(spec: string): RosterEntry[] {
|
|
73
|
+
return spec
|
|
74
|
+
.split(",")
|
|
75
|
+
.filter(Boolean)
|
|
76
|
+
.map((pair) => {
|
|
77
|
+
const [id, name] = pair.split(":");
|
|
78
|
+
return { id: id ?? "", name: name ?? id ?? "" };
|
|
79
|
+
});
|
|
80
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { createServer } from "node:http";
|
|
2
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
-
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
2
|
import { z } from "zod";
|
|
3
|
+
import { serveMcpOverHttp } from "../server/http-transport";
|
|
4
|
+
import type { McpHttpTransportHandle } from "../server/http-transport";
|
|
5
5
|
import { listLiveRooms } from "../installer/registry";
|
|
6
6
|
import { syncSkill } from "../installer/skill-sync";
|
|
7
7
|
import { NAMED_TARGETS, resolveTargets } from "../installer/skill-targets";
|
|
@@ -10,6 +10,15 @@ export interface ManagementOptions {
|
|
|
10
10
|
registryPath: string;
|
|
11
11
|
bundledSkillPath: string;
|
|
12
12
|
configPath: string;
|
|
13
|
+
/**
|
|
14
|
+
* The project a project-scoped target resolves against — `keryx` keeps its
|
|
15
|
+
* skills in `<project>/.metaproject/project-skills/`. Defaults to
|
|
16
|
+
* `process.cwd()`, which is right for `roomyx mcp` and wrong for a
|
|
17
|
+
* long-lived embedded server whose working directory is somebody else's.
|
|
18
|
+
* Every other path this server touches is already explicit; this one was
|
|
19
|
+
* the exception.
|
|
20
|
+
*/
|
|
21
|
+
cwd?: string;
|
|
13
22
|
}
|
|
14
23
|
|
|
15
24
|
export interface ManagementServeOptions {
|
|
@@ -45,33 +54,21 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
|
|
|
45
54
|
{
|
|
46
55
|
title: "Sync the bundled startup-room skill",
|
|
47
56
|
description:
|
|
48
|
-
"Diffs/backs-up/writes the bundled skill into a
|
|
57
|
+
"Diffs/backs-up/writes the bundled skill into a named runtime's skill location (see decisions.md D-02 for safety rules).",
|
|
49
58
|
inputSchema: {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
59
|
+
// Named targets only. This tool used to accept a literal `targetPath`,
|
|
60
|
+
// which made it an arbitrary-path file writer reachable over a loopback
|
|
61
|
+
// port with no authentication — a browser on any page the operator
|
|
62
|
+
// visits could drive it cross-origin. The CLI keeps the literal-path
|
|
63
|
+
// escape hatch, because that is the operator on their own machine;
|
|
64
|
+
// the network surface does not get one.
|
|
65
|
+
target: z.enum([...NAMED_TARGETS, "all"]).describe("A runtime by name, or `all`."),
|
|
55
66
|
dryRun: z.boolean().optional(),
|
|
56
67
|
yes: z.boolean().optional(),
|
|
57
68
|
},
|
|
58
69
|
},
|
|
59
|
-
async ({ target,
|
|
60
|
-
|
|
61
|
-
// schema without excluding the other.
|
|
62
|
-
if (!target && !targetPath) {
|
|
63
|
-
return {
|
|
64
|
-
content: [
|
|
65
|
-
{
|
|
66
|
-
type: "text",
|
|
67
|
-
text: JSON.stringify({
|
|
68
|
-
error: `Pass either target (${[...NAMED_TARGETS, "all"].join(", ")}) or targetPath.`,
|
|
69
|
-
}),
|
|
70
|
-
},
|
|
71
|
-
],
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
const targets = targetPath ? [{ name: targetPath, path: targetPath }] : resolveTargets(target as string);
|
|
70
|
+
async ({ target, dryRun, yes }) => {
|
|
71
|
+
const targets = resolveTargets(target, options.cwd);
|
|
75
72
|
const results = targets.map(({ name, path }) => ({
|
|
76
73
|
target: name,
|
|
77
74
|
path,
|
|
@@ -90,86 +87,30 @@ export function createManagementMcpServer(options: ManagementOptions): McpServer
|
|
|
90
87
|
return server;
|
|
91
88
|
}
|
|
92
89
|
|
|
93
|
-
export
|
|
94
|
-
url: string;
|
|
95
|
-
port: number;
|
|
96
|
-
close(): Promise<void>;
|
|
97
|
-
}
|
|
90
|
+
export type ManagementHandle = McpHttpTransportHandle;
|
|
98
91
|
|
|
99
|
-
|
|
92
|
+
export interface ManagementServeOptions {
|
|
93
|
+
/** Defaults to 4320 so it does not collide with `roomyx serve` (4319). 0 selects an ephemeral port. */
|
|
94
|
+
port?: number;
|
|
95
|
+
host?: string;
|
|
96
|
+
acknowledgeNonLoopback?: boolean;
|
|
97
|
+
}
|
|
100
98
|
|
|
101
99
|
/**
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
* gets its own transport + McpServer pair.
|
|
100
|
+
* Serves the management tools over the shared loopback HTTP transport. The
|
|
101
|
+
* session, binding and shutdown behaviour is `../server/http-transport`'s —
|
|
102
|
+
* this file used to carry its own copy, and the copies had already drifted.
|
|
106
103
|
*/
|
|
107
104
|
export async function serveManagement(
|
|
108
105
|
options: ManagementOptions,
|
|
109
106
|
serveOptions: ManagementServeOptions,
|
|
110
107
|
): Promise<ManagementHandle> {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const sessions = new Map<string, StreamableHTTPServerTransport>();
|
|
119
|
-
|
|
120
|
-
async function createSession(): Promise<StreamableHTTPServerTransport> {
|
|
121
|
-
const transport = new StreamableHTTPServerTransport({
|
|
122
|
-
sessionIdGenerator: () => crypto.randomUUID(),
|
|
123
|
-
onsessioninitialized: (sessionId) => {
|
|
124
|
-
sessions.set(sessionId, transport);
|
|
125
|
-
},
|
|
126
|
-
onsessionclosed: (sessionId) => {
|
|
127
|
-
sessions.delete(sessionId);
|
|
128
|
-
},
|
|
129
|
-
});
|
|
130
|
-
const mcpServer = createManagementMcpServer(options);
|
|
131
|
-
await mcpServer.connect(transport);
|
|
132
|
-
return transport;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
const httpServer = createServer((req, res) => {
|
|
136
|
-
const sessionIdHeader = req.headers["mcp-session-id"];
|
|
137
|
-
const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
|
|
138
|
-
const existing = sessionId ? sessions.get(sessionId) : undefined;
|
|
139
|
-
|
|
140
|
-
const transportPromise = existing ? Promise.resolve(existing) : createSession();
|
|
141
|
-
transportPromise
|
|
142
|
-
.then((transport) => transport.handleRequest(req, res))
|
|
143
|
-
.catch((error) => {
|
|
144
|
-
if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
|
|
145
|
-
res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
|
|
146
|
-
});
|
|
108
|
+
return serveMcpOverHttp({
|
|
109
|
+
createMcpServer: () => createManagementMcpServer(options),
|
|
110
|
+
commandLabel: "roomyx mcp",
|
|
111
|
+
defaultPort: 4320,
|
|
112
|
+
port: serveOptions.port,
|
|
113
|
+
host: serveOptions.host,
|
|
114
|
+
acknowledgeNonLoopback: serveOptions.acknowledgeNonLoopback,
|
|
147
115
|
});
|
|
148
|
-
|
|
149
|
-
const port = serveOptions.port ?? 4320;
|
|
150
|
-
try {
|
|
151
|
-
await new Promise<void>((resolve, reject) => {
|
|
152
|
-
httpServer.once("error", reject);
|
|
153
|
-
httpServer.listen(port, host, () => resolve());
|
|
154
|
-
});
|
|
155
|
-
} catch (error) {
|
|
156
|
-
await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
|
|
157
|
-
throw error;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
const address = httpServer.address();
|
|
161
|
-
const actualPort = typeof address === "object" && address !== null ? address.port : port;
|
|
162
|
-
|
|
163
|
-
return {
|
|
164
|
-
url: `http://${host}:${actualPort}/mcp`,
|
|
165
|
-
port: actualPort,
|
|
166
|
-
close: () =>
|
|
167
|
-
new Promise<void>((resolve, reject) => {
|
|
168
|
-
httpServer.close(async (error) => {
|
|
169
|
-
await Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
|
|
170
|
-
if (error) reject(error);
|
|
171
|
-
else resolve();
|
|
172
|
-
});
|
|
173
|
-
}),
|
|
174
|
-
};
|
|
175
116
|
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { createServer as createHttpServer } from "node:http";
|
|
2
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
3
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The loopback HTTP transport both roomyx servers bind to.
|
|
7
|
+
*
|
|
8
|
+
* It was written twice — once for the per-room server, once for the management
|
|
9
|
+
* server — and the copies had drifted: only one of them closed its sessions on
|
|
10
|
+
* shutdown. Two servers meant every transport-level fix had to be applied
|
|
11
|
+
* twice, and a signed tarball is a poor place to discover that the second one
|
|
12
|
+
* was missed. There is one now.
|
|
13
|
+
*
|
|
14
|
+
* A single `StreamableHTTPServerTransport` only ever completes ONE `initialize`
|
|
15
|
+
* handshake for its whole lifetime — an independent review reproduced this
|
|
16
|
+
* concretely: a second client, even a short-lived liveness check, gets "Server
|
|
17
|
+
* already initialized" and the transport is permanently unusable afterward. So
|
|
18
|
+
* each session (a request with no `mcp-session-id`) gets its own transport and
|
|
19
|
+
* its own `McpServer`, tracked by session id, and later requests carrying that
|
|
20
|
+
* header are routed to the pair that already exists.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export interface McpHttpTransportOptions {
|
|
24
|
+
/** Called once per session. Each session gets its own server instance. */
|
|
25
|
+
createMcpServer: () => McpServer;
|
|
26
|
+
/** Used in the refusal message when a non-loopback host is asked for without acknowledgement. */
|
|
27
|
+
commandLabel: string;
|
|
28
|
+
/** `roomyx serve` uses 4319, `roomyx mcp` 4320 — they must not collide. 0 selects an ephemeral port. */
|
|
29
|
+
defaultPort: number;
|
|
30
|
+
port?: number;
|
|
31
|
+
host?: string;
|
|
32
|
+
acknowledgeNonLoopback?: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface McpHttpTransportHandle {
|
|
36
|
+
url: string;
|
|
37
|
+
port: number;
|
|
38
|
+
close(): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Refuses non-loopback hosts unless explicitly acknowledged, mirroring `keryx
|
|
45
|
+
* serve`'s convention — same reasoning, recorded as D-06.
|
|
46
|
+
*/
|
|
47
|
+
export async function serveMcpOverHttp(
|
|
48
|
+
options: McpHttpTransportOptions,
|
|
49
|
+
): Promise<McpHttpTransportHandle> {
|
|
50
|
+
const host = options.host ?? "127.0.0.1";
|
|
51
|
+
if (!LOOPBACK_HOSTS.has(host) && !options.acknowledgeNonLoopback) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
`Refusing to bind ${options.commandLabel} to non-loopback host "${host}" without --acknowledge-non-loopback.`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const sessions = new Map<string, StreamableHTTPServerTransport>();
|
|
58
|
+
|
|
59
|
+
// Filled in after listen(). Sessions are only ever created while handling a
|
|
60
|
+
// request, so by the time createSession runs this is the real bound port —
|
|
61
|
+
// which matters because the allowlists below cannot be built without it.
|
|
62
|
+
let boundPort = 0;
|
|
63
|
+
|
|
64
|
+
async function createSession(): Promise<StreamableHTTPServerTransport> {
|
|
65
|
+
const transport = new StreamableHTTPServerTransport({
|
|
66
|
+
sessionIdGenerator: () => crypto.randomUUID(),
|
|
67
|
+
// Both guards, built lazily, from the port we actually bound.
|
|
68
|
+
//
|
|
69
|
+
// `allowedHosts` is an exact match against the whole `Host` header,
|
|
70
|
+
// port included: a port-less allowlist returns 403 to roomyx's own
|
|
71
|
+
// client. And with `--port 0` the port is not knowable until listen()
|
|
72
|
+
// resolves, so an allowlist written at option-construction time would be
|
|
73
|
+
// wrong by construction.
|
|
74
|
+
//
|
|
75
|
+
// Both lists are required because they stop different attacks. A page at
|
|
76
|
+
// http://127.0.0.1:<port>/mcp sends a legitimate Host, so only
|
|
77
|
+
// `allowedOrigins` refuses it. A DNS-rebound page sends
|
|
78
|
+
// `Host: attacker.example` and, post-rebind, a same-origin Origin — so
|
|
79
|
+
// only `allowedHosts` refuses that one.
|
|
80
|
+
//
|
|
81
|
+
// Nothing legitimate sends an Origin at all: roomyx's own client, the
|
|
82
|
+
// liveness probe and every MCP client are not browsers. The SDK skips
|
|
83
|
+
// the Origin check when the header is absent, so the list below exists
|
|
84
|
+
// to be matched by nothing.
|
|
85
|
+
enableDnsRebindingProtection: true,
|
|
86
|
+
allowedHosts: [`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`],
|
|
87
|
+
allowedOrigins: [`http://127.0.0.1:${boundPort}`, `http://localhost:${boundPort}`],
|
|
88
|
+
onsessioninitialized: (sessionId) => {
|
|
89
|
+
sessions.set(sessionId, transport);
|
|
90
|
+
},
|
|
91
|
+
onsessionclosed: (sessionId) => {
|
|
92
|
+
sessions.delete(sessionId);
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
const mcpServer = options.createMcpServer();
|
|
96
|
+
await mcpServer.connect(transport);
|
|
97
|
+
return transport;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const httpServer = createHttpServer((req, res) => {
|
|
101
|
+
const sessionIdHeader = req.headers["mcp-session-id"];
|
|
102
|
+
const sessionId = typeof sessionIdHeader === "string" ? sessionIdHeader : undefined;
|
|
103
|
+
const existing = sessionId ? sessions.get(sessionId) : undefined;
|
|
104
|
+
|
|
105
|
+
const transportPromise = existing ? Promise.resolve(existing) : createSession();
|
|
106
|
+
transportPromise
|
|
107
|
+
.then((transport) => transport.handleRequest(req, res))
|
|
108
|
+
.catch((error) => {
|
|
109
|
+
if (!res.headersSent) {
|
|
110
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
111
|
+
}
|
|
112
|
+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const port = options.port ?? options.defaultPort;
|
|
117
|
+
try {
|
|
118
|
+
await new Promise<void>((resolve, reject) => {
|
|
119
|
+
httpServer.once("error", reject);
|
|
120
|
+
httpServer.listen(port, host, () => resolve());
|
|
121
|
+
});
|
|
122
|
+
} catch (error) {
|
|
123
|
+
await closeSessions(sessions);
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const address = httpServer.address();
|
|
128
|
+
const actualPort = typeof address === "object" && address !== null ? address.port : port;
|
|
129
|
+
boundPort = actualPort;
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
url: `http://${host}:${actualPort}/mcp`,
|
|
133
|
+
port: actualPort,
|
|
134
|
+
close: () =>
|
|
135
|
+
new Promise<void>((resolve, reject) => {
|
|
136
|
+
httpServer.close(async (error) => {
|
|
137
|
+
// The management server used to skip this, so its sessions outlived
|
|
138
|
+
// the process that owned them. One implementation, one behaviour.
|
|
139
|
+
await closeSessions(sessions);
|
|
140
|
+
if (error) reject(error);
|
|
141
|
+
else resolve();
|
|
142
|
+
});
|
|
143
|
+
}),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function closeSessions(sessions: Map<string, StreamableHTTPServerTransport>): Promise<unknown[]> {
|
|
148
|
+
return Promise.all([...sessions.values()].map((t) => t.close().catch(() => undefined)));
|
|
149
|
+
}
|