Files
accounted/lib/auth
Jakob Wennberg 5c52f24a49 feat(mcp): agent-native improvements — progressive discovery, widgets, skills, telemetry (#393)
* feat(mcp): agent-native improvements — progressive discovery, widgets, skills, telemetry

Four coordinated streams of MCP server improvements that move gnubok toward
agent-first design, grounded in Anthropic's Nov 2025 "Code execution with MCP"
article and the May 2026 MCP conference talk.

Context budget — minimize tools/list payload
- New gnubok_search_tools: progressive discovery with name|summary|full detail
  levels and scope filtering. Agents pull only the schemas they need.
- Trimmed all 50 tool descriptions from multi-paragraph blocks (avg ~500-1000
  chars) to one-sentence summaries (avg ~120 chars). Args/Returns/Examples
  blocks dropped — they duplicated inputSchema.
- outputSchema declared on every tool; structuredContent emitted on every
  successful tools/call (was previously only widget-tagged tools).
- protocolVersion bumped to 2025-06-18 (negotiates back to 2024-11-05).
- Workflow examples consolidated into initialize.instructions.
- Net effect: tools/list payload ~43 KB / ~10.8K tokens for 51+ tools, with
  headroom guard at 20K tokens.

MCP applications — server-shipped UI widgets
- New widgets/ directory with typed UiWidget contract; receipt-matcher moved
  out of widget-html.ts (which was deleted) into widgets/receipt-matcher.ts.
- New gnubok_vat_review_widget tool + interactive momsdeklaration widget
  (all 8 rutor with summary card, theme-aware light/dark, copy buttons).
- resources/list and resources/read iterate uiWidgets dynamically — adding
  the next widget is a single file drop.

Skills over MCP — domain-knowledge primitive
- 5 user-facing SKILL.md-style workflow guides authored from existing
  .claude/skills/swedish-* development skills:
  • month-end-close — book → reconcile → VAT (monthly filers) → lock
  • quarterly-vat-review — ruta-by-ruta map, deadlines, common errors
  • year-end-close — bokslut, bokslutstransaktioner, lock → year-end
    → opening balances → close (irreversible)
  • invoicing-rules — ML 17 kap. 24 §, customer types, ROT/RUT, Peppol
  • payroll-monthly — salary run → calculate → review → AGI XML
- gnubok_list_skills (with optional tag filter) + gnubok_load_skill(slug).
  Both unscoped — available to any authenticated key.
- Each skill also exposed as MCP resource at gnubok://skill/<slug>
  (text/markdown) for forward compatibility with a future native
  skills/list primitive.

Tool-call telemetry — measure before optimizing further
- Three new CoreEvent types (mcp.tool_called, mcp.tools_list_called,
  mcp.resource_read), all persisted to event_log (30-day TTL, RLS-scoped).
- Fire-and-forget emission from the dispatcher — never blocks JSON-RPC
  response, double-guarded against handler failures.
- tools/call instrumented at all four exit points (success, execution
  error, scope denied, unknown tool). Latency measured tightly around
  tool.execute() — excludes dispatcher overhead.
- tools/list logs returned tool count (informs progressive-discovery
  adoption); resources/read logs URI + kind discriminator (widget /
  skill / data / unknown).
- No PII or secret material in payloads — only metadata.

Out of scope (explicitly deferred):
- Code-mode SDK (no production code-mode hosts to consume it yet).
- Elicitations (require streamable HTTP transport — bigger architectural lift).
- DB lockdown / RPC funnel (foundational; should follow once telemetry tells
  us where writes actually flow).
- CRUD → intent endpoints (frontend coupling — multi-PR effort).

Tests: +37 new unit tests across search-tools, output-schema, payload-size,
vat-review-widget, skills, telemetry. Existing receipt-matcher test updated
for the new structuredContent contract. 2,615 unit tests passing.
Production build green. No new lint warnings or errors in changed files.

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

* fix(mcp): address PR #393 review findings

Greptile (P1 + P2) and the Swedish accounting compliance bot flagged 9 issues
across security, data correctness, and skill content. All addressed:

Security (P1)
- gnubok_search_tools: scope filter now fails closed when __keyScopes is
  absent. The earlier permissive default leaked the full tool inventory if
  the dispatcher's hard-coded name check ever silently broke. Marker presence
  is part of the contract — explicitly empty array also hides scoped tools.
  Two new test cases pin the fail-closed behaviour.

Compliance — VAT (data correctness)
- get_vat_report now aggregates 2614/2624/2634 (reverse-charge output VAT)
  and exposes them as ruta30/ruta31/ruta32 per SKV 4700. ruta48 also picks
  up 2647 (missing before). ruta49 formula corrected to
  (10+11+12+30+31+32) − 48. The widget renders the new rutor between the
  Utgående and Ingående sections.
- Widget ruta 05 sub-label updated from "3001+3002+3003" to "all momspliktig
  försäljning oavsett skattesats" — ruta 05 covers all domestic taxable
  supplies, not just direct-rate sales.
- Refactored: extracted computeVatReport() helper used by both
  gnubok_get_vat_report and gnubok_vat_review_widget. Removes the
  rename-fragile tools.find() lookup at runtime.

Compliance — payroll
- payroll-monthly skill: replaced "born 1958 or earlier = 10.21%" (the 2024
  formulation) with the statutory rule "age 66+ on 1 January of the income
  year (67+ from income year 2026)". Removed the unsourced "age 16–18:
  11.78%" row in favour of a current växa-stöd description with explicit
  Prop. 2025/26:34 reference and a "verify against current Skatteverket
  tables" caveat.

Compliance — skills text
- invoicing-rules: added explicit footnote on the 1 April 2026 livsmedel
  rate change. Restaurang/servering stays at 12 %; livsmedel sold in other
  forms drops to 6 %. Per Prop. 2025/26:55.
- year-end-close: clarified periodiseringsfond cap as "25 % of överskott
  before this year's avsättning" (IL 30 kap.), removing the ambiguous
  "skattemässigt resultat" phrasing that could be misread as a circular
  after-fond computation.

Schema correctness
- STAGED_OPERATION_SCHEMA.required gains "staged" — every path through
  stagePendingOperation returns the field, so the schema now matches the
  contract that MCP clients validate against.

Tests: 2,617 passing (+2 for the search-tools fail-closed cases).
Production build green.

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

* fix(mcp): address PR #393 round-2 compliance review

Round 2 of the swedish-compliance bot ran after the previous fix-push and
flagged four substantive items + a recommendation. All addressed:

VAT computation (data correctness)
- ruta05 expanded beyond 3001/3002/3003 to cover the common BAS taxable-
  revenue accounts (3001-3008, 3041-3048, 3051-3058, 3071-3078). Companies
  that book to 30xx alternates were previously under-reporting taxable
  turnover; now all standard BAS taxable-revenue numbering contributes.
- One-sided reverse-charge warning: when output VAT is booked on
  2614/2624/2634 (rutor 30/31/32 > 0) but the matching calculated input
  VAT (2645) is zero, computeVatReport now returns a Swedish-language
  warning string. ruta49 is inflated in this case — the warning surfaces
  the most common reverse-charge error per the swedish-vat skill. The
  widget renders warnings in a terracotta panel above the summary card.
- computeVatReport exported and a focused unit test added — exercises 2647
  inclusion in ruta48, reverse-charge balanced/unbalanced cases, and the
  expanded ruta05 mapping. Fills the gap that prior tools/call integration
  tests couldn't reach.

Skill content
- payroll-monthly Step 6: BAS journal-entry example no longer hard-codes
  31.42 % on the 7510/2730 lines. The avgift line is now described as
  "avgift_base × applicable_rate per employee" with explicit aggregation
  semantics for runs that mix full-rate and reduced-rate employees.
  Aligns with the Step-4 reduced-rate caveats already in place.
- invoicing-rules ROT/RUT block: replaced the bare "30 % / max 50 000 SEK"
  text with the full year-by-year picture — RUT 50 % / 75 000 max, ROT
  baseline 30 % / 50 000 max, 2024 H2 doubled ceiling, 2025 May–Dec
  enhanced 50 % rate. Defaults to "verify against current Skatteverket
  table" rather than a single hard-coded rate.

False positives in the round-2 review (no fix needed; documented for the
record):
- "Old vat_report path still computes ruta48 without 2647" — the old path
  was replaced by computeVatReport in the previous push; the bot was
  reading the diff hunk and conflating it with current behaviour.
- "Widget prose says ruta49 = (10+11+12) - 48" — no such prose exists in
  widgets/vat-review.ts. The skill body has the correct
  (10+11+12+30+31+32)-48 formula.
- "Including 'reversed' status entries in VAT aggregation may over-count
  cross-period storno" — current behaviour is correct per Skatteverket
  period-aligned filing: the reversed original stays in its own period,
  the matching storno (status 'posted') lands in the reversal period,
  and they net to zero across the full year. Adding code comment to
  document.

Tests: 2,623 passing (+6 for computeVatReport unit tests). Production
build green.

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

* fix(mcp): address PR #393 round-3 compliance review

Compliance bot re-ran after the round-2 push and flagged three items:

VAT computation
- One-sided reverse-charge warning previously only checked 2645 (EU
  acquisitions). For domestic reverse charge per ML 16:13 (byggtjänster,
  electronics > 100k SEK, etc.) the matching input lands on 2647 — a
  correctly-balanced 2614+2647 booking would have falsely fired the
  warning. Fixed: warning now triggers only when *both* 2645 and 2647
  are zero. Updated message text mentions both accounts. Added a test
  case asserting the no-warning path for 2647-only-input.

Skill documentation drift
- quarterly-vat-review skill body still showed ruta05 source as
  "3001 + 3002 + 3003" while the runtime computeVatReport sums 32 BAS
  taxable-revenue accounts. Updated the skill table to read
  "3001–3008, 3041–3048, 3051–3058, 3071–3078" so the auditor-facing
  docs match the implementation.

outputSchema upgrade
- gnubok_get_vat_report and gnubok_vat_review_widget previously declared
  outputSchema as the bare { type: 'object' }. Replaced with a shared
  VAT_REPORT_OUTPUT_SCHEMA constant declaring period, period_label, all
  11 rutor (with descriptions referencing source accounts), summary,
  and warnings. Modern MCP clients that validate structuredContent
  against outputSchema now have an accurate contract. Added a test
  asserting the schema is non-trivial and declares every ruta the
  runtime returns.

Tests: 2,625 passing (+2 for the 2647 warning path and the
outputSchema shape assertion). Production build green.

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

* fix(mcp): address PR #393 round-4 compliance review

The compliance bot re-ran after the round-3 push with a fresh batch.
Real findings fixed; false positives documented.

VAT computation
- Removed 3004 (Försäljning inom Sverige, momsfri / VAT-exempt) from
  RUTA_05_ACCOUNTS — round-2's expansion accidentally included it. Ruta 05
  is the *taxable* base; exempt sales must NOT contribute. New test pins
  the exclusion.
- Added 3106 (taxable EU goods supply, momspliktig) to RUTA_05_ACCOUNTS.
  Used when EU buyer's VAT number is invalid or buyer is private.
- Added ruta35 — EU intra-community goods supplies, momsfri (account
  3108). Previously omitted entirely from the rutor schema; SKV 4700
  has it as a distinct box separate from ruta 39 (services) and ruta 40
  (export outside EU). VatReportResult, VAT_REPORT_OUTPUT_SCHEMA, the
  widget table, the copy-summary block, and the quarterly-vat-review
  skill table all updated. New test covers 3108 → ruta35 mapping.
- Strengthened the comment on the posted+reversed status filter to
  document why current behavior is correct per ML 2023:200 and
  faktureringsmetoden (the bot's cross-period storno concern is a false
  positive — see commit message rationale below).

Skill content
- invoicing-rules: added explicit BFL 5 kap. 6–7 § / ML 17 kap. 22–23 §
  note that the kreditfaktura itself consumes a sequential number from
  the same (or dedicated KR-) fakturaserie. The KR- prefix is a display
  convention; the underlying löpnummer must be unbroken just like the
  regular series.
- payroll-monthly: added the missing "born 1937 or earlier → 0 %"
  cohort to the rate breakdown. Previously could lead a payroll run to
  over-pay avgifter on the oldest cohort.

False positives in the round-4 review (verified, not changed)
- 2644/2648 as reverse-charge inputs: verified against gnubok's actual
  BAS chart (lib/bookkeeping/bas-data/class-2-equity-liabilities.ts).
  2644 does not exist; 2648 is "Vilande ingående moms" (dormant input
  VAT for cash method), not RC at 6 %. Canonical RC inputs are 2645 (EU)
  and 2647 (domestic) — both already covered.
- Cross-period storno over-count: per ML 2023:200 + Skatteverket
  faktureringsmetoden, the original sale's VAT belongs to the invoice-
  date period; the kreditfaktura's reduction belongs to the storno-date
  period. Including 'reversed' status entries (which still have their
  original date) is therefore correct. *Excluding* them would
  under-report the original period and over-credit the reversal period.
  Added a multi-line comment in computeVatReport documenting this.

Tests: 2,627 passing (+2 for ruta35 mapping and 3004 exclusion).
Production build green.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 20:04:10 +02:00
..