Fix/mcp fixes and bugs (#518)
* feat(voucher): add create voucher and correct entry previews; update commit methods * feat: add support for pending operations in API key scopes and OAuth client management - Introduced new API key scopes for reading and approving pending operations. - Updated the scope groups to include pending operations. - Added new tools for listing and managing pending operations. - Implemented OAuth client registration and revocation endpoints. - Created a UI panel for managing OAuth clients, including registration and revocation. - Added tests for pending operations tools and OAuth allowlist functionality. - Implemented a database migration for OAuth client registrations with appropriate policies and constraints. * feat: Implement OAuth client registration rate limiting and enhance security measures - Added IP-based rate limiting to the OAuth client registration endpoint to prevent enumeration attacks. - Introduced a service-role client for allowlist lookups, ensuring trust boundaries are maintained. - Updated error responses to be uniform across different types of redirect URI validation failures. - Enhanced tests to reflect changes in OAuth scope handling, ensuring fallback to read-only scopes when no scopes are provided. - Improved handling of high-risk pending operations, requiring explicit confirmation for approvals. - Added audit logging for OAuth client revocations and pending operation approvals/rejections to maintain a security audit trail. - Refactored API key scope management to include default read-only scopes for OAuth-issued keys and added segregation-of-duties checks.
This commit is contained in:
@@ -3,7 +3,7 @@ import { NextResponse } from 'next/server'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { z } from 'zod'
|
||||
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
import { extractInvoiceFields } from './lib/extract-invoice-fields'
|
||||
import { extractInvoiceFields, ExtractionSchema, emptyResult } from './lib/extract-invoice-fields'
|
||||
import {
|
||||
verifyInboundWebhook,
|
||||
fetchReceivingEmail,
|
||||
@@ -107,7 +107,8 @@ async function uploadAndExtract(
|
||||
companyId: string,
|
||||
file: { name: string; buffer: ArrayBuffer; type: string },
|
||||
source: 'upload' | 'email',
|
||||
emailMeta?: EmailMeta
|
||||
emailMeta?: EmailMeta,
|
||||
opts: { skipExtraction?: boolean } = {}
|
||||
) {
|
||||
const correlationId = crypto.randomUUID()
|
||||
|
||||
@@ -139,11 +140,18 @@ async function uploadAndExtract(
|
||||
console.error('[invoice-inbox] Failed to append DocumentIngested:', err)
|
||||
}
|
||||
|
||||
const { data: extracted, rawText } = await extractInvoiceFields({
|
||||
buffer: Buffer.from(file.buffer),
|
||||
mimeType: file.type,
|
||||
fileName: file.name,
|
||||
})
|
||||
// Bring-your-own-extraction: skip the Bedrock call entirely and seed an
|
||||
// empty extraction skeleton. The caller is expected to PUT the parsed
|
||||
// fields via /items/:id/extracted-data before converting to a supplier
|
||||
// invoice. extracted_data is never null in the DB; an empty skeleton
|
||||
// keeps downstream readers (UI, MCP) happy.
|
||||
const { data: extracted, rawText } = opts.skipExtraction
|
||||
? { data: emptyResult(), rawText: null }
|
||||
: await extractInvoiceFields({
|
||||
buffer: Buffer.from(file.buffer),
|
||||
mimeType: file.type,
|
||||
fileName: file.name,
|
||||
})
|
||||
|
||||
// Supplier match by org-nr, then case-insensitive name (no AI fuzz).
|
||||
let matchedSupplierId: string | null = null
|
||||
@@ -275,6 +283,12 @@ export const invoiceInboxExtension: Extension = {
|
||||
|
||||
const formData = await request.formData()
|
||||
const file = formData.get('file') as File | null
|
||||
// Opt-out of the built-in Claude/Bedrock OCR. Agents with their own
|
||||
// extraction pipeline upload the document, get the inbox row, then
|
||||
// PUT /items/:id/extracted-data with their parsed fields.
|
||||
const skipExtraction =
|
||||
formData.get('skip_extraction') === 'true' ||
|
||||
formData.get('skip_extraction') === '1'
|
||||
|
||||
if (!file) return NextResponse.json({ error: 'No file provided' }, { status: 400 })
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
@@ -294,7 +308,9 @@ export const invoiceInboxExtension: Extension = {
|
||||
ctx.userId,
|
||||
ctx.companyId,
|
||||
{ name: file.name, buffer, type: file.type },
|
||||
'upload'
|
||||
'upload',
|
||||
undefined,
|
||||
{ skipExtraction }
|
||||
)
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (error) {
|
||||
@@ -466,6 +482,141 @@ export const invoiceInboxExtension: Extension = {
|
||||
},
|
||||
},
|
||||
|
||||
// ── Replace extracted_data wholesale (BYO extraction) ────
|
||||
// Used by agents that ran their own OCR/extraction pipeline. Validates
|
||||
// the full InvoiceExtractionResult shape via the same Zod schema that
|
||||
// gates Bedrock output, so downstream consumers (UI, supplier-invoice
|
||||
// creation) cannot tell apart agent-supplied from AI-extracted data.
|
||||
{
|
||||
method: 'PUT',
|
||||
path: '/items/:id/extracted-data',
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const url = new URL(request.url)
|
||||
const id = url.searchParams.get('_id')
|
||||
if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 })
|
||||
|
||||
// Rate-limit BYO extraction the same way fresh uploads are limited —
|
||||
// both paths inject extracted_data into invoice_inbox_items, so an
|
||||
// unbounded BYO loop is the same abuse surface as an upload flood
|
||||
// (ISO 27001 A.8.12, data-injection guard).
|
||||
const rl = await checkInboxUploadRateLimit(ctx.supabase, ctx.companyId)
|
||||
if (!rl.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: `För många förfrågningar — försök igen om en stund.` },
|
||||
{
|
||||
status: 429,
|
||||
headers: rl.retryAfterSec ? { 'Retry-After': String(rl.retryAfterSec) } : undefined,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
let extracted: InvoiceExtractionResult
|
||||
try {
|
||||
const json = await request.json()
|
||||
// ExtractionSchema doesn't include `confidence` (the AI path tacks
|
||||
// it on after parsing). BYO data gets 0.95 so downstream UI can
|
||||
// distinguish it from a perfect AI parse — financial-data
|
||||
// provenance per ISO 27001 A.8.12.
|
||||
const parsed = ExtractionSchema.parse(json)
|
||||
extracted = { ...parsed, confidence: 0.95 }
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Invalid extracted_data shape' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const { data: item } = await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, company_id, created_supplier_invoice_id')
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!item) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
// Explicit tenant boundary assertion alongside the .eq filter
|
||||
// (V4.5.1 defense-in-depth). Surfaces any future change that
|
||||
// accidentally bypasses the where-clause.
|
||||
if (item.company_id !== ctx.companyId) {
|
||||
return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
}
|
||||
if (item.created_supplier_invoice_id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Posten är redan kopplad till en leverantörsfaktura och kan inte ändras.' },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
// Re-run supplier match so the agent's parsed fields trigger the
|
||||
// same auto-link the AI path uses. Skipped if neither key is present.
|
||||
let matchedSupplierId: string | null = null
|
||||
if (extracted.supplier.orgNumber) {
|
||||
const { data: s } = await ctx.supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('company_id', ctx.companyId)
|
||||
.eq('org_number', extracted.supplier.orgNumber)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (s) matchedSupplierId = s.id
|
||||
}
|
||||
if (!matchedSupplierId && extracted.supplier.name) {
|
||||
const { data: s } = await ctx.supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('company_id', ctx.companyId)
|
||||
.ilike('name', extracted.supplier.name)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (s) matchedSupplierId = s.id
|
||||
}
|
||||
|
||||
const { data: updated, error: updateError } = await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({
|
||||
extracted_data: extracted as unknown as Record<string, unknown>,
|
||||
matched_supplier_id: matchedSupplierId,
|
||||
})
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.select('id, extracted_data, matched_supplier_id')
|
||||
.single()
|
||||
|
||||
if (updateError) {
|
||||
return NextResponse.json({ error: updateError.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// Audit the BYO override so financial-data provenance is traceable
|
||||
// (GDPR Art. 5(1)(f), SOC 2 CC9.2). Failure logged but never blocks
|
||||
// the response — the override has already happened.
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId: ctx.companyId,
|
||||
correlationId: id,
|
||||
aggregateType: 'Document',
|
||||
aggregateId: id,
|
||||
eventType: 'DocumentExtractionOverridden',
|
||||
payload: {
|
||||
inbox_item_id: id,
|
||||
channel: 'rest_api',
|
||||
has_supplier_org_number: extracted.supplier.orgNumber != null,
|
||||
has_invoice_number: extracted.invoice.invoiceNumber != null,
|
||||
extracted_total: extracted.totals.total,
|
||||
matched_supplier_id: matchedSupplierId,
|
||||
},
|
||||
actor: { type: 'user', id: ctx.userId },
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (auditErr) {
|
||||
console.error('[invoice-inbox] Failed to append DocumentExtractionOverridden:', auditErr)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: updated })
|
||||
},
|
||||
},
|
||||
|
||||
// ── Attach a source document to an existing inbox item ──
|
||||
{
|
||||
method: 'POST',
|
||||
|
||||
@@ -54,7 +54,7 @@ export interface ExtractionOutput {
|
||||
rawText: string | null
|
||||
}
|
||||
|
||||
const ExtractionSchema = z.object({
|
||||
export const ExtractionSchema = z.object({
|
||||
supplier: z.object({
|
||||
name: z.string().nullable(),
|
||||
orgNumber: z.string().nullable(),
|
||||
@@ -159,7 +159,7 @@ Rules:
|
||||
- lineItems: include every line. Empty array is fine if the document has no itemised lines.
|
||||
- vatBreakdown: include one entry per distinct VAT rate. Empty array is fine.`
|
||||
|
||||
function emptyResult(): InvoiceExtractionResult {
|
||||
export function emptyResult(): InvoiceExtractionResult {
|
||||
return {
|
||||
supplier: {
|
||||
name: null,
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
|
||||
const commitSpy = vi.fn()
|
||||
|
||||
vi.mock('@/lib/pending-operations/commit', () => ({
|
||||
commitPendingOperation: (...args: unknown[]) => commitSpy(...args),
|
||||
}))
|
||||
|
||||
// Import after mock so the tool registry binds to the mocked module
|
||||
import { tools } from '../server'
|
||||
|
||||
const listTool = tools.find((t) => t.name === 'gnubok_list_pending_operations')!
|
||||
const approveTool = tools.find((t) => t.name === 'gnubok_approve_pending_operation')!
|
||||
const rejectTool = tools.find((t) => t.name === 'gnubok_reject_pending_operation')!
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('pending_operations MCP tools — registration', () => {
|
||||
it('all three tools are registered', () => {
|
||||
expect(listTool).toBeDefined()
|
||||
expect(approveTool).toBeDefined()
|
||||
expect(rejectTool).toBeDefined()
|
||||
})
|
||||
|
||||
it('list is gated by pending_operations:read', () => {
|
||||
expect(TOOL_SCOPE_MAP['gnubok_list_pending_operations']).toBe('pending_operations:read')
|
||||
})
|
||||
|
||||
it('approve and reject are gated by pending_operations:approve', () => {
|
||||
expect(TOOL_SCOPE_MAP['gnubok_approve_pending_operation']).toBe('pending_operations:approve')
|
||||
expect(TOOL_SCOPE_MAP['gnubok_reject_pending_operation']).toBe('pending_operations:approve')
|
||||
})
|
||||
|
||||
it('input schemas have additionalProperties: false', () => {
|
||||
for (const t of [listTool, approveTool, rejectTool]) {
|
||||
expect((t.inputSchema as Record<string, unknown>).additionalProperties).toBe(false)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('gnubok_list_pending_operations', () => {
|
||||
it('returns operations with pagination envelope', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const ops = [
|
||||
{ id: 'op-1', operation_type: 'create_invoice', status: 'pending', risk_level: 'medium', created_at: '2026-05-01T00:00:00Z' },
|
||||
{ id: 'op-2', operation_type: 'create_voucher', status: 'pending', risk_level: 'high', created_at: '2026-05-02T00:00:00Z' },
|
||||
]
|
||||
enqueue({ data: ops, error: null, count: 2 })
|
||||
|
||||
const result = (await listTool.execute(
|
||||
{},
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
{ type: 'api_key' }
|
||||
)) as {
|
||||
operations: Array<{ id: string }>
|
||||
count: number
|
||||
total_count: number
|
||||
has_more: boolean
|
||||
}
|
||||
|
||||
expect(result.operations).toHaveLength(2)
|
||||
expect(result.count).toBe(2)
|
||||
expect(result.total_count).toBe(2)
|
||||
expect(result.has_more).toBe(false)
|
||||
})
|
||||
|
||||
it('signals has_more + next_offset when more rows exist beyond the page', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ id: 'op-1' }], error: null, count: 50 })
|
||||
|
||||
const result = (await listTool.execute(
|
||||
{ limit: 1, offset: 0 },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
{ type: 'api_key' }
|
||||
)) as { has_more: boolean; next_offset?: number }
|
||||
|
||||
expect(result.has_more).toBe(true)
|
||||
expect(result.next_offset).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('gnubok_approve_pending_operation', () => {
|
||||
it('fetches the op then delegates to commitPendingOperation', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const op = { id: 'op-1', operation_type: 'create_invoice', company_id: 'company-1', status: 'pending', risk_level: 'medium', params: {} }
|
||||
enqueue({ data: op, error: null }) // fetch
|
||||
commitSpy.mockResolvedValue({ status: 'committed', data: { invoice_id: 'inv-1' } })
|
||||
|
||||
const result = (await approveTool.execute(
|
||||
{ operation_id: 'op-1' },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
{ type: 'api_key' }
|
||||
)) as { status: string; operation_id: string; data?: { invoice_id: string } }
|
||||
|
||||
expect(commitSpy).toHaveBeenCalledTimes(1)
|
||||
expect(commitSpy.mock.calls[0][3]).toMatchObject({ id: 'op-1' })
|
||||
// commit options always include commitMethod; userEmail is added when
|
||||
// the supabase mock supports auth.admin.getUserById (it doesn't here, so
|
||||
// the resolution silently fails and we fall back to just commitMethod).
|
||||
expect(commitSpy.mock.calls[0][4]).toMatchObject({ commitMethod: 'user_accept' })
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.operation_id).toBe('op-1')
|
||||
expect(result.data?.invoice_id).toBe('inv-1')
|
||||
})
|
||||
|
||||
it('refuses to approve a risk_level=high op without confirmed=true', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const op = {
|
||||
id: 'op-1',
|
||||
operation_type: 'create_voucher',
|
||||
company_id: 'company-1',
|
||||
status: 'pending',
|
||||
risk_level: 'high',
|
||||
params: {},
|
||||
}
|
||||
enqueue({ data: op, error: null }) // fetch
|
||||
|
||||
await expect(
|
||||
approveTool.execute(
|
||||
{ operation_id: 'op-1' },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
{ type: 'api_key' }
|
||||
)
|
||||
).rejects.toThrow(/confirmed=true/i)
|
||||
expect(commitSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('approves a risk_level=high op when confirmed=true is supplied', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
const op = {
|
||||
id: 'op-1',
|
||||
operation_type: 'create_voucher',
|
||||
company_id: 'company-1',
|
||||
status: 'pending',
|
||||
risk_level: 'high',
|
||||
params: {},
|
||||
}
|
||||
enqueue({ data: op, error: null }) // fetch
|
||||
commitSpy.mockResolvedValue({ status: 'committed' })
|
||||
|
||||
const result = (await approveTool.execute(
|
||||
{ operation_id: 'op-1', confirmed: true },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
{ type: 'api_key' }
|
||||
)) as { status: string; operation_id: string }
|
||||
|
||||
expect(commitSpy).toHaveBeenCalledTimes(1)
|
||||
expect(result.status).toBe('committed')
|
||||
})
|
||||
|
||||
it('throws when the operation is not found', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: { message: 'not found' } })
|
||||
|
||||
await expect(
|
||||
approveTool.execute({ operation_id: 'missing' }, 'company-1', 'user-1', supabase as never)
|
||||
).rejects.toThrow(/not found/i)
|
||||
expect(commitSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('surfaces failed status from the executor', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1', operation_type: 'create_voucher', company_id: 'company-1', status: 'pending', params: {} }, error: null })
|
||||
commitSpy.mockResolvedValue({ status: 'failed', error: 'Period locked', http_status: 423 })
|
||||
|
||||
const result = (await approveTool.execute(
|
||||
{ operation_id: 'op-1' },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never
|
||||
)) as { status: string; error?: string }
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.error).toBe('Period locked')
|
||||
})
|
||||
})
|
||||
|
||||
describe('gnubok_reject_pending_operation', () => {
|
||||
it('flips status to rejected and never invokes the executor', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1', status: 'pending' }, error: null }) // fetch
|
||||
enqueue({ data: [{ id: 'op-1' }], error: null }) // update CAS — returns rows
|
||||
|
||||
const result = (await rejectTool.execute(
|
||||
{ operation_id: 'op-1' },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never
|
||||
)) as { status: string; operation_id: string }
|
||||
|
||||
expect(result.status).toBe('rejected')
|
||||
expect(result.operation_id).toBe('op-1')
|
||||
expect(commitSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('throws when the CAS update affects 0 rows (concurrent claim)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1', status: 'pending' }, error: null }) // fetch
|
||||
enqueue({ data: [], error: null }) // update CAS — 0 rows (lost race)
|
||||
|
||||
await expect(
|
||||
rejectTool.execute({ operation_id: 'op-1' }, 'company-1', 'user-1', supabase as never)
|
||||
).rejects.toThrow(/no longer pending/i)
|
||||
})
|
||||
|
||||
it('throws 409-style error if the op is already resolved', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1', status: 'committed' }, error: null })
|
||||
|
||||
await expect(
|
||||
rejectTool.execute({ operation_id: 'op-1' }, 'company-1', 'user-1', supabase as never)
|
||||
).rejects.toThrow(/already committed/i)
|
||||
})
|
||||
|
||||
it('throws when the op is missing', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: { message: 'not found' } })
|
||||
|
||||
await expect(
|
||||
rejectTool.execute({ operation_id: 'missing' }, 'company-1', 'user-1', supabase as never)
|
||||
).rejects.toThrow(/not found/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { tools } from '../server'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_set_inbox_extracted_data')!
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
function validPayload() {
|
||||
return {
|
||||
supplier: {
|
||||
name: 'Anthropic Inc.',
|
||||
orgNumber: null,
|
||||
vatNumber: null,
|
||||
address: null,
|
||||
bankgiro: null,
|
||||
plusgiro: null,
|
||||
},
|
||||
invoice: {
|
||||
invoiceNumber: 'A-2026-0001',
|
||||
invoiceDate: '2026-05-12',
|
||||
dueDate: '2026-06-11',
|
||||
paymentReference: null,
|
||||
currency: 'USD',
|
||||
},
|
||||
lineItems: [
|
||||
{
|
||||
description: 'Claude API usage',
|
||||
quantity: 1,
|
||||
unitPrice: 50,
|
||||
lineTotal: 50,
|
||||
vatRate: 0,
|
||||
accountSuggestion: null,
|
||||
},
|
||||
],
|
||||
totals: { subtotal: 50, vatAmount: 0, total: 50 },
|
||||
vatBreakdown: [{ rate: 0, base: 50, amount: 0 }],
|
||||
}
|
||||
}
|
||||
|
||||
describe('gnubok_set_inbox_extracted_data — registration', () => {
|
||||
it('is registered with the right scope', () => {
|
||||
expect(tool).toBeDefined()
|
||||
expect(TOOL_SCOPE_MAP['gnubok_set_inbox_extracted_data']).toBe('suppliers:write')
|
||||
})
|
||||
|
||||
it('has additionalProperties: false on the top-level inputSchema', () => {
|
||||
expect((tool.inputSchema as Record<string, unknown>).additionalProperties).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('gnubok_set_inbox_extracted_data — happy path', () => {
|
||||
it('validates the payload, fetches the item, matches supplier, and updates', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
// fetch inbox item — must include company_id so the defense-in-depth
|
||||
// tenant check passes.
|
||||
enqueue({
|
||||
data: { id: 'inbox-1', company_id: 'company-1', created_supplier_invoice_id: null },
|
||||
error: null,
|
||||
})
|
||||
// supplier match by orgNumber — payload has none, skipped
|
||||
// supplier match by name (ILIKE) — found
|
||||
enqueue({ data: { id: 'sup-1' }, error: null })
|
||||
// update inbox_items
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ inbox_item_id: 'inbox-1', extracted_data: validPayload() },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never,
|
||||
{ type: 'api_key' }
|
||||
)) as { inbox_item_id: string; matched_supplier_id: string | null; extracted_data: { confidence: number } }
|
||||
|
||||
expect(result.inbox_item_id).toBe('inbox-1')
|
||||
expect(result.matched_supplier_id).toBe('sup-1')
|
||||
// BYO data is marked confidence 0.95 (vs 1.0 for AI-perfect parse) so
|
||||
// downstream provenance is distinguishable.
|
||||
expect(result.extracted_data.confidence).toBe(0.95)
|
||||
})
|
||||
})
|
||||
|
||||
describe('gnubok_set_inbox_extracted_data — validation & guards', () => {
|
||||
it('rejects malformed extracted_data with a Zod error', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
await expect(
|
||||
tool.execute(
|
||||
{ inbox_item_id: 'inbox-1', extracted_data: { supplier: 'not-an-object' } },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never
|
||||
)
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('throws when the inbox item does not exist', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: null })
|
||||
await expect(
|
||||
tool.execute(
|
||||
{ inbox_item_id: 'missing', extracted_data: validPayload() },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never
|
||||
)
|
||||
).rejects.toThrow(/not found/i)
|
||||
})
|
||||
|
||||
it('refuses to overwrite when the item already created a supplier invoice', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: { id: 'inbox-1', company_id: 'company-1', created_supplier_invoice_id: 'sinv-1' },
|
||||
error: null,
|
||||
})
|
||||
await expect(
|
||||
tool.execute(
|
||||
{ inbox_item_id: 'inbox-1', extracted_data: validPayload() },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never
|
||||
)
|
||||
).rejects.toThrow(/already linked/i)
|
||||
})
|
||||
|
||||
it('rejects when the fetched row belongs to a different company (defense-in-depth)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
// The .eq('company_id', companyId) on the SELECT should already prevent
|
||||
// this in practice, but the explicit assert catches any future query
|
||||
// change that bypasses the where-clause (V4.5.1).
|
||||
enqueue({
|
||||
data: { id: 'inbox-1', company_id: 'company-other', created_supplier_invoice_id: null },
|
||||
error: null,
|
||||
})
|
||||
await expect(
|
||||
tool.execute(
|
||||
{ inbox_item_id: 'inbox-1', extracted_data: validPayload() },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never
|
||||
)
|
||||
).rejects.toThrow(/different company/i)
|
||||
})
|
||||
|
||||
it('requires inbox_item_id', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
await expect(
|
||||
tool.execute(
|
||||
{ inbox_item_id: '', extracted_data: validPayload() },
|
||||
'company-1',
|
||||
'user-1',
|
||||
supabase as never
|
||||
)
|
||||
).rejects.toThrow(/inbox_item_id/i)
|
||||
})
|
||||
})
|
||||
@@ -60,10 +60,12 @@ import {
|
||||
generateInvoiceEmailSubject,
|
||||
} from '@/lib/email/invoice-templates'
|
||||
import { uploadDocument, MAX_DOCUMENT_SIZE } from '@/lib/core/documents/document-service'
|
||||
import { extractInvoiceFields } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
|
||||
import { extractInvoiceFields, ExtractionSchema as InvoiceExtractionSchema } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
|
||||
import { commitPendingOperation } from '@/lib/pending-operations/commit'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
// ensureInitialized() is called by the extension router (ext/[...path]/route.ts)
|
||||
// which dispatches to this handler — no duplicate call needed here.
|
||||
import type { Transaction, TransactionCategory, EntityType, VatTreatment, Invoice, Currency, CompanySettings, Customer, InvoiceItem } from '@/types'
|
||||
import type { Transaction, TransactionCategory, EntityType, VatTreatment, Invoice, Currency, CompanySettings, Customer, InvoiceItem, PendingOperation } from '@/types'
|
||||
|
||||
// ── Actor context ────────────────────────────────────────────
|
||||
|
||||
@@ -6194,6 +6196,401 @@ export const tools: McpTool[] = [
|
||||
})
|
||||
},
|
||||
},
|
||||
|
||||
// ── Pending operations: list / approve / reject ──────────────
|
||||
// Mirrors the /pending web UI for agents that self-review before committing.
|
||||
{
|
||||
name: 'gnubok_list_pending_operations',
|
||||
description: 'List staged pending_operations. Filter by status (default pending), risk_level, or operation_type. Use to review the queue before calling gnubok_approve_pending_operation or gnubok_reject_pending_operation.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
status: { type: 'string', enum: ['pending', 'committing', 'committed', 'rejected'], description: 'Default: pending' },
|
||||
risk_level: { type: 'string', enum: ['low', 'medium', 'high'] },
|
||||
operation_type: { type: 'string', description: 'Filter to a single operation_type (e.g. "create_invoice")' },
|
||||
limit: { type: 'number', minimum: 1, maximum: 200, description: 'Default 50' },
|
||||
offset: { type: 'number', minimum: 0, description: 'Default 0' },
|
||||
},
|
||||
required: [],
|
||||
},
|
||||
outputSchema: paginatedSchema('operations'),
|
||||
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
async execute(args, companyId, _userId, supabase) {
|
||||
const status = (args.status as string) ?? 'pending'
|
||||
const limit = Math.min(200, Math.max(1, (args.limit as number) ?? 50))
|
||||
const offset = Math.max(0, (args.offset as number) ?? 0)
|
||||
|
||||
// `params` holds the raw operation inputs (invoice line items, supplier
|
||||
// PII, voucher descriptions) — excluded from the list response to
|
||||
// satisfy data-minimisation (GDPR Art. 5(1)(b)). Use preview_data for
|
||||
// a redacted, human-readable summary, or call the underlying entity
|
||||
// endpoint when the agent needs the full payload.
|
||||
let query = supabase
|
||||
.from('pending_operations')
|
||||
.select(
|
||||
'id, operation_type, title, preview_data, status, risk_level, actor_type, actor_id, actor_label, created_at, resolved_at, result_data',
|
||||
{ count: 'exact' }
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', status)
|
||||
.order('created_at', { ascending: false })
|
||||
.range(offset, offset + limit - 1)
|
||||
|
||||
if (args.risk_level) query = query.eq('risk_level', args.risk_level as string)
|
||||
if (args.operation_type) query = query.eq('operation_type', args.operation_type as string)
|
||||
|
||||
const { data, error, count } = await query
|
||||
if (error) throw new Error(`Failed to list pending operations: ${error.message}`)
|
||||
|
||||
const operations = data ?? []
|
||||
const totalCount = count ?? operations.length
|
||||
const hasMore = offset + operations.length < totalCount
|
||||
return {
|
||||
operations,
|
||||
count: operations.length,
|
||||
total_count: totalCount,
|
||||
has_more: hasMore,
|
||||
...(hasMore ? { next_offset: offset + operations.length } : {}),
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_approve_pending_operation',
|
||||
description: 'Approve a staged pending_operation. Runs the same commit path as web-UI approval — atomic claim → executor → status update. High-risk operations require confirmed=true. Returns status=committed on success, or status=rejected/failed with error details.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
operation_id: { type: 'string', description: 'UUID of the pending_operations row to approve' },
|
||||
confirmed: {
|
||||
type: 'boolean',
|
||||
description: 'Required when the operation has risk_level=high (create_voucher, correct_entry, reverse_entry, year-end, period lock/close). Acknowledges the BFL/BFNAR irreversibility implications. The web UI surfaces the same gate via an explicit warning dialog.',
|
||||
},
|
||||
},
|
||||
required: ['operation_id'],
|
||||
},
|
||||
outputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
status: { type: 'string', enum: ['committed', 'rejected', 'failed'] },
|
||||
operation_id: { type: 'string' },
|
||||
data: { type: 'object' },
|
||||
error: { type: 'string' },
|
||||
auto_rejected: { type: 'boolean' },
|
||||
},
|
||||
required: ['status', 'operation_id'],
|
||||
},
|
||||
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
||||
async execute(args, companyId, userId, supabase, actor) {
|
||||
const operationId = args.operation_id as string
|
||||
if (!operationId) throw new Error('operation_id is required')
|
||||
|
||||
const { data: op, error: fetchError } = await supabase
|
||||
.from('pending_operations')
|
||||
.select('*')
|
||||
.eq('id', operationId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (fetchError || !op) throw new Error('Pending operation not found')
|
||||
|
||||
// High-risk operations require explicit confirmation in addition to the
|
||||
// standard pending_operations:approve scope. Mirrors the web-UI gate
|
||||
// (BFL 5 kap 5§ — irreversible postings require positive acknowledgment).
|
||||
const operation = op as PendingOperation
|
||||
if (operation.risk_level === 'high' && args.confirmed !== true) {
|
||||
throw new Error(
|
||||
`Operation "${operation.operation_type}" is risk_level=high — pass confirmed=true to approve. The web UI requires the same positive acknowledgment per BFL 5 kap 5§ (irreversible postings).`
|
||||
)
|
||||
}
|
||||
|
||||
// Resolve the user's email so commitPendingOperation can attribute the
|
||||
// journal_entries.committed_by_email and any user-facing email side
|
||||
// effects (send_invoice cc) to the actor — matches the web-UI commit
|
||||
// path attribution (V8.2.1, GDPR Art. 25(1)).
|
||||
let userEmail: string | undefined
|
||||
try {
|
||||
const { data: userData } = await supabase.auth.admin.getUserById(userId)
|
||||
userEmail = userData.user?.email ?? undefined
|
||||
} catch (err) {
|
||||
log.warn('Failed to resolve user email for MCP approval', { userId, err })
|
||||
}
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase,
|
||||
userId,
|
||||
companyId,
|
||||
operation,
|
||||
{ commitMethod: 'user_accept', ...(userEmail ? { userEmail } : {}) }
|
||||
)
|
||||
|
||||
// Audit the MCP-initiated approval. Failure must not break the user
|
||||
// flow — the side-effects have already happened.
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId,
|
||||
correlationId: operationId,
|
||||
aggregateType: 'System',
|
||||
aggregateId: operationId,
|
||||
eventType: 'PendingOperationApproved',
|
||||
payload: {
|
||||
operation_id: operationId,
|
||||
operation_type: operation.operation_type,
|
||||
risk_level: operation.risk_level,
|
||||
outcome: result.status,
|
||||
commit_method: 'user_accept',
|
||||
channel: 'mcp',
|
||||
confirmed: args.confirmed === true,
|
||||
},
|
||||
actor: {
|
||||
type: actor?.type === 'api_key' ? 'api_key' : 'user',
|
||||
id: actor?.id ?? userId,
|
||||
...(actor?.label ? { label: actor.label } : {}),
|
||||
},
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (auditErr) {
|
||||
log.warn('Failed to append PendingOperationApproved audit event', auditErr)
|
||||
}
|
||||
|
||||
return {
|
||||
status: result.status,
|
||||
operation_id: operationId,
|
||||
...(result.data ? { data: result.data } : {}),
|
||||
...(result.error ? { error: result.error } : {}),
|
||||
...(result.auto_rejected ? { auto_rejected: true } : {}),
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_reject_pending_operation',
|
||||
description: 'Reject a staged pending_operation without executing it. Status flips to rejected; no journal entries, invoices, or other side-effects created. Idempotent on already-resolved ops (returns 409).',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
operation_id: { type: 'string', description: 'UUID of the pending_operations row to reject' },
|
||||
reason: {
|
||||
type: 'string',
|
||||
description: 'Optional human-readable reason recorded in result_data for the audit trail',
|
||||
maxLength: 500,
|
||||
},
|
||||
},
|
||||
required: ['operation_id'],
|
||||
},
|
||||
outputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
status: { type: 'string', enum: ['rejected'] },
|
||||
operation_id: { type: 'string' },
|
||||
},
|
||||
required: ['status', 'operation_id'],
|
||||
},
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
||||
async execute(args, companyId, userId, supabase, actor) {
|
||||
const operationId = args.operation_id as string
|
||||
if (!operationId) throw new Error('operation_id is required')
|
||||
|
||||
const reason = typeof args.reason === 'string' ? args.reason.slice(0, 500) : undefined
|
||||
|
||||
const { data: op, error: fetchError } = await supabase
|
||||
.from('pending_operations')
|
||||
.select('id, status, operation_type, risk_level')
|
||||
.eq('id', operationId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (fetchError || !op) throw new Error('Pending operation not found')
|
||||
if (op.status !== 'pending') throw new Error(`Operation already ${op.status}`)
|
||||
|
||||
// Atomic claim — flips pending → rejected only when the row is still
|
||||
// pending AND in the caller's tenant (V8.3.1, CC6.3 tenant isolation).
|
||||
// The .eq('status', 'pending') guard makes this a CAS so a concurrent
|
||||
// approval cannot lose to a parallel reject.
|
||||
const { data: updated, error: updateError } = await supabase
|
||||
.from('pending_operations')
|
||||
.update({
|
||||
status: 'rejected',
|
||||
resolved_at: new Date().toISOString(),
|
||||
result_data: {
|
||||
rejected_by: userId,
|
||||
rejected_via: actor?.type ?? 'user',
|
||||
...(actor?.id ? { actor_id: actor.id } : {}),
|
||||
...(reason ? { reason } : {}),
|
||||
},
|
||||
})
|
||||
.eq('id', operationId)
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', 'pending')
|
||||
.select('id')
|
||||
|
||||
if (updateError) throw new Error(`Failed to reject operation: ${updateError.message}`)
|
||||
if (!updated || updated.length === 0) {
|
||||
throw new Error('Operation no longer pending — another caller claimed it')
|
||||
}
|
||||
|
||||
// Audit the rejection so the trail mirrors the approval path.
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId,
|
||||
correlationId: operationId,
|
||||
aggregateType: 'System',
|
||||
aggregateId: operationId,
|
||||
eventType: 'PendingOperationRejected',
|
||||
payload: {
|
||||
operation_id: operationId,
|
||||
operation_type: op.operation_type,
|
||||
risk_level: op.risk_level,
|
||||
channel: 'mcp',
|
||||
...(reason ? { has_reason: true } : { has_reason: false }),
|
||||
},
|
||||
actor: {
|
||||
type: actor?.type === 'api_key' ? 'api_key' : 'user',
|
||||
id: actor?.id ?? userId,
|
||||
...(actor?.label ? { label: actor.label } : {}),
|
||||
},
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (auditErr) {
|
||||
log.warn('Failed to append PendingOperationRejected audit event', auditErr)
|
||||
}
|
||||
|
||||
return { status: 'rejected' as const, operation_id: operationId }
|
||||
},
|
||||
},
|
||||
|
||||
// ── Bring-your-own-extraction for inbox items ────────────────
|
||||
{
|
||||
name: 'gnubok_set_inbox_extracted_data',
|
||||
description: 'Replace extracted_data on an inbox item with agent-supplied fields (bring-your-own-extraction). Use when your own pipeline parses the document better than gnubok\'s OCR. Follow with gnubok_create_supplier_invoice_from_inbox to stage.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
inbox_item_id: { type: 'string', description: 'UUID of the invoice_inbox_items row' },
|
||||
extracted_data: {
|
||||
type: 'object',
|
||||
description: 'Full InvoiceExtractionResult (supplier, invoice, lineItems, totals, vatBreakdown). Validated server-side via the same Zod schema as the AI extractor.',
|
||||
},
|
||||
},
|
||||
required: ['inbox_item_id', 'extracted_data'],
|
||||
},
|
||||
outputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
inbox_item_id: { type: 'string' },
|
||||
matched_supplier_id: { type: ['string', 'null'] },
|
||||
extracted_data: { type: 'object' },
|
||||
},
|
||||
required: ['inbox_item_id', 'extracted_data'],
|
||||
},
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
async execute(args, companyId, userId, supabase, actor) {
|
||||
const inboxItemId = args.inbox_item_id as string
|
||||
if (!inboxItemId) throw new Error('inbox_item_id is required')
|
||||
|
||||
const parsed = InvoiceExtractionSchema.parse(args.extracted_data)
|
||||
// BYO extraction: confidence 0.95 marks the result as agent-supplied
|
||||
// (vs 1.0 the AI extractor uses on a perfect parse) so downstream UI
|
||||
// can render the provenance differently (ISO 27001 A.8.12).
|
||||
const extracted = { ...parsed, confidence: 0.95 }
|
||||
|
||||
const { data: item, error: fetchError } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, company_id, created_supplier_invoice_id')
|
||||
.eq('id', inboxItemId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (fetchError) throw new Error(`Failed to fetch inbox item: ${fetchError.message}`)
|
||||
if (!item) throw new Error('Inbox item not found')
|
||||
// Explicit defense-in-depth tenant check (V4.5.1) alongside the .eq()
|
||||
// filter on the SELECT — surfaces a tampered service-role query
|
||||
// before it reaches the UPDATE.
|
||||
if (item.company_id !== companyId) {
|
||||
throw new Error('Inbox item belongs to a different company')
|
||||
}
|
||||
if (item.created_supplier_invoice_id) {
|
||||
throw new Error('Inbox item is already linked to a supplier invoice and cannot be modified')
|
||||
}
|
||||
|
||||
// Re-run supplier match so agent-supplied fields trigger the same
|
||||
// auto-link the AI path does (org-nr → name, ILIKE).
|
||||
let matchedSupplierId: string | null = null
|
||||
if (extracted.supplier.orgNumber) {
|
||||
const { data: s } = await supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('org_number', extracted.supplier.orgNumber)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (s) matchedSupplierId = s.id
|
||||
}
|
||||
if (!matchedSupplierId && extracted.supplier.name) {
|
||||
const { data: s } = await supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('company_id', companyId)
|
||||
.ilike('name', extracted.supplier.name)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
if (s) matchedSupplierId = s.id
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({
|
||||
extracted_data: extracted as unknown as Record<string, unknown>,
|
||||
matched_supplier_id: matchedSupplierId,
|
||||
})
|
||||
.eq('id', inboxItemId)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (updateError) throw new Error(`Failed to update inbox item: ${updateError.message}`)
|
||||
|
||||
// Audit the BYO override so financial-data provenance is traceable
|
||||
// (GDPR Art. 5(1)(f), SOC 2 CC9.2). Failure must not block the user
|
||||
// flow — the override has already landed in the DB.
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId,
|
||||
correlationId: inboxItemId,
|
||||
aggregateType: 'Document',
|
||||
aggregateId: inboxItemId,
|
||||
eventType: 'DocumentExtractionOverridden',
|
||||
payload: {
|
||||
inbox_item_id: inboxItemId,
|
||||
channel: 'mcp',
|
||||
has_supplier_org_number: extracted.supplier.orgNumber != null,
|
||||
has_invoice_number: extracted.invoice.invoiceNumber != null,
|
||||
extracted_total: extracted.totals.total,
|
||||
matched_supplier_id: matchedSupplierId,
|
||||
},
|
||||
actor: {
|
||||
type: actor?.type === 'api_key' ? 'api_key' : 'user',
|
||||
id: actor?.id ?? userId,
|
||||
...(actor?.label ? { label: actor.label } : {}),
|
||||
},
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (auditErr) {
|
||||
log.warn('Failed to append DocumentExtractionOverridden audit event', auditErr)
|
||||
}
|
||||
|
||||
return {
|
||||
inbox_item_id: inboxItemId,
|
||||
matched_supplier_id: matchedSupplierId,
|
||||
extracted_data: extracted as unknown as Record<string, unknown>,
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
// ── MCP Protocol Handler ─────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user