Files
accounted/extensions/general/mcp-server/company-routing.ts
T
31e0cd6e05 feat(onboarding): company setup from the conversation and POST /api/v1/companies (#1814 PR 3) (#1864)
* feat(onboarding): company setup from the conversation and POST /api/v1/companies

Third PR of agent-first onboarding (#1814). Once connected, the agent can
now set up a company end to end without the web wizard, and partner
platforms can provision companies over REST.

- create_company_for_user: service-role-only SECURITY DEFINER twin of
  create_company_with_owner taking the owner explicitly (service clients
  have no auth.uid()). pg-real test covers creation, role gating, unknown
  owner and foreign team.
- lib/company/create-company.ts: the wizard's creation sequence (org
  number, TIC snapshot, BAS chart, settings, first fiscal period, tax
  deadlines, rollback) extracted into createCompanyCore; the Server
  Action delegates to it, behaviour unchanged.
- lib/company/onboarding-input.ts: one Zod schema + planner for the
  agent/API paths; a VAT-registered company without moms_period is
  refused (a missing period silently yields zero VAT deadlines).
- MCP: gnubok_create_company (two-phase: preview, then confirm=true;
  companies:write, company-independent), gnubok_connect_bank and
  gnubok_connect_skatteverket (status + the browser link, gated on
  bank_sync / skatteverket, search-only in the catalog), the
  "onboarding" skill, and initialize instructions pointing at it.
- Consent page pre-ticks companies:write for an account with no company
  yet, so the setup does not dead-end on insufficient scope after signup.
- POST /api/v1/companies (companies:write, dry-run aware) on the same
  core; scope map, registry, spec snapshot and the generated API skill
  updated.
- tools/list payload ceiling raised 59.95K -> 60.4K for the one new
  default-catalog tool (documented in the guard).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* fix(onboarding): explicit f_skatt, org number when VAT-registered, EF first year ends 31 Dec

Review findings on #1864 (Swedish compliance review):
- f_skatt is required, never defaulted to approved (SE-R-005 risk).
- org_number is required when vat_registered: the invoice
  momsregistreringsnummer derives from it (ML 17 kap 24 §).
- An enskild firma's first fiscal year must end on 31 December and its
  start month is forced to 1 even with first_fiscal_year set, mirroring
  the wizard's own rule text (BFL 3 kap. 1 §).
- POST /api/v1/companies no longer claims Idempotency-Key support (the
  wrapper only honours it on company-scoped routes).
- pg-real: createCompanyCore's chart seed runs under the real
  service_role, which the unit tests could not prove.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* test(pg): starter chart has 41 accounts, assert non-empty

The service_role chart-seed proof passed the part that mattered (no
42501 from seed_chart_of_accounts) and failed on a wrong row-count
guess: the seeded chart is a curated starter set, not the full BAS list.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* fix(migrations): move create_company_for_user to 20260825120000

main gained 20260824170000_bulk_book_transactions_service_actor.sql with
the same version while this branch was open; two files on one version
abort every Supabase branch apply and the prod auto-apply.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* chore(api): refresh spec snapshot and generated skill after rebasing onto main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

* fix(mcp): flat create_company result, refuse localhost connect links, test hygiene

CodeRabbit on #1864: the confirmed-create result was wrapped in the
{ data, next } envelope while its outputSchema promised top-level
fields; it now returns the fields with next as a sibling. The two
connect-link tools refuse to build a link when NEXT_PUBLIC_APP_URL is
unset instead of handing a remote user a localhost URL. Tests clear
mocks and the event bus in beforeEach. Not changed: the rollback
already survives user_preferences.active_company_id (that FK is ON
DELETE SET NULL since 20260331010000), and v1 error details stay in the
surface's English developer convention.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018wCdzRTatKiDByKB8hCNT6

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 12:41:02 +02:00

183 lines
5.9 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import type { ApiKeyScope } from '@/lib/auth/api-keys'
import type { CompanyRole } from '@/types'
const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
const COMPANY_INDEPENDENT_TOOLS = new Set([
'gnubok_search_tools',
'gnubok_list_skills',
'gnubok_load_skill',
'gnubok_list_companies',
// Creates the company: by definition it runs before one exists.
'gnubok_create_company',
])
/**
* Company-independent tools that still USE a company when one is available:
* they run without one (anonymous or not-yet-onboarded callers, issue #1814)
* but accept an explicit company_id, which is then membership-checked like
* on any company-dependent tool. gnubok_list_skills filters skills by the
* company's entity type, employees and VAT registration.
*/
const OPTIONAL_COMPANY_TOOLS = new Set(['gnubok_list_skills'])
export function isOptionalCompanyTool(toolName: string): boolean {
return OPTIONAL_COMPANY_TOOLS.has(toolName)
}
export const COMPANY_ID_INPUT_PROPERTY = {
type: 'string',
format: 'uuid',
description: 'Target company ID. Omit for default.',
} as const
export interface McpCompanyContext {
companyId: string
role: CompanyRole
isDefault: boolean
}
interface ToolSchemaSource {
name: string
inputSchema: Record<string, unknown>
}
export function codedError(
code: 'VALIDATION_ERROR' | 'NOT_FOUND' | 'FORBIDDEN' | 'INTERNAL_ERROR' | 'NO_COMPANY_YET',
message: string
) {
return Object.assign(new Error(message), { code })
}
/**
* Thrown when a company-scoped operation runs on a key whose user has no
* company at all (minted from the OAuth popup before onboarding, issue
* #1814). Maps to the NO_COMPANY_YET structured error with its remediation.
*/
export function noCompanyYetError(): Error {
return codedError(
'NO_COMPANY_YET',
'This account has no company yet. Create the company in the web app, then retry.'
)
}
function isCompanyRole(value: unknown): value is CompanyRole {
return value === 'owner' || value === 'admin' || value === 'member' || value === 'viewer'
}
export function isCompanyDependentTool(toolName: string): boolean {
return !COMPANY_INDEPENDENT_TOOLS.has(toolName)
}
export function isTenantWriteScope(scope: ApiKeyScope | undefined): boolean {
return (
scope?.endsWith(':write') === true ||
scope?.endsWith(':approve') === true ||
scope?.endsWith(':manage') === true ||
// Sign-off attests on the company's behalf: a write for the role guard
// even though the scope is deliberately not `:write` (linking rows must
// not imply the right to attest).
scope?.endsWith(':signoff') === true
)
}
export function projectToolInputSchema(tool: ToolSchemaSource): Record<string, unknown> {
if (!isCompanyDependentTool(tool.name) && !isOptionalCompanyTool(tool.name)) return tool.inputSchema
const properties =
tool.inputSchema.properties && typeof tool.inputSchema.properties === 'object'
? (tool.inputSchema.properties as Record<string, unknown>)
: {}
return {
...tool.inputSchema,
properties: {
...properties,
company_id: COMPANY_ID_INPUT_PROPERTY,
},
}
}
export function extractRequestedCompany(
rawArgs: Record<string, unknown>
): { requestedCompanyId: string | undefined; toolArgs: Record<string, unknown> } {
const { company_id: rawCompanyId, ...toolArgs } = rawArgs
if (rawCompanyId === undefined) return { requestedCompanyId: undefined, toolArgs }
if (typeof rawCompanyId !== 'string' || !UUID_PATTERN.test(rawCompanyId)) {
throw codedError('VALIDATION_ERROR', 'company_id must be a valid UUID')
}
return { requestedCompanyId: rawCompanyId, toolArgs }
}
export async function resolveMcpCompanyContext(args: {
supabase: SupabaseClient
userId: string
/** null while the key's user has no company (see validateApiKey). */
defaultCompanyId: string | null
requestedCompanyId?: string
}): Promise<McpCompanyContext> {
const companyId = args.requestedCompanyId ?? args.defaultCompanyId
if (!companyId) {
throw noCompanyYetError()
}
const { data: membership, error } = await args.supabase
.from('company_members')
.select('company_id, role, companies!inner(archived_at)')
.eq('user_id', args.userId)
.eq('company_id', companyId)
.is('companies.archived_at', null)
.maybeSingle()
if (error) {
throw codedError('INTERNAL_ERROR', `Failed to resolve company membership: ${error.message}`)
}
if (!membership) {
throw codedError('NOT_FOUND', 'Company not found')
}
if (!isCompanyRole(membership.role)) {
throw codedError('FORBIDDEN', 'Company membership has an unsupported role')
}
return {
companyId,
role: membership.role,
isDefault: companyId === args.defaultCompanyId,
}
}
export function assertMcpCompanyWriteAccess(
context: McpCompanyContext,
scope: ApiKeyScope | undefined
): void {
if (context.role === 'viewer' && isTenantWriteScope(scope)) {
throw codedError('FORBIDDEN', 'Write permission required for this company')
}
}
export function addCompanyToNextHint(next: unknown, companyId: string): unknown {
if (!next || typeof next !== 'object' || Array.isArray(next)) return next
const hint = next as Record<string, unknown>
if (typeof hint.tool !== 'string' || !isCompanyDependentTool(hint.tool)) return next
const args =
hint.args && typeof hint.args === 'object' && !Array.isArray(hint.args)
? (hint.args as Record<string, unknown>)
: {}
return {
...hint,
args: { ...args, company_id: companyId },
}
}
export function addCompanyToTopLevelNext(result: unknown, companyId: string): unknown {
if (!result || typeof result !== 'object' || Array.isArray(result)) return result
const record = result as Record<string, unknown>
if (!record.next) return result
return {
...record,
next: addCompanyToNextHint(record.next, companyId),
}
}