8000 fix(transport): add Streamable HTTP MCP transport, fix stateless-per-request bug by Mnehmos · Pull Request #77 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,155 +184,156 @@
return server;
}

async function main() {
setupShutdownHandlers();

// =========================================================================
// AGENT RUNTIME: wire LLM providers + repos behind getAgentRuntime()
// =========================================================================
try {
// Deliberately no setAgentRuntime() here any more. Runtime deps bind eight
// repositories to a single database, and under per-campaign databases the
// right one is not known until a request arrives with a verified tenant.
// agent_manage and combat_manage already build the runtime lazily from the
// request's own database, which is now the only correct place to do it.
// Provider initialization stays at boot: it is genuinely process-wide, and
// surfacing misconfiguration early is worth keeping.
const providerFactory = new ProviderFactory();
const providers = providerFactory.initialize();

// Diagnostic: print enough to self-diagnose the "Provider not configured"
// error class without ever printing key values. The MCP-host-spawned-with-
// wrong-cwd trap is universal; surfacing the resolved .env path makes it
// obvious in 5 seconds.
console.error('[Agent] Runtime initialized:');
console.error(`[Agent] .env loaded from: ${envLoadedFrom ?? '(none found — relying on ambient env)'}`);
console.error(`[Agent] process cwd: ${process.cwd()}`);
if (providers.length > 0) {
console.error(`[Agent] providers ready: ${providers.join(', ')}`);
} else {
console.error('[Agent] providers ready: (none — set OPENAI_API_KEY and/or OPENROUTER_API_KEY)');
// Show which key names exist in the process env (presence only, never values)
const visibleKeys = ['OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'OPENAI_ORGANIZATION', 'OPENROUTER_REFERER']
.filter(k => process.env[k] !== undefined);
console.error(`[Agent] env keys visible: ${visibleKeys.length > 0 ? visibleKeys.join(', ') : '(none of the expected keys)'}`);
}
} catch (err) {
console.error(`[Server] Failed to initialize agent runtime: ${(err as Error).message}`);
}

// App-level singletons shared across every McpServer instance buildServer() creates.
const pubsub = new PubSub();
setWorldPubSub(pubsub);
setCombatPubSub(pubsub);
registerEventInboxBridge(pubsub);
const auditLogger = new AuditLogger();

// =========================================================================
// TRANSPORT SETUP
// =========================================================================

const args = process.argv.slice(2);
const transportType = args.includes('--tcp') ? 'tcp'
: (args.includes('--unix') || args.includes('--socket')) ? 'unix'
: (args.includes('--ws') || args.includes('--websocket')) ? 'websocket'
: (args.includes('--http') || process.env.PORT) ? 'http'
: 'stdio';

const getArgValue = (name: string): string | undefined => {
const index = args.indexOf(name);
return index !== -1 ? args[index + 1] : undefined;
};
// Only the HTTP transport is multi-tenant; it establishes a verified tenant
// per request. Every other transport serves one local operator, so it opens a
// single database up front. Without this, getDb() would find no tenant and
// every storage tool would fail for local users of the npm package, the
// standalone binaries, and MCP client configs.
//
// The legacy-database assertion is likewise HTTP-only: for a hosted server a
// pre-split file means an incomplete cutover, but in single-user mode that
// same file is simply the operator's database.
if (transportType === 'http') {
assertNoLegacyDatabase();
console.error(`[Server] Campaign databases: ${campaignDbPath('<campaign-id>')}`);
} else {
useSingleUserDatabase(getArgValue('--db-path'));
}

const networkHost = getArgValue('--host') || '127.0.0.1';
const transportToken = getArgValue('--transport-token') || process.env.RPG_MCP_TRANSPORT_TOKEN;
const maxMessageBytes = parseInt(getArgValue('--max-message-bytes') || '1048576', 10);

if ((transportType === 'tcp' || transportType === 'websocket') &&
networkHost !== '127.0.0.1' &&
networkHost !== 'localhost' &&
!transportToken) {
console.error('[Server] WARNING: network transport is not bound to loopback and no transport token is configured.');
}

if (transportType === 'tcp') {
const { TCPServerTransport } = await import('./transport/tcp.js');
const port = getArgValue('--port') ? parseInt(getArgValue('--port')!, 10) : 3000;

const server = buildServer(pubsub, auditLogger);
const transport = new TCPServerTransport(port, {
host: networkHost,
authToken: transportToken,
maxMessageBytes
});
await server.connect(transport);
console.error(`RPG MCP Server running on TCP ${networkHost}:${port}`);
} else if (transportType === 'unix') {
const { UnixServerTransport } = await import('./transport/unix.js');
let socketPath = '';
const unixIndex = args.indexOf('--unix');
const socketIndex = args.indexOf('--socket');

if (unixIndex !== -1 && args[unixIndex + 1]) {
socketPath = args[unixIndex + 1];
} else if (socketIndex !== -1 && args[socketIndex + 1]) {
socketPath = args[socketIndex + 1];
}

if (!socketPath) {
socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\rpg-mcp' : '/tmp/rpg-mcp.sock';
}

const server = buildServer(pubsub, auditLogger);
const transport = new UnixServerTransport(socketPath, { maxMessageBytes });
await server.connect(transport);
console.error(`RPG MCP Server running on Unix socket ${socketPath}`);
} else if (transportType === 'websocket') {
const { WebSocketServerTransport } = await import('./transport/websocket.js');
const port = getArgValue('--port') ? parseInt(getArgValue('--port')!, 10) : 3001;

const server = buildServer(pubsub, auditLogger);
const transport = new WebSocketServerTransport(port, {
host: networkHost,
authToken: transportToken,
maxMessageBytes
});
await server.connect(transport);
console.error(`RPG MCP Server running on WebSocket ${networkHost}:${port}`);
} else if (transportType === 'http') {
const { startHttpServerTransport } = await import('./transport/http.js');
const port = getArgValue('--port') ? parseInt(getArgValue('--port')!, 10) : parseInt(process.env.PORT || '3000', 10);

// '::' binds dual-stack (IPv6 + IPv4). Required for Railway private
// networking, which is IPv6-only — see transport/http.ts.
const httpHost = getArgValue('--host') || '::';
await startHttpServerTransport(() => buildServer(pubsub, auditLogger), port, {
host: httpHost,
authToken: transportToken,
maxBodyBytes: maxMessageBytes,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
console.error(`RPG MCP Server running on HTTP ${httpHost}:${port} (POST /mcp, GET /health)`);
} else {
const server = buildServer(pubsub, auditLogger);
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('RPG MCP Server running on stdio');
}
}

Check warning on line 336 in src/server/index.ts

View check run for this annotation

Repowise Bot / Repowise / code health

Introduced: brain method

Brain Method: main is 105 lines, CCN 36, in a file imported by 4 others

main().catch((error) => {
console.error('Server error:', error);
Expand Down
28 changes: 26 additions & 2 deletions src/server/transport/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,32 @@ export class WebSocketServerTransport implements Transport {
}

async start(): Promise<void> {
// Server starts in constructor
return Promise.resolve();
// WebSocketServer begins listening in its constructor, but the
// listening event is asynchronous. Await it so callers (and the MCP
// server's connect path) cannot race the first client connection.
if (this.wss.address() !== null) return;

await new Promise<void>((resolve, reject) => {
const => {
cleanup();
resolve();
};
const Error) => {
cleanup();
reject(error);
};
const cleanup = () => {
this.wss.off('listening', onListening);
this.wss.off('error', onError);
};

this.wss.once('listening', onListening);
this.wss.once('error', onError);

// The server may have finished between the initial check and
// listener registration.
if (this.wss.address() !== null) onListening();
});
}

async close(): Promise<void> {
< 467A /a> Expand Down
Loading
0