Files
accounted/extensions/general/mcp-server/__tests__/agent-briefing.test.ts
T
Jakob WennbergandClaude Opus 4.8 43007fa869 feat(mcp): self-describing agent surface — staging _meta, company identity, clean skill summaries (#775)
* feat(mcp): make the agent surface self-describing (staging _meta, company identity, clean summaries)

A pass over the MCP server's agent-facing surface so an agent can act
correctly without parsing description prose:

- Machine-readable staging contract: deriveToolMeta() attaches _meta to
  tools/list (and search detail=full) — { requires_approval, approve_tool,
  preflight? } — keyed off the STAGED_OPERATION_SCHEMA output schema. Literal
  _meta (e.g. UI widget hints) wins on collision. TOOL_PREFLIGHT_MAP names the
  read-only pre-flight for the few writes that have one (year-end readiness,
  VAT validate, depreciation proposal). Guarded by staging-meta.test.ts.
- Company identity in gnubok_get_agent_briefing: returns a `company` block
  (id, name, org_number, entity_type, accounting_method) so the agent can
  confirm WHICH entity it operates on and pick the right settlement account
  (accrual = credit 1510; cash = debit 19xx) before any write. Best-effort —
  a missing row never blocks the briefing. Covered by agent-briefing.test.ts.
- toSummary(): trims the long, keyword-stuffed SKILL.md frontmatter into clean
  one-liners for gnubok_list_skills / gnubok_get_agent_briefing so the client
  never truncates one mid-sentence; full bodies stay in gnubok_load_skill.
  Covered by to-summary.test.ts.
- bank-reconciliation skill: a match/link decision tree (what you have x
  whether a verifikat exists) and kontant- vs faktureringsmetoden settlement
  accounts.
- Prose/description clarifications: "Stages"/"Stages for approval" on the
  link tools; propose_dispositioner/accruals note there is no dedicated MCP
  poster; server-info documents _meta and the legacy gnubok_ tool prefix.

All 34 touched MCP tests pass. Merged cleanly on top of #759/#760 (server.ts).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(mcp): make accounting_method description state the full settlement posting

Review (swedish-accounting-compliance): the agent-briefing schema described
accrual as "credit 1510 on payment", which reads as a one-sided entry. Spell
out both sides (payment debits 19xx AND credits 1510) so an agent can't infer a
single-leg posting that violates BFL 5 kap double-entry. Mirrors the precision
already in the bank-reconciliation skill body. Payload-size guard still passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 13:42:12 +02:00

348 lines
12 KiB
TypeScript

/**
* Tests for gnubok_get_agent_briefing — session-bootstrap context for the
* specialized accountant agent over MCP.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { tools } from '../server'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/auth/api-keys')>()
return {
...actual,
extractBearerToken: vi.fn().mockReturnValue('test-token'),
validateApiKey: vi.fn().mockResolvedValue({
userId: 'user-1',
companyId: 'company-1',
scopes: ['agent:read'],
}),
createServiceClientNoCookies: vi.fn(),
}
})
/** Builds a supabase mock whose three relevant tables resolve to canned data. */
function mockSupabase(opts: {
profile?: {
profile_summary: string | null
horizontal_atoms: string[] | null
vertical_atoms: string[] | null
modifier_atoms: string[] | null
} | null
memoryRows?: Array<{
id: string
kind: string
content: string
relevance_score: number | null
}>
atomRows?: Array<{
id: string
tier: string
title: string | null
description: string
}>
// profiles.full_name for the signed-in user. undefined → no profile row.
userFullName?: string | null
// companies row for the active company. undefined → no row (null data).
company?: { name: string | null; org_number: string | null; entity_type: string | null } | null
// company_settings.accounting_method. undefined → no settings row (null data).
accountingMethod?: string | null
errors?: { profile?: string; memory?: string; atoms?: string }
}) {
const profile = opts.profile === undefined ? null : opts.profile
const memoryRows = opts.memoryRows ?? []
const atomRows = opts.atomRows ?? []
const errors = opts.errors ?? {}
return {
from: vi.fn((table: string) => {
if (table === 'profiles') {
return {
select: vi.fn(() => ({
eq: vi.fn(() => ({
maybeSingle: vi.fn().mockResolvedValue({
data:
opts.userFullName === undefined ? null : { full_name: opts.userFullName },
error: null,
}),
})),
})),
}
}
if (table === 'agent_profiles') {
return {
select: vi.fn(() => ({
eq: vi.fn(() => ({
maybeSingle: vi.fn().mockResolvedValue({
data: profile,
error: errors.profile ? new Error(errors.profile) : null,
}),
})),
})),
}
}
if (table === 'agent_memory') {
return {
select: vi.fn(() => ({
eq: vi.fn(() => ({
eq: vi.fn(() => ({
order: vi.fn(() => ({
order: vi.fn(() => ({
limit: vi.fn().mockResolvedValue({
data: memoryRows,
error: errors.memory ? new Error(errors.memory) : null,
}),
})),
})),
})),
})),
})),
}
}
if (table === 'agent_atom_registry') {
return {
select: vi.fn(() => ({
in: vi.fn(() => ({
eq: vi.fn().mockResolvedValue({
data: atomRows,
error: errors.atoms ? new Error(errors.atoms) : null,
}),
})),
})),
}
}
if (table === 'companies') {
return {
select: vi.fn(() => ({
eq: vi.fn(() => ({
maybeSingle: vi.fn().mockResolvedValue({
data: opts.company === undefined ? null : opts.company,
error: null,
}),
})),
})),
}
}
if (table === 'company_settings') {
return {
select: vi.fn(() => ({
eq: vi.fn(() => ({
maybeSingle: vi.fn().mockResolvedValue({
data:
opts.accountingMethod === undefined
? null
: { accounting_method: opts.accountingMethod },
error: null,
}),
})),
})),
}
}
throw new Error(`Unexpected table in test mock: ${table}`)
}),
}
}
describe('gnubok_get_agent_briefing tool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('is registered with readOnly + idempotent annotations', () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')
expect(tool).toBeDefined()
expect(tool?.annotations.readOnlyHint).toBe(true)
expect(tool?.annotations.idempotentHint).toBe(true)
expect(tool?.annotations.destructiveHint).toBe(false)
})
it('inputSchema declares no required args (no inputs)', () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const input = tool.inputSchema as { properties?: Record<string, unknown>; required?: string[]; additionalProperties: boolean }
expect(input.additionalProperties).toBe(false)
expect(input.required).toBeUndefined()
})
it('returns null summary, empty atoms, empty memory, null user_name when nothing exists', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({ profile: null })
const result = (await tool.execute(
{},
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' }
)) as {
user_name: string | null
profile_summary: string | null
atoms: unknown[]
memory: unknown[]
}
expect(result.profile_summary).toBeNull()
expect(result.atoms).toEqual([])
expect(result.memory).toEqual([])
expect(result.user_name).toBeNull()
})
it('returns the active company block so the agent can confirm the entity before writing', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({
profile: null,
company: { name: 'Acme AB', org_number: '556677-8899', entity_type: 'aktiebolag' },
accountingMethod: 'cash',
})
const result = (await tool.execute(
{},
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' }
)) as {
company: {
id: string
name: string | null
org_number: string | null
entity_type: string | null
accounting_method: string | null
}
}
expect(result.company).toEqual({
id: 'company-1',
name: 'Acme AB',
org_number: '556677-8899',
entity_type: 'aktiebolag',
accounting_method: 'cash',
})
})
it('always returns the company id even when the company/settings rows are missing', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({ profile: null })
const result = (await tool.execute(
{},
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' }
)) as {
company: { id: string; name: string | null; accounting_method: string | null }
}
expect(result.company.id).toBe('company-1')
expect(result.company.name).toBeNull()
expect(result.company.accounting_method).toBeNull()
})
it('returns only the first name (tilltalsnamn) — data minimisation, not the full legal name', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({ profile: null, userFullName: 'Peter Bennet' })
const result = (await tool.execute(
{},
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' }
)) as { user_name: string | null }
// GDPR Art.5(1)(c): the surname never enters the LLM prompt.
expect(result.user_name).toBe('Peter')
})
it('treats a blank full_name as no name (null)', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({ profile: null, userFullName: ' ' })
const result = (await tool.execute(
{},
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' }
)) as { user_name: string | null }
expect(result.user_name).toBeNull()
})
it('returns profile + atom metadata + memory when populated', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({
profile: {
profile_summary: 'Du driver Acme AB som IT-konsult …',
horizontal_atoms: ['horizontal/swedish-vat'],
vertical_atoms: ['vertical/konsult-it'],
modifier_atoms: ['modifier/single-shareholder-ab-fmb'],
},
atomRows: [
{ id: 'horizontal/swedish-vat', tier: 'horizontal', title: 'Swedish VAT', description: 'Moms compliance' },
{ id: 'vertical/konsult-it', tier: 'vertical', title: 'IT-konsult', description: 'SNI 62' },
{ id: 'modifier/single-shareholder-ab-fmb', tier: 'modifier', title: 'Fåmansbolag', description: 'AB single shareholder' },
],
memoryRows: [
{ id: 'mem-1', kind: 'fact', content: 'Hyresavtal löper t.o.m. 2027', relevance_score: 0.9 },
{ id: 'mem-2', kind: 'preference', content: 'Föredrar månadsslut den 25:e', relevance_score: 0.7 },
],
})
const result = (await tool.execute(
{},
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' }
)) as {
profile_summary: string | null
atoms: Array<{ id: string; tier: string; title: string; description: string }>
memory: Array<{ id: string; kind: string; content: string; relevance_score: number | null }>
}
expect(result.profile_summary).toContain('Acme AB')
expect(result.atoms).toHaveLength(3)
expect(result.atoms.map((a) => a.id).sort()).toEqual([
'horizontal/swedish-vat',
'modifier/single-shareholder-ab-fmb',
'vertical/konsult-it',
])
expect(result.memory).toHaveLength(2)
expect(result.memory[0].id).toBe('mem-1') // top-ranked
expect(result.memory[0].relevance_score).toBe(0.9)
})
it('handles profile present but no atoms loaded yet', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({
profile: {
profile_summary: 'Composer ran but selected nothing.',
horizontal_atoms: null,
vertical_atoms: null,
modifier_atoms: null,
},
})
const result = (await tool.execute(
{},
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' }
)) as {
profile_summary: string | null
atoms: unknown[]
memory: unknown[]
}
expect(result.profile_summary).toBe('Composer ran but selected nothing.')
expect(result.atoms).toEqual([])
})
it('surfaces a structured error if the profile query fails', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({ profile: null, errors: { profile: 'pg-down' } })
await expect(
tool.execute({}, 'company-1', 'user-1', supabase as never, { type: 'api_key' })
).rejects.toThrow(/Failed to load agent profile.*pg-down/)
})
it('surfaces a structured error if the memory query fails', async () => {
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
const supabase = mockSupabase({ profile: null, errors: { memory: 'rls-denied' } })
await expect(
tool.execute({}, 'company-1', 'user-1', supabase as never, { type: 'api_key' })
).rejects.toThrow(/Failed to load agent memory.*rls-denied/)
})
})