import { Server } from '@modelcontextprotocol/sdk/server/index.js' import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js' import { ListToolsRequestSchema, CallToolRequestSchema, } from '@modelcontextprotocol/sdk/types.js' import { toolInputJsonSchema } from './tool-input-schema' import { buildMcpToolAnnotations } from './mcp-tool-annotations' import { advertisedOutputJsonSchema, buildToolSuccessResponse, filterRunnableAgentTools, resolveAgentToolAuditIds, resolveAgentToolPendingActionIds, type AgentToolAuditIds, } from './mcp-agent-tool-results' import { getToolRegistry } from './tool-registry' import { buildPendingApprovalMcpResponse, executeTool } from './tool-executor' import { loadAllModuleTools, indexToolsForSearch } from './tool-loader' import { authenticateMcpRequest } from './auth' import { assertValidMcpExposureConfig, buildDirectMutationModeWarning, describeMcpExposureConfig, filterToolsForCaller, isToolExposed, resolveMcpExposureConfig, } from './mcp-exposure' import { EMPTY_MCP_AUDIT_IDENTITY, attachCorrelationMeta, isMutationTool, mapToolResultToAuditOutcome, recordMcpToolCall, resolveAuditActorUserId, resolveCorrelationId, type McpAuditIdentity, type McpAuditOutcome, } from './mcp-audit' import type { McpServerOptions, McpToolContext } from './types' import type { SearchService } from '@open-mercato/search/service' const formatStderrError = (error: unknown): string => error instanceof Error ? error.stack ?? error.message : String(error) const writeStderrLine = (line: string): void => { process.stderr.write(`${line}\n`) } /** * Create and configure an MCP server instance. */ export async function createMcpServer(options: McpServerOptions): Promise { const { config, container, context, allowUnauthenticatedSuperadmin } = options const exposureConfig = options.exposureConfig ?? resolveMcpExposureConfig(process.env, options.cliArgs ?? {}) // Treat empty / whitespace-only secrets as missing so a blank api key cannot // fall through into an unauthenticated branch. const apiKeySecret = typeof options.apiKeySecret === 'string' && options.apiKeySecret.trim().length > 0 ? options.apiKeySecret : undefined let tenantId: string | null = null let organizationId: string | null = null let userId: string | null = null let userFeatures: string[] = [] let isSuperAdmin = false let auditIdentity: McpAuditIdentity = EMPTY_MCP_AUDIT_IDENTITY // API key authentication takes precedence if (apiKeySecret) { const authResult = await authenticateMcpRequest(apiKeySecret, container) if (!authResult.success) { throw new Error(`API key authentication failed: ${authResult.error}`) } tenantId = authResult.tenantId organizationId = authResult.organizationId userId = authResult.userId userFeatures = authResult.features isSuperAdmin = authResult.isSuperAdmin auditIdentity = { apiKeyId: authResult.keyId, apiKeySessionUserId: authResult.keySessionUserId ?? null, apiKeyCreatedBy: authResult.keyCreatedBy ?? null, sessionUserId: null, } writeStderrLine(`[MCP Server] Authenticated via API key: ${authResult.keyName}`) } else if (context && context.userId) { // Manual context with a real user — load that user's ACL. tenantId = context.tenantId organizationId = context.organizationId userId = context.userId auditIdentity = { ...EMPTY_MCP_AUDIT_IDENTITY, sessionUserId: context.userId } try { const rbacService = container.resolve('rbacService') as { loadAcl: ( userId: string, scope: { tenantId: string | null; organizationId: string | null } ) => Promise<{ isSuperAdmin: boolean features: string[] }> } const acl = await rbacService.loadAcl(userId, { tenantId, organizationId, }) userFeatures = acl.features isSuperAdmin = acl.isSuperAdmin } catch (error) { writeStderrLine(`[MCP Server] Failed to load user ACL: ${formatStderrError(error)}`) } } else if (allowUnauthenticatedSuperadmin) { // Explicit, loud dev/testing opt-in. Without a user there is no ACL to load, // so the server runs as superadmin with no tenant scoping beyond whatever the // caller pinned via `context`. NEVER enable this in production. if (context) { tenantId = context.tenantId organizationId = context.organizationId } isSuperAdmin = true writeStderrLine( '[MCP Server] WARNING: allowUnauthenticatedSuperadmin is enabled — running with UNAUTHENTICATED SUPERADMIN access and no per-user ACL. Do not use this outside local development/testing.' ) } else { // Fail closed: refuse to start rather than silently escalating to superadmin. throw new Error( '[internal] MCP server refused to start: no authentication provided. Supply a valid apiKeySecret, a context with a non-empty userId, or explicitly set allowUnauthenticatedSuperadmin: true for local development.' ) } const toolContext: McpToolContext = { tenantId, organizationId, userId, container, userFeatures, isSuperAdmin, apiKeySecret, } const server = new Server( { name: config.name, version: config.version }, { capabilities: { tools: {} } } ) // List tools handler server.setRequestHandler(ListToolsRequestSchema, async () => { const registry = getToolRegistry() const tools = Array.from(registry.getTools().values()) const accessibleTools = await filterRunnableAgentTools( filterToolsForCaller(tools, exposureConfig, { features: userFeatures, isSuperAdmin }), container ) if (config.debug) { writeStderrLine( `[MCP Server] Listing ${accessibleTools.length}/${tools.length} tools (filtered by exposure config and ACL)` ) } return { tools: accessibleTools.map((tool) => { const outputSchema = advertisedOutputJsonSchema(tool) return { name: tool.name, description: tool.description, inputSchema: toolInputJsonSchema(tool.inputSchema), ...(outputSchema ? { outputSchema } : {}), annotations: buildMcpToolAnnotations(tool), } }), } }) // Call tool handler server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params if (config.debug) { writeStderrLine(`[MCP Server] Calling tool: ${name} argKeys=${Object.keys(args ?? {}).join(',')}`) } const correlationId = resolveCorrelationId(null) const startedAt = Date.now() const toolArgs = args ?? {} const audit = ( outcome: McpAuditOutcome, errorCode: string | null, pendingActionIds: string[] | null = null, agentAuditIds: AgentToolAuditIds = resolveAgentToolAuditIds(getToolRegistry().getTool(name)) ) => recordMcpToolCall(container, { ...auditIdentity, ...agentAuditIds, toolName: name, tenantId, organizationId, channel: 'mcp', mcpServer: 'stdio', sessionKeyId: null, principal: 'api_key', outcome, errorCode, durationMs: Date.now() - startedAt, isMutation: isMutationTool(getToolRegistry().getTool(name)), pendingActionIds, correlationId, args: toolArgs, }) const registeredTool = getToolRegistry().getTool(name) if (!registeredTool || !isToolExposed(registeredTool, exposureConfig)) { await audit('denied', 'NOT_FOUND') return attachCorrelationMeta( { content: [ { type: 'text' as const, text: JSON.stringify({ error: `Tool "${name}" not found`, code: 'NOT_FOUND' }), }, ], isError: true, }, correlationId ) } let result: Awaited> try { result = await executeTool(name, toolArgs, toolContext, { channel: 'mcp', mutationMode: exposureConfig.mutationMode, requester: { userId: resolveAuditActorUserId(auditIdentity), apiKeyId: auditIdentity.apiKeyId, }, correlationId, }) } catch (error) { await audit('error', 'EXCEPTION') throw error } if (result.pendingApproval) { await audit(mapToolResultToAuditOutcome(result), null, [result.pendingApproval.pendingActionId]) return attachCorrelationMeta(buildPendingApprovalMcpResponse(result), correlationId) } const toolResultValue = result.success ? result.result : undefined await audit( mapToolResultToAuditOutcome(result), result.errorCode ?? null, resolveAgentToolPendingActionIds(registeredTool, toolResultValue), resolveAgentToolAuditIds(registeredTool, toolResultValue) ) if (!result.success) { return attachCorrelationMeta( { content: [ { type: 'text' as const, text: JSON.stringify({ error: result.error, code: result.errorCode }), }, ], isError: true, }, correlationId ) } return attachCorrelationMeta(buildToolSuccessResponse(registeredTool, result.result), correlationId) }) return server } /** * Run MCP server with stdio transport. * This keeps the process running until terminated. * * Supports two authentication modes: * 1. API key: Provide `apiKeySecret` option * 2. Manual context: Provide `context` with tenant/org/user */ export async function runMcpServer(options: McpServerOptions): Promise { if (!options.exposureConfig) assertValidMcpExposureConfig(process.env, options.cliArgs ?? {}) // Generate entity graph for Code Mode search tool try { const { extractEntityGraph, cacheEntityGraph } = await import('./entity-graph') const { getOrm } = await import('@open-mercato/shared/lib/db/mikro') const orm = await getOrm() const graph = await extractEntityGraph(orm) cacheEntityGraph(graph) writeStderrLine(`[MCP Server] Entity graph: ${graph.nodes.length} entities`) } catch (error) { writeStderrLine(`[MCP Server] Entity graph skipped: ${error instanceof Error ? error.message : String(error)}`) } // Pre-cache raw OpenAPI spec for Code Mode search tool try { const { getRawOpenApiSpec } = await import('./api-endpoint-index') await getRawOpenApiSpec() writeStderrLine('[MCP Server] Raw OpenAPI spec cached for Code Mode') } catch (error) { writeStderrLine(`[MCP Server] Raw OpenAPI spec caching skipped: ${error instanceof Error ? error.message : String(error)}`) } // Load tools from all modules before starting await loadAllModuleTools() // Index tools for hybrid search discovery (if search service available) try { const searchService = options.container.resolve('searchService') as SearchService await indexToolsForSearch(searchService) } catch (error) { // Search service might not be configured - discovery will use fallback writeStderrLine('[MCP Server] Search indexing skipped (search service not available)') } const exposureConfig = options.exposureConfig ?? resolveMcpExposureConfig(process.env, options.cliArgs ?? {}) const server = await createMcpServer({ ...options, exposureConfig }) const transport = new StdioServerTransport() const toolCount = getToolRegistry().listToolNames().length writeStderrLine(`[MCP Server] Starting ${options.config.name} v${options.config.version}`) if (options.apiKeySecret && options.apiKeySecret.trim().length > 0) { writeStderrLine(`[MCP Server] Authentication: API key`) } else if (options.context && options.context.userId) { writeStderrLine(`[MCP Server] Tenant: ${options.context.tenantId ?? '(none)'}`) writeStderrLine(`[MCP Server] Organization: ${options.context.organizationId ?? '(none)'}`) writeStderrLine(`[MCP Server] User: ${options.context.userId}`) } else { writeStderrLine(`[MCP Server] Authentication: none (unauthenticated superadmin opt-in)`) } writeStderrLine(`[MCP Server] Tools registered: ${toolCount}`) writeStderrLine( `[MCP Server] Exposure config: ${JSON.stringify( describeMcpExposureConfig(exposureConfig, Array.from(getToolRegistry().getTools().values())), )}` ) const directMutationWarning = buildDirectMutationModeWarning( exposureConfig, Array.from(getToolRegistry().getTools().values()), ) if (directMutationWarning) { writeStderrLine(`[MCP Server] WARN ${directMutationWarning}`) } await server.connect(transport) writeStderrLine('[MCP Server] Connected and ready for requests') // Handle shutdown gracefully const shutdown = async () => { writeStderrLine('[MCP Server] Shutting down...') await server.close() process.exit(0) } process.on('SIGINT', shutdown) process.on('SIGTERM', shutdown) }