import { createServer, type Server } from 'node:http' import type { AddressInfo } from 'node:net' import { z } from 'zod' import { createMcpHttpRequestHandler } from '../http-server' import { DEFAULT_MCP_EXPOSURE_CONFIG, type McpExposureConfig } from '../mcp-exposure' import { MCP_AUDIT_RESOURCE_KIND, type McpAuditAccessLogInput } from '../mcp-audit' import { buildAgentToolOutputSchema } from '../agent-tool' import type { McpToolExecutionObserver, McpToolExecutionObserverContext } from '../mcp-tool-execution-observer' import type { AiToolDefinition, McpServerConfig, McpToolDefinition, ToolExecutionResult } from '../types' const mockRegisteredTools = new Map() const mockFindApiKeyBySecret = jest.fn() const mockFindSessionApiKeyWithSecret = jest.fn() const mockExecuteTool = jest.fn, [string, unknown, unknown, unknown?]>() jest.mock('../tool-registry', () => ({ getToolRegistry: () => ({ getTools: () => new Map(mockRegisteredTools), listToolNames: () => Array.from(mockRegisteredTools.keys()), }), })) jest.mock('../tool-executor', () => ({ ...jest.requireActual('../tool-executor'), executeTool: (...args: [string, unknown, unknown, unknown?]) => mockExecuteTool(...args), })) jest.mock('../agent-registry', () => ({ loadAgentRegistry: jest.fn(async () => undefined), getAgent: (agentId: string) => (agentId === 'customers.summary_agent' ? { id: agentId } : undefined), })) jest.mock('../tool-loader', () => ({ loadAllModuleTools: jest.fn(), indexToolsForSearch: jest.fn(), })) jest.mock('@open-mercato/core/modules/api_keys/services/apiKeyService', () => ({ findApiKeyBySecret: (...args: unknown[]) => mockFindApiKeyBySecret(...args), findSessionApiKeyWithSecret: (...args: unknown[]) => mockFindSessionApiKeyWithSecret(...args), })) type AclFixture = { features: string[]; isSuperAdmin: boolean } const SERVER_KEY_ID = 'server-key' const SESSION_KEY_ID = 'session-key' const SERVER_SECRET = 'omk_server_secret' const SESSION_TOKEN = 'sess_valid' const SECRET_ARG_VALUE = 'very-secret-customer-name' const aclBySubject = new Map() const accessLogEntries: McpAuditAccessLogInput[] = [] let toolExecutionObserver: McpToolExecutionObserver | null = null function registerTool(overrides: Partial & { name: string }): void { mockRegisteredTools.set(overrides.name, { description: `${overrides.name} description`, inputSchema: z.object({ id: z.string().optional() }), handler: async () => ({}), ...overrides, } as McpToolDefinition) } function makeContainer() { const rbacService = { loadAcl: jest.fn(async (subject: string) => aclBySubject.get(subject) ?? { features: [], isSuperAdmin: false }), } const accessLogService = { log: jest.fn(async (input: McpAuditAccessLogInput) => { accessLogEntries.push(input) }), } return { resolve: (key: string) => { if (key === 'rbacService') return rbacService if (key === 'accessLogService') return accessLogService if (key === 'mcpToolExecutionObserver' && toolExecutionObserver) return toolExecutionObserver return {} }, } } const serverConfig: McpServerConfig = { name: 'test-mcp', version: '0.0.0' } let activeServer: Server | null = null async function startHandler(exposureOverrides: Partial = {}): Promise { const handler = createMcpHttpRequestHandler({ config: serverConfig, container: makeContainer() as unknown as Parameters[0]['container'], exposureConfig: { ...DEFAULT_MCP_EXPOSURE_CONFIG, ...exposureOverrides }, }) activeServer = createServer(handler) await new Promise((resolve) => activeServer?.listen(0, '127.0.0.1', resolve)) const address = activeServer.address() as AddressInfo return `http://127.0.0.1:${address.port}` } type CallToolBody = { result?: { content?: Array<{ type: string; text: string }> structuredContent?: Record isError?: boolean _meta?: { correlationId?: string } } } async function callTool( baseUrl: string, name: string, toolArgs: Record, extraHeaders: Record = {}, ): Promise { const response = await fetch(`${baseUrl}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'x-api-key': SERVER_SECRET, ...extraHeaders, }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: toolArgs } }), }) return (await response.json()) as CallToolBody } describe('MCP HTTP server — tools/call audit', () => { beforeEach(() => { mockRegisteredTools.clear() aclBySubject.clear() accessLogEntries.length = 0 mockFindApiKeyBySecret.mockReset() mockFindSessionApiKeyWithSecret.mockReset() mockExecuteTool.mockReset() toolExecutionObserver = null registerTool({ name: 'customers.list_people', requiredFeatures: ['customers.people.view'] }) registerTool({ name: 'customers.update_person', requiredFeatures: ['customers.people.manage'], isMutation: true }) mockFindApiKeyBySecret.mockImplementation(async (_em: unknown, secret: string) => secret === SERVER_SECRET ? { id: SERVER_KEY_ID, tenantId: 'tenant-1', organizationId: 'org-1', createdBy: 'user-1', sessionUserId: null, keyPrefix: 'omk_serv', } : null, ) mockFindSessionApiKeyWithSecret.mockImplementation(async (_em: unknown, token: string) => token === SESSION_TOKEN ? { key: { id: SESSION_KEY_ID, tenantId: 'tenant-1', organizationId: 'org-1', sessionUserId: 'user-2' }, secret: 'omk_session_secret', } : null, ) aclBySubject.set(`api_key:${SERVER_KEY_ID}`, { features: ['customers.*'], isSuperAdmin: false }) aclBySubject.set(`api_key:${SESSION_KEY_ID}`, { features: ['catalog.products.view'], isSuperAdmin: false }) }) afterEach(async () => { if (activeServer) { await new Promise((resolve) => activeServer?.close(() => resolve())) activeServer = null } }) it('writes one ok row with the header correlation id and echoes it in _meta', async () => { mockExecuteTool.mockResolvedValue({ success: true, result: { items: [] } }) const baseUrl = await startHandler() const body = await callTool( baseUrl, 'customers.list_people', { id: SECRET_ARG_VALUE }, { 'x-correlation-id': 'corr-http-1' }, ) expect(body.result?.isError).toBeUndefined() expect(body.result?.content?.[0]?.text).toBe(JSON.stringify({ items: [] }, null, 2)) expect(body.result?._meta).toEqual({ correlationId: 'corr-http-1' }) expect(accessLogEntries).toHaveLength(1) const [entry] = accessLogEntries expect(entry).toMatchObject({ tenantId: 'tenant-1', organizationId: 'org-1', actorUserId: 'user-1', resourceKind: MCP_AUDIT_RESOURCE_KIND, resourceId: 'customers.list_people', context: { channel: 'mcp', mcpServer: 'http', apiKeyId: SERVER_KEY_ID, sessionKeyId: null, principal: 'api_key', outcome: 'ok', errorCode: null, isMutation: false, correlationId: 'corr-http-1', argKeys: ['id'], }, }) expect(typeof entry.context.durationMs).toBe('number') expect(JSON.stringify(entry)).not.toContain(SECRET_ARG_VALUE) }) it('returns a pending_approval structured result and audits the pending action id', async () => { const pendingResult = { status: 'pending_approval', pendingActionId: 'pa-1', expiresAt: '2026-10-23T00:00:00.000Z', approvalPath: '/backend/config/ai-assistant/pending-actions/pa-1', summary: { toolName: 'customers.update_person', targetEntityType: null, targetRecordId: null, recordCount: 1 }, } mockExecuteTool.mockResolvedValue({ success: true, pendingApproval: { pendingActionId: 'pa-1', expiresAt: '2026-10-23T00:00:00.000Z' }, result: pendingResult, }) const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.update_person', { id: 'p-1' }, { 'x-correlation-id': 'corr-http-pa' }) expect(body.result?.isError).toBe(false) expect(body.result?.structuredContent).toEqual(pendingResult) expect(JSON.parse(body.result?.content?.[0]?.text ?? '{}')).toEqual(pendingResult) expect(body.result?._meta).toEqual({ correlationId: 'corr-http-pa' }) expect(mockExecuteTool.mock.calls[0][3]).toMatchObject({ requester: { userId: 'user-1', apiKeyId: SERVER_KEY_ID }, correlationId: 'corr-http-pa', }) expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'pending_approval', errorCode: null, pendingActionIds: ['pa-1'], correlationId: 'corr-http-pa', }) }) it('records the session principal and drops the session token from argKeys', async () => { mockExecuteTool.mockResolvedValue({ success: false, error: 'bad input', errorCode: 'VALIDATION_ERROR' }) registerTool({ name: 'catalog.list_products', requiredFeatures: ['catalog.products.view'] }) const baseUrl = await startHandler() const body = await callTool( baseUrl, 'catalog.list_products', { id: SECRET_ARG_VALUE, _sessionToken: SESSION_TOKEN }, { 'x-om-session-token': SESSION_TOKEN }, ) expect(body.result?.isError).toBe(true) expect(JSON.parse(body.result?.content?.[0]?.text ?? '{}')).toEqual({ error: 'bad input', code: 'VALIDATION_ERROR' }) const correlationId = body.result?._meta?.correlationId expect(correlationId).toEqual(expect.any(String)) expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0]).toMatchObject({ actorUserId: 'user-2', context: { principal: 'session', sessionKeyId: SESSION_KEY_ID, apiKeyId: SERVER_KEY_ID, outcome: 'invalid_input', errorCode: 'VALIDATION_ERROR', correlationId, argKeys: ['id'], }, }) expect(JSON.stringify(accessLogEntries[0])).not.toContain(SESSION_TOKEN) }) it('wraps tool execution in the registered observer with the session id', async () => { const observedContexts: McpToolExecutionObserverContext[] = [] toolExecutionObserver = { wrap: async (ctx, fn) => { observedContexts.push(ctx) return fn() }, } mockExecuteTool.mockResolvedValue({ success: true, result: { items: [] } }) registerTool({ name: 'catalog.list_products', requiredFeatures: ['catalog.products.view'] }) const baseUrl = await startHandler() const body = await callTool( baseUrl, 'catalog.list_products', { _sessionToken: SESSION_TOKEN }, { 'x-om-session-token': SESSION_TOKEN, 'x-correlation-id': 'corr-observer' }, ) expect(body.result?.isError).toBeUndefined() expect(mockExecuteTool).toHaveBeenCalledTimes(1) expect(observedContexts).toEqual([ { sessionId: SESSION_TOKEN, toolName: 'catalog.list_products', tenantId: 'tenant-1', organizationId: 'org-1', correlationId: 'corr-observer', }, ]) }) it('still executes the tool once when the observer throws', async () => { toolExecutionObserver = { wrap: async () => { throw new Error('observer unavailable') }, } mockExecuteTool.mockResolvedValue({ success: true, result: { items: [] } }) const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.list_people', {}) expect(body.result?.isError).toBeUndefined() expect(mockExecuteTool).toHaveBeenCalledTimes(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'ok' }) }) it('queues session-principal mutations for the session user without the server api key id', async () => { aclBySubject.set(`api_key:${SESSION_KEY_ID}`, { features: ['customers.*'], isSuperAdmin: false }) mockExecuteTool.mockResolvedValue({ success: true, pendingApproval: { pendingActionId: 'pa-session', expiresAt: '2026-10-23T00:00:00.000Z' }, result: { status: 'pending_approval', pendingActionId: 'pa-session' }, }) const baseUrl = await startHandler() await callTool(baseUrl, 'customers.update_person', { id: 'p-1', _sessionToken: SESSION_TOKEN }) expect(mockExecuteTool).toHaveBeenCalledTimes(1) expect(mockExecuteTool.mock.calls[0][3]).toMatchObject({ requester: { userId: 'user-2', apiKeyId: null }, }) expect(accessLogEntries[0].context).toMatchObject({ principal: 'session', sessionKeyId: SESSION_KEY_ID, apiKeyId: SERVER_KEY_ID, pendingActionIds: ['pa-session'], }) }) it('records denied for the per-call ACL rejection without executing the tool', async () => { const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.update_person', { id: 'p-1', _sessionToken: SESSION_TOKEN }) expect(body.result?.isError).toBe(true) expect(JSON.parse(body.result?.content?.[0]?.text ?? '{}').code).toBe('UNAUTHORIZED') expect(mockExecuteTool).not.toHaveBeenCalled() expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'denied', errorCode: 'UNAUTHORIZED', isMutation: true, principal: 'session', correlationId: body.result?._meta?.correlationId, }) }) it('records denied for an expired session token', async () => { const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.list_people', { _sessionToken: 'sess_expired' }) expect(JSON.parse(body.result?.content?.[0]?.text ?? '{}').code).toBe('SESSION_EXPIRED') expect(body.result?._meta?.correlationId).toEqual(expect.any(String)) expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'denied', errorCode: 'SESSION_EXPIRED', principal: 'api_key', }) }) describe('agent tools', () => { beforeEach(() => { registerTool({ name: 'customers.summary_agent.run', requiredFeatures: ['customers.people.view'], agentRef: { agentId: 'customers.summary_agent', engine: 'ai-assistant' }, mcp: { outputSchema: buildAgentToolOutputSchema(z.object({ summary: z.string() })) }, }) }) it('returns structuredContent with the run ids and records them in the audit row', async () => { const payload = { result: { summary: 'ok' }, agentId: 'customers.summary_agent', runId: 'run-1', agentRunId: null } mockExecuteTool.mockResolvedValue({ success: true, result: payload }) const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.summary_agent.run', { id: SECRET_ARG_VALUE }, { 'x-correlation-id': 'corr-agent' }) expect(body.result?.isError).toBeUndefined() expect(body.result?.structuredContent).toEqual(payload) expect(JSON.parse(body.result?.content?.[0]?.text ?? '{}')).toEqual(payload) expect(body.result?._meta).toEqual({ correlationId: 'corr-agent' }) expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'ok', agentId: 'customers.summary_agent', aiAgentRunId: 'run-1', agentRunId: null, correlationId: 'corr-agent', argKeys: ['id'], }) expect(JSON.stringify(accessLogEntries[0])).not.toContain(SECRET_ARG_VALUE) }) it('surfaces AGENT_DISPATCHER_UNAVAILABLE as an error result with the code', async () => { mockExecuteTool.mockResolvedValue({ success: false, error: 'Tool "customers.summary_agent.run" cannot run: its agent is not available', errorCode: 'AGENT_DISPATCHER_UNAVAILABLE', }) const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.summary_agent.run', {}) expect(body.result?.isError).toBe(true) expect(body.result?.structuredContent).toBeUndefined() expect(JSON.parse(body.result?.content?.[0]?.text ?? '{}').code).toBe('AGENT_DISPATCHER_UNAVAILABLE') expect(accessLogEntries[0].context).toMatchObject({ outcome: 'dispatcher_unavailable', errorCode: 'AGENT_DISPATCHER_UNAVAILABLE', agentId: 'customers.summary_agent', aiAgentRunId: null, agentRunId: null, }) }) it('leaves non-agent tool rows without agent ids', async () => { mockExecuteTool.mockResolvedValue({ success: true, result: { items: [] } }) const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.list_people', {}) expect(body.result?.structuredContent).toBeUndefined() expect(accessLogEntries[0].context).toMatchObject({ agentId: null, aiAgentRunId: null, agentRunId: null }) }) }) it('records error when the tool throws and replaces an invalid correlation header', async () => { mockExecuteTool.mockRejectedValue(new Error('boom')) const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.list_people', {}, { 'x-correlation-id': 'bad id with spaces' }) expect(JSON.parse(body.result?.content?.[0]?.text ?? '{}')).toEqual({ error: 'boom', code: 'EXCEPTION' }) const correlationId = body.result?._meta?.correlationId expect(correlationId).not.toBe('bad id with spaces') expect(correlationId).toMatch(/^[0-9a-f-]{36}$/) expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'error', errorCode: 'EXCEPTION', correlationId }) }) describe('calls the SDK refuses before the tool handler runs', () => { it('records denied NOT_FOUND for an unknown tool with the request correlation id', async () => { const baseUrl = await startHandler() const body = await callTool(baseUrl, 'does.not_exist', { id: SECRET_ARG_VALUE }, { 'x-correlation-id': 'corr-unknown' }) expect(body.result?.isError).toBe(true) expect(body.result?.content?.[0]?.text).toContain('Tool does.not_exist not found') expect(body.result?._meta).toEqual({ correlationId: 'corr-unknown' }) expect(mockExecuteTool).not.toHaveBeenCalled() expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0]).toMatchObject({ tenantId: 'tenant-1', organizationId: 'org-1', actorUserId: 'user-1', resourceKind: MCP_AUDIT_RESOURCE_KIND, resourceId: 'does.not_exist', context: { channel: 'mcp', mcpServer: 'http', apiKeyId: SERVER_KEY_ID, sessionKeyId: null, principal: 'api_key', outcome: 'denied', errorCode: 'NOT_FOUND', isMutation: false, correlationId: 'corr-unknown', argKeys: ['id'], }, }) expect(JSON.stringify(accessLogEntries[0])).not.toContain(SECRET_ARG_VALUE) }) it('records denied NOT_FOUND for a tool hidden by the caller ACL, with the same response as an unknown tool', async () => { registerTool({ name: 'catalog.update_product', requiredFeatures: ['catalog.products.manage'], isMutation: true }) const baseUrl = await startHandler() const hidden = await callTool(baseUrl, 'catalog.update_product', { id: 'p-1' }) const unknown = await callTool(baseUrl, 'catalog.no_such_tool', { id: 'p-1' }) expect(hidden.result?.content?.[0]?.text).toBe( unknown.result?.content?.[0]?.text?.replace('catalog.no_such_tool', 'catalog.update_product'), ) expect(mockExecuteTool).not.toHaveBeenCalled() expect(accessLogEntries).toHaveLength(2) expect(accessLogEntries[0]).toMatchObject({ resourceId: 'catalog.update_product', context: { outcome: 'denied', errorCode: 'NOT_FOUND', isMutation: true, principal: 'api_key' }, }) }) it('records denied NOT_FOUND for a mutation tool hidden by the deny mutation mode', async () => { const baseUrl = await startHandler({ mutationMode: 'deny' }) const body = await callTool(baseUrl, 'customers.update_person', { id: 'p-1' }) expect(body.result?.isError).toBe(true) expect(mockExecuteTool).not.toHaveBeenCalled() expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'denied', errorCode: 'NOT_FOUND', isMutation: true }) }) it('records invalid_input for arguments rejected by the input schema', async () => { registerTool({ name: 'customers.get_person', requiredFeatures: ['customers.people.view'], inputSchema: z.object({ id: z.string() }), }) const baseUrl = await startHandler() const body = await callTool(baseUrl, 'customers.get_person', { id: 42 }, { 'x-correlation-id': 'corr-invalid' }) expect(body.result?.isError).toBe(true) expect(body.result?.content?.[0]?.text).toContain('Input validation error') expect(body.result?._meta).toEqual({ correlationId: 'corr-invalid' }) expect(mockExecuteTool).not.toHaveBeenCalled() expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0]).toMatchObject({ resourceId: 'customers.get_person', context: { outcome: 'invalid_input', errorCode: 'VALIDATION_ERROR', principal: 'api_key', argKeys: ['id'] }, }) }) it('never resolves or records an unverified _sessionToken argument on a refused call', async () => { const baseUrl = await startHandler() await callTool(baseUrl, 'does.not_exist', { _sessionToken: SESSION_TOKEN }) expect(mockFindSessionApiKeyWithSecret).not.toHaveBeenCalled() expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0]).toMatchObject({ actorUserId: 'user-1', context: { principal: 'api_key', sessionKeyId: null, argKeys: [] }, }) expect(JSON.stringify(accessLogEntries[0])).not.toContain(SESSION_TOKEN) }) it('attributes a refused call to the verified session header principal and its scope', async () => { mockFindSessionApiKeyWithSecret.mockImplementation(async (_em: unknown, token: string) => token === SESSION_TOKEN ? { key: { id: SESSION_KEY_ID, tenantId: 'tenant-1', organizationId: 'org-2', sessionUserId: 'user-2' }, secret: 'omk_session_secret', } : null, ) const baseUrl = await startHandler() await callTool(baseUrl, 'customers.list_people', {}, { 'x-om-session-token': SESSION_TOKEN }) expect(mockExecuteTool).not.toHaveBeenCalled() expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0]).toMatchObject({ tenantId: 'tenant-1', organizationId: 'org-2', actorUserId: 'user-2', resourceId: 'customers.list_people', context: { principal: 'session', sessionKeyId: SESSION_KEY_ID, apiKeyId: SERVER_KEY_ID, outcome: 'denied', errorCode: 'NOT_FOUND' }, }) }) it('bounds a caller-supplied tool name in the audit row', async () => { const baseUrl = await startHandler() await callTool(baseUrl, `x${'a'.repeat(5000)}`, {}) expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].resourceId).toHaveLength(128) }) it('writes exactly one row for a call the tool handler handled', async () => { mockExecuteTool.mockResolvedValue({ success: false, error: 'bad input', errorCode: 'VALIDATION_ERROR' }) const baseUrl = await startHandler() await callTool(baseUrl, 'customers.list_people', { id: 'p-1' }) expect(accessLogEntries).toHaveLength(1) expect(accessLogEntries[0].context).toMatchObject({ outcome: 'invalid_input', errorCode: 'VALIDATION_ERROR' }) }) }) })