Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix: mcp 1

Carl-Gerhard Lindesvärd28cda437b956
diff --git a/packages/mcp/src/auth.ts b/packages/mcp/src/auth.ts
index e16273c38..f3f551f99 100644
--- a/packages/mcp/src/auth.ts
+++ b/packages/mcp/src/auth.ts
@@ -2,6 +2,9 @@ import { createHash } from 'node:crypto';
import { verifyPassword } from '@openpanel/common/server';
import { ClientType, getClientByIdCached } from '@openpanel/db';
import { getCache } from '@openpanel/redis';
+import { createLogger } from '@openpanel/logger';
+
+const logger = createLogger({ name: 'mcp:auth' });
export interface McpAuthContext {
/**
@@ -46,6 +49,7 @@ export async function authenticateToken(
const colonIndex = decoded.indexOf(':');
if (colonIndex === -1) {
+ logger.warn('MCP auth: token has no colon separator', { decodedLength: decoded.length });
throw new McpAuthError(
'Invalid token format — expected base64(clientId:clientSecret)',
);
@@ -54,11 +58,14 @@ export async function authenticateToken(
const clientId = decoded.slice(0, colonIndex);
const clientSecret = decoded.slice(colonIndex + 1);
+ logger.info('MCP auth: decoded token', { clientId, secretPrefix: clientSecret.slice(0, 6) });
+
if (
!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(
clientId,
)
) {
+ logger.warn('MCP auth: invalid client ID format', { clientId });
throw new McpAuthError('Invalid client ID format');
}
@@ -68,9 +75,12 @@ export async function authenticateToken(
const client = await getClientByIdCached(clientId);
if (!client) {
+ logger.warn('MCP auth: client not found', { clientId });
throw new McpAuthError('Invalid credentials');
}
+ logger.info('MCP auth: client found', { clientId, type: client.type, hasSecret: !!client.secret });
+
if (!client.secret) {
throw new McpAuthError(
'This client has no secret — only clients with a secret can use MCP',
@@ -78,6 +88,7 @@ export async function authenticateToken(
}
if (client.type === ClientType.write) {
+ logger.warn('MCP auth: write-only client rejected', { clientId });
throw new McpAuthError(
'Write-only clients cannot use MCP — use a read or root client',
);
@@ -92,6 +103,8 @@ export async function authenticateToken(
true,
);
+ logger.info('MCP auth: password verification result', { clientId, isVerified });
+
if (!isVerified) {
throw new McpAuthError('Invalid credentials');
}
diff --git a/packages/mcp/src/handler.ts b/packages/mcp/src/handler.ts
index a0ab50cdd..f3e245869 100644
--- a/packages/mcp/src/handler.ts
+++ b/packages/mcp/src/handler.ts
@@ -1,4 +1,5 @@
-import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { createLogger } from '@openpanel/logger';
import { McpAuthError, authenticateToken, extractToken } from './auth';
@@ -7,15 +8,18 @@ import type { SessionManager } from './session-manager';
const logger = createLogger({ name: 'mcp:handler' });
+const MCP_PROTOCOL_VERSION = '2024-11-05';
+
/**
* Handle a POST /mcp request.
*
- * - If Mcp-Session-Id is present and the session is local: route to existing transport.
- * - If Mcp-Session-Id is present but not local: check Redis — if context found,
- * recreate server+transport on this instance (cross-instance migration).
- * - Otherwise authenticate via token and create a new session.
+ * Fully stateless: each request creates a fresh McpServer driven by InMemoryTransport.
+ * Auth context is the only thing persisted — stored in Redis by session ID.
+ * Works across any number of API instances with no sticky-session requirement.
*
- * Writes directly to `res` (caller must have hijacked the Fastify reply).
+ * - No session ID: authenticate + must be an `initialize` request → create session in Redis.
+ * - Session ID found in Redis: look up context, process request on a fresh server.
+ * - Session ID not in Redis: 404 → client reinitializes.
*/
export async function handleMcpPost(
sessionManager: SessionManager,
@@ -25,36 +29,75 @@ export async function handleMcpPost(
query: Record<string, unknown>,
): Promise<void> {
const sessionId = req.headers['mcp-session-id'] as string | undefined;
- logger.info('MCP POST request', { sessionId: sessionId ?? 'new', hasAuth: !!(query['token'] || req.headers.authorization) });
+ const message = body as JSONRPCMessage;
- if (sessionId) {
- // Fast path: session is already on this instance
- const local = sessionManager.getLocal(sessionId);
- if (local) {
- await sessionManager.touchContext(sessionId);
- await local.transport.handleRequest(req, res, body);
- return;
- }
+ logger.info('MCP POST request', {
+ sessionId: sessionId ?? 'new',
+ method: 'method' in message ? message.method : 'unknown',
+ hasAuth: !!(query['token'] || req.headers.authorization),
+ });
- // Slow path: session exists on another instance — retrieve context from Redis
+ if (sessionId) {
const context = await sessionManager.getContext(sessionId);
if (!context) {
+ logger.warn('MCP session not found in Redis', { sessionId });
res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Session not found or expired' }));
+ res.end(JSON.stringify({ error: 'Session not found — please reconnect' }));
return;
}
- logger.info('MCP session migrated to this instance', { sessionId });
- await attachSession(sessionManager, sessionId, context, req, res, body);
+ await sessionManager.touchContext(sessionId);
+
+ // Notifications have no `id` and expect no response
+ if (!('id' in message)) {
+ res.writeHead(202);
+ res.end();
+ return;
+ }
+
+ try {
+ const response = await processRequest(context, message);
+ res.writeHead(200, {
+ 'Content-Type': 'application/json',
+ 'Mcp-Session-Id': sessionId,
+ });
+ res.end(JSON.stringify(response));
+ } catch (err) {
+ logger.error('MCP request processing error', { err, sessionId });
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Internal server error' }));
+ }
return;
}
- // New session — authenticate first
+ // New connection — authenticate and expect `initialize`
const token = extractToken(query, req.headers.authorization);
try {
const context = await authenticateToken(token);
- await attachSession(sessionManager, null, context, req, res, body);
+
+ if (!('method' in message) || message.method !== 'initialize') {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'First request must be initialize' }));
+ return;
+ }
+
+ const response = await processRequest(context, message, true);
+ const newSessionId = sessionManager.generateId();
+ await sessionManager.setContext(newSessionId, context);
+
+ logger.info('MCP session created', {
+ sessionId: newSessionId,
+ clientType: context.clientType,
+ organizationId: context.organizationId,
+ projectId: context.projectId,
+ });
+
+ res.writeHead(200, {
+ 'Content-Type': 'application/json',
+ 'Mcp-Session-Id': newSessionId,
+ });
+ res.end(JSON.stringify(response));
} catch (err) {
if (err instanceof McpAuthError) {
logger.warn('MCP auth failed', { reason: err.message });
@@ -69,75 +112,60 @@ export async function handleMcpPost(
}
/**
- * Create (or recreate) a server+transport for the given context, handle the
- * request, and register the session locally + in Redis.
+ * Create a fresh McpServer for each request and process a single JSON-RPC message.
*
- * @param fixedSessionId When migrating an existing session, pass its ID so we
- * reuse the same session ID rather than generating a new one.
+ * For non-initialize requests we fast-forward the server through the MCP
+ * initialization handshake (using an internal fake initialize) before dispatching
+ * the real message. This keeps the handler stateless while satisfying the SDK's
+ * internal state machine.
*/
-async function attachSession(
- sessionManager: SessionManager,
- fixedSessionId: string | null,
+async function processRequest(
context: Parameters<typeof createMcpServer>[0],
- req: IncomingMessage,
- res: ServerResponse,
- body: unknown,
-): Promise<void> {
+ message: JSONRPCMessage,
+ isInitialize = false,
+): Promise<JSONRPCMessage> {
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const server = createMcpServer(context);
+ await server.connect(serverTransport);
- const transport = new StreamableHTTPServerTransport({
- sessionIdGenerator: fixedSessionId
- ? () => fixedSessionId
- : () => sessionManager.generateId(),
- onsessioninitialized: async (id: string) => {
- sessionManager.setLocal(id, { server, transport });
- await sessionManager.setContext(id, context);
- logger.info('MCP session initialized', {
- sessionId: id,
- clientType: context.clientType,
- organizationId: context.organizationId,
- projectId: context.projectId,
- });
- },
- });
+ if (!isInitialize) {
+ // Fast-forward: send a fake initialize so the server enters its ready state
+ await new Promise<void>((resolve, reject) => {
+ clientTransport.onmessage = () => resolve();
+ clientTransport
+ .send({
+ jsonrpc: '2.0',
+ id: '__mcp_init__',
+ method: 'initialize',
+ params: {
+ protocolVersion: MCP_PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: 'mcp-proxy', version: '0' },
+ },
+ })
+ .catch(reject);
+ });
+ // Notify the server that initialization is complete (no response expected)
+ await clientTransport.send({
+ jsonrpc: '2.0',
+ method: 'notifications/initialized',
+ });
+ }
- await server.connect(transport);
- await transport.handleRequest(req, res, body);
+ return new Promise<JSONRPCMessage>((resolve, reject) => {
+ clientTransport.onmessage = resolve;
+ clientTransport.send(message).catch(reject);
+ });
}
/**
- * Handle a GET /mcp request (SSE stream for an existing session).
- *
- * SSE streams are tied to the instance they started on. If the session is not
- * local (i.e., it was started on a different instance), return 404 so the
- * client reconnects and establishes a fresh session on this instance.
+ * SSE is not supported in stateless mode — all communication happens over POST.
*/
export async function handleMcpGet(
- sessionManager: SessionManager,
- req: IncomingMessage,
+ _sessionManager: SessionManager,
+ _req: IncomingMessage,
res: ServerResponse,
): Promise<void> {
- const sessionId = req.headers['mcp-session-id'] as string | undefined;
- if (!sessionId) {
- res.writeHead(400, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ error: 'Mcp-Session-Id header is required' }));
- return;
- }
-
- const session = sessionManager.getLocal(sessionId);
- if (!session) {
- res.writeHead(404, { 'Content-Type': 'application/json' });
- res.end(
- JSON.stringify({
- error: 'Session not found on this instance — reconnect to start a new session',
- }),
- );
- return;
- }
-
- try {
- await session.transport.handleRequest(req, res);
- } catch (err) {
- logger.error('MCP SSE stream error', { err, sessionId });
- }
+ res.writeHead(405, { 'Content-Type': 'application/json', Allow: 'POST, DELETE' });
+ res.end(JSON.stringify({ error: 'SSE not supported — use POST for all requests' }));
}
diff --git a/packages/mcp/src/session-manager.test.ts b/packages/mcp/src/session-manager.test.ts
index b5ab162a7..dc72ce20b 100644
--- a/packages/mcp/src/session-manager.test.ts
+++ b/packages/mcp/src/session-manager.test.ts
@@ -31,12 +31,6 @@ const CTX: McpAuthContext = {
clientType: 'read',
};
-const mockTransport = {
- close: vi.fn().mockResolvedValue(undefined),
-};
-
-const mockServer = {} as any;
-
beforeEach(() => {
vi.clearAllMocks();
});
@@ -87,75 +81,18 @@ describe('SessionManager', () => {
});
});
- describe('local transport', () => {
- it('stores and retrieves local session', () => {
- const sm = new SessionManager();
- sm.setLocal('sess-1', { server: mockServer, transport: mockTransport as any });
- expect(sm.getLocal('sess-1')).toBeDefined();
- });
-
- it('returns undefined for unknown session', () => {
- const sm = new SessionManager();
- expect(sm.getLocal('unknown')).toBeUndefined();
- });
-
- it('deletes local session', () => {
- const sm = new SessionManager();
- sm.setLocal('sess-1', { server: mockServer, transport: mockTransport as any });
- sm.deleteLocal('sess-1');
- expect(sm.getLocal('sess-1')).toBeUndefined();
- });
-
- it('tracks localSize correctly', () => {
- const sm = new SessionManager();
- expect(sm.localSize).toBe(0);
- sm.setLocal('a', { server: mockServer, transport: mockTransport as any });
- sm.setLocal('b', { server: mockServer, transport: mockTransport as any });
- expect(sm.localSize).toBe(2);
- sm.deleteLocal('a');
- expect(sm.localSize).toBe(1);
- });
- });
-
describe('close', () => {
- it('closes transport, removes local session, and deletes Redis context', async () => {
+ it('deletes session from Redis', async () => {
const sm = new SessionManager();
- sm.setLocal('sess-1', { server: mockServer, transport: mockTransport as any });
await sm.close('sess-1');
-
- expect(mockTransport.close).toHaveBeenCalled();
- expect(sm.getLocal('sess-1')).toBeUndefined();
expect(mockDel).toHaveBeenCalledWith('mcp:session:sess-1');
});
-
- it('still removes Redis context even when no local session exists', async () => {
- const sm = new SessionManager();
- await sm.close('no-local-sess');
- expect(mockDel).toHaveBeenCalledWith('mcp:session:no-local-sess');
- expect(mockTransport.close).not.toHaveBeenCalled();
- });
-
- it('does not throw if transport.close fails', async () => {
- const sm = new SessionManager();
- const failingTransport = { close: vi.fn().mockRejectedValue(new Error('already closed')) };
- sm.setLocal('sess-1', { server: mockServer, transport: failingTransport as any });
- await expect(sm.close('sess-1')).resolves.toBeUndefined();
- });
});
describe('destroy', () => {
- it('closes all local sessions', async () => {
+ it('is a no-op (sessions are in Redis, not in-process)', async () => {
const sm = new SessionManager();
- const t1 = { close: vi.fn().mockResolvedValue(undefined) };
- const t2 = { close: vi.fn().mockResolvedValue(undefined) };
- sm.setLocal('a', { server: mockServer, transport: t1 as any });
- sm.setLocal('b', { server: mockServer, transport: t2 as any });
-
- await sm.destroy();
-
- expect(t1.close).toHaveBeenCalled();
- expect(t2.close).toHaveBeenCalled();
- expect(sm.localSize).toBe(0);
+ await expect(sm.destroy()).resolves.toBeUndefined();
});
});
});
diff --git a/packages/mcp/src/session-manager.ts b/packages/mcp/src/session-manager.ts
index 535a7c635..b22c03d73 100644
--- a/packages/mcp/src/session-manager.ts
+++ b/packages/mcp/src/session-manager.ts
@@ -1,6 +1,4 @@
import { randomUUID } from 'node:crypto';
-import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
-import type { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { createLogger } from '@openpanel/logger';
import { getRedisCache } from '@openpanel/redis';
import type { McpAuthContext } from './auth';
@@ -13,30 +11,17 @@ function redisKey(id: string) {
return `mcp:session:${id}`;
}
-interface McpLocalSession {
- server: McpServer;
- transport: StreamableHTTPServerTransport;
-}
-
/**
- * Hybrid session manager:
- * - Auth context is stored in Redis (shared across all API instances, TTL 30 min)
- * - Active transport/server are kept in a local Map (in-process only — they hold live HTTP connections)
+ * Stateless session manager — auth context lives only in Redis.
*
- * This means POST requests can be handled by any instance: if the transport
- * isn't local, we retrieve the context from Redis and recreate it here.
- * SSE (GET) streams are inherently tied to the instance they started on;
- * when that instance goes down the client reconnects and gets a fresh session.
+ * No in-process state: any API instance can handle any request for any session.
+ * No sticky sessions required.
*/
export class SessionManager {
- private readonly local = new Map<string, McpLocalSession>();
-
generateId(): string {
return randomUUID();
}
- // --- context (Redis) ---
-
async setContext(id: string, context: McpAuthContext): Promise<void> {
await getRedisCache().setJson(redisKey(id), SESSION_TTL_SECONDS, context);
logger.info('MCP session context stored', {
@@ -57,46 +42,14 @@ export class SessionManager {
async deleteContext(id: string): Promise<void> {
await getRedisCache().del(redisKey(id));
+ logger.info('MCP session deleted', { sessionId: id });
}
- // --- transport/server (local) ---
-
- setLocal(id: string, session: McpLocalSession): void {
- this.local.set(id, session);
- }
-
- getLocal(id: string): McpLocalSession | undefined {
- return this.local.get(id);
- }
-
- deleteLocal(id: string): void {
- this.local.delete(id);
- }
-
- // --- combined ops ---
-
async close(id: string): Promise<void> {
- const session = this.local.get(id);
- this.local.delete(id);
await this.deleteContext(id);
-
- if (session) {
- try {
- await session.transport.close();
- } catch (err) {
- logger.warn('Error closing MCP transport', { sessionId: id, err });
- }
- }
-
- logger.info('MCP session closed', { sessionId: id });
}
async destroy(): Promise<void> {
- const ids = [...this.local.keys()];
- await Promise.all(ids.map((id) => this.close(id)));
- }
-
- get localSize(): number {
- return this.local.size;
+ // No-op: sessions are in Redis, not in-process
}
}