firmaapi-mcp-server 3.1.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -7
- package/dist/api-client.d.ts +59 -0
- package/dist/api-client.js +184 -53
- package/dist/api-client.js.map +1 -1
- package/dist/factual-tools.d.ts +1 -1
- package/dist/http.d.ts +37 -0
- package/dist/http.js +88 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +19 -4179
- package/dist/index.js.map +1 -1
- package/dist/server.d.ts +25 -0
- package/dist/server.js +4327 -0
- package/dist/server.js.map +1 -0
- package/dist/skills.d.ts +11 -0
- package/dist/skills.generated.d.ts +1 -0
- package/dist/skills.generated.js +7 -0
- package/dist/skills.generated.js.map +1 -0
- package/dist/skills.js +28 -0
- package/dist/skills.js.map +1 -0
- package/dist/tool-costs.d.ts +7 -0
- package/dist/tool-costs.js +50 -0
- package/dist/tool-costs.js.map +1 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.js +7 -0
- package/dist/version.js.map +1 -0
- package/package.json +61 -51
package/dist/server.js
ADDED
|
@@ -0,0 +1,4327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FirmaAPI MCP Server - værktøjerne.
|
|
3
|
+
*
|
|
4
|
+
* `createFirmaApiServer()` bygger en server med alle værktøjer. Den bruges
|
|
5
|
+
* både af stdio-indgangen (index.ts, npm-pakken) og af HTTP-indgangen
|
|
6
|
+
* (http.ts, https://firmaapi.dk/mcp).
|
|
7
|
+
*/
|
|
8
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { registerFactualTools } from "./factual-tools.js";
|
|
11
|
+
import { defaultApiClient, handleApiError, formatUpgradeNotice, CLIENT_VERSION } from "./api-client.js";
|
|
12
|
+
import { withApiCost } from "./tool-costs.js";
|
|
13
|
+
const CHARACTER_LIMIT = 25_000;
|
|
14
|
+
// ── Helpers ──────────────────────────────────────────────────────
|
|
15
|
+
function truncate(text) {
|
|
16
|
+
if (text.length <= CHARACTER_LIMIT)
|
|
17
|
+
return text;
|
|
18
|
+
return text.slice(0, CHARACTER_LIMIT) + "\n\n⚠️ Responsen er afkortet. Brug filtre eller limit for at indsnævre resultatet.";
|
|
19
|
+
}
|
|
20
|
+
const FORMAT_SCHEMA = z
|
|
21
|
+
.enum(["markdown", "json"])
|
|
22
|
+
.optional()
|
|
23
|
+
.describe("Output-format. 'markdown' (default) er læsbart for mennesker, 'json' returnerer rå strukturerede data fra API'et.");
|
|
24
|
+
// Plan-requirement badges — tilføjes konsistent i bunden af tool-descriptions.
|
|
25
|
+
// Brug i template literals: `${PLAN.standard}` eller `${PLAN.pro}`. Hvis et
|
|
26
|
+
// tool fejler pga. plan-restriktion, returneres en HTTP 403 fra API'et og
|
|
27
|
+
// `handleApiError` formaterer den som "Adgang nægtet — opgrader på firmaapi.dk/priser".
|
|
28
|
+
const PLAN = {
|
|
29
|
+
any: "**Plan**: Tilgængelig på alle planer (Gratis+).",
|
|
30
|
+
basis: "**Plan**: Kræver Basis-plan eller højere. På Gratis returneres 403.",
|
|
31
|
+
standard: "**Plan**: Kræver Standard-plan eller højere. På Gratis/Basis returneres 403 eller felter er tomme.",
|
|
32
|
+
pro: "**Plan**: Kræver Professionel-plan eller Enterprise for personprofiler og koncernrelationer. Ledelsesdata er tilgængelige fra Basis; person_id kræver Professionel+.",
|
|
33
|
+
};
|
|
34
|
+
const FIELDS_SCHEMA = z
|
|
35
|
+
.array(z.string())
|
|
36
|
+
.optional()
|
|
37
|
+
.describe("Begræns hvilke felter der returneres pr. række (fx ['name','cvr','zipcode']). Kombineres med format=json for kompakt output. Springes hvis verbose=true.");
|
|
38
|
+
const VERBOSE_SCHEMA = z
|
|
39
|
+
.boolean()
|
|
40
|
+
.optional()
|
|
41
|
+
.describe("Giv det fulde, ufiltrerede output (inkl. lange branchetekster). Default er kompakt for at spare tokens.");
|
|
42
|
+
const COMPACT_LIST_FIELDS = ["name", "cvr", "city", "zipcode", "industry_code", "status"];
|
|
43
|
+
function pickFields(obj, fields) {
|
|
44
|
+
const out = {};
|
|
45
|
+
for (const f of fields) {
|
|
46
|
+
if (f in obj)
|
|
47
|
+
out[f] = obj[f];
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
function selectListFields(rows, fields, verbose) {
|
|
52
|
+
if (verbose)
|
|
53
|
+
return rows;
|
|
54
|
+
const selected = fields && fields.length > 0 ? fields : [...COMPACT_LIST_FIELDS];
|
|
55
|
+
return rows.map((r) => pickFields(r, selected));
|
|
56
|
+
}
|
|
57
|
+
function jsonText(data) {
|
|
58
|
+
const pretty = JSON.stringify(data, null, 2);
|
|
59
|
+
if (pretty.length <= CHARACTER_LIMIT) {
|
|
60
|
+
return { content: [{ type: "text", text: pretty }] };
|
|
61
|
+
}
|
|
62
|
+
// Try without indentation before giving up — saves ~30-40% on most payloads
|
|
63
|
+
// and keeps the output as valid parseable JSON for agent pipelines.
|
|
64
|
+
const compact = JSON.stringify(data);
|
|
65
|
+
if (compact.length <= CHARACTER_LIMIT) {
|
|
66
|
+
return { content: [{ type: "text", text: compact }] };
|
|
67
|
+
}
|
|
68
|
+
// Mid-string truncation would produce broken JSON, so emit a valid
|
|
69
|
+
// error envelope instead.
|
|
70
|
+
const envelope = {
|
|
71
|
+
error: "response_too_large",
|
|
72
|
+
character_limit: CHARACTER_LIMIT,
|
|
73
|
+
actual_size: compact.length,
|
|
74
|
+
hint: "Brug 'limit', 'fields' eller mere specifikke filtre for at reducere svaret.",
|
|
75
|
+
};
|
|
76
|
+
return { content: [{ type: "text", text: JSON.stringify(envelope, null, 2) }] };
|
|
77
|
+
}
|
|
78
|
+
function formatPickedValue(v) {
|
|
79
|
+
if (v == null || v === "")
|
|
80
|
+
return null;
|
|
81
|
+
if (typeof v === "object")
|
|
82
|
+
return JSON.stringify(v);
|
|
83
|
+
return String(v);
|
|
84
|
+
}
|
|
85
|
+
function formatPickedRow(c, fields) {
|
|
86
|
+
const subset = pickFields(c, fields);
|
|
87
|
+
const formatted = Object.entries(subset)
|
|
88
|
+
.map(([k, v]) => {
|
|
89
|
+
const rendered = formatPickedValue(v);
|
|
90
|
+
return rendered === null ? null : `${k}=${rendered}`;
|
|
91
|
+
})
|
|
92
|
+
.filter((s) => s !== null)
|
|
93
|
+
.join(", ");
|
|
94
|
+
if (formatted)
|
|
95
|
+
return `- ${formatted}`;
|
|
96
|
+
// No requested field carried a value — fall back to CVR so the row is
|
|
97
|
+
// still identifiable instead of showing an empty bullet.
|
|
98
|
+
const cvr = c.cvr;
|
|
99
|
+
return cvr ? `- (CVR ${cvr}, ingen v\u00e6rdier for valgte felter)` : `- (ingen v\u00e6rdier for valgte felter)`;
|
|
100
|
+
}
|
|
101
|
+
function dkk(v) {
|
|
102
|
+
return v != null ? `${Number(v).toLocaleString("da-DK")} DKK` : "—";
|
|
103
|
+
}
|
|
104
|
+
function pct(v) {
|
|
105
|
+
return v != null ? `${(Number(v) * 100).toFixed(1)}%` : "—";
|
|
106
|
+
}
|
|
107
|
+
function formatCompanyMarkdown(c) {
|
|
108
|
+
const lines = [];
|
|
109
|
+
lines.push(`## ${c.name} (CVR ${c.cvr})`);
|
|
110
|
+
lines.push("");
|
|
111
|
+
const upgradeNotice = formatUpgradeNotice(c);
|
|
112
|
+
if (upgradeNotice)
|
|
113
|
+
lines.push(upgradeNotice, "");
|
|
114
|
+
// Stamdata
|
|
115
|
+
lines.push(`- **Status**: ${c.status}`);
|
|
116
|
+
if (c.company_type)
|
|
117
|
+
lines.push(`- **Selskabsform**: ${c.company_type}`);
|
|
118
|
+
if (c.enhedsnummer)
|
|
119
|
+
lines.push(`- **Enhedsnummer**: ${c.enhedsnummer}`);
|
|
120
|
+
if (c.industry_text)
|
|
121
|
+
lines.push(`- **Branche**: ${c.industry_text} (${c.industry_code})`);
|
|
122
|
+
const secIndustries = c.secondary_industries;
|
|
123
|
+
if (secIndustries?.length) {
|
|
124
|
+
for (const si of secIndustries) {
|
|
125
|
+
lines.push(`- **Sekundær branche**: ${si.text} (${si.code})`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (c.founded)
|
|
129
|
+
lines.push(`- **Stiftet**: ${c.founded}`);
|
|
130
|
+
if (c.employees)
|
|
131
|
+
lines.push(`- **Ansatte**: ${c.employees}`);
|
|
132
|
+
if (c.annual_employees && c.annual_employees !== c.employees)
|
|
133
|
+
lines.push(`- **Årsværk**: ${c.annual_employees}`);
|
|
134
|
+
lines.push(`- **Reklamebeskyttet**: ${c.ad_protected ? "Ja" : "Nej"}`);
|
|
135
|
+
// Adresse
|
|
136
|
+
if (c.address) {
|
|
137
|
+
let addr = `${c.address}, ${c.zipcode} ${c.city}`;
|
|
138
|
+
if (c.municipality_name)
|
|
139
|
+
addr += ` (${c.municipality_name} kommune)`;
|
|
140
|
+
lines.push(`- **Adresse**: ${addr}`);
|
|
141
|
+
}
|
|
142
|
+
// Phase 5: address_full delfelter (Standard+) — vis kun hvis felter er sat ud over
|
|
143
|
+
// basis-adressen, så vi ikke duplikerer
|
|
144
|
+
const addressFull = c.address_full;
|
|
145
|
+
if (addressFull) {
|
|
146
|
+
const detailParts = [];
|
|
147
|
+
if (addressFull.floor)
|
|
148
|
+
detailParts.push(`etage ${addressFull.floor}`);
|
|
149
|
+
if (addressFull.door)
|
|
150
|
+
detailParts.push(`dør ${addressFull.door}`);
|
|
151
|
+
if (addressFull.po_box)
|
|
152
|
+
detailParts.push(`postboks ${addressFull.po_box}`);
|
|
153
|
+
if (addressFull.co_name)
|
|
154
|
+
detailParts.push(`c/o ${addressFull.co_name}`);
|
|
155
|
+
if (addressFull.country_code && addressFull.country_code !== "DK") {
|
|
156
|
+
detailParts.push(`land ${addressFull.country_code}`);
|
|
157
|
+
}
|
|
158
|
+
if (detailParts.length) {
|
|
159
|
+
lines.push(`- **Adresse-detaljer**: ${detailParts.join(", ")}`);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (c.latitude != null && c.longitude != null) {
|
|
163
|
+
lines.push(`- **Koordinater**: ${c.latitude}, ${c.longitude}`);
|
|
164
|
+
}
|
|
165
|
+
// Kontaktoplysninger
|
|
166
|
+
if (c.phone)
|
|
167
|
+
lines.push(`- **Tlf**: ${c.phone}`);
|
|
168
|
+
const allPhones = c.all_phones;
|
|
169
|
+
if (allPhones && allPhones.length > 1) {
|
|
170
|
+
lines.push(`- **Alle telefonnumre**: ${allPhones.join(", ")}`);
|
|
171
|
+
}
|
|
172
|
+
if (c.email)
|
|
173
|
+
lines.push(`- **Email**: ${c.email}`);
|
|
174
|
+
const allEmails = c.all_emails;
|
|
175
|
+
if (allEmails && allEmails.length > 1) {
|
|
176
|
+
lines.push(`- **Alle e-mails**: ${allEmails.join(", ")}`);
|
|
177
|
+
}
|
|
178
|
+
if (c.fax)
|
|
179
|
+
lines.push(`- **Fax**: ${c.fax}`);
|
|
180
|
+
if (c.website)
|
|
181
|
+
lines.push(`- **Web**: ${c.website}`);
|
|
182
|
+
// Formål og binavne
|
|
183
|
+
if (c.purpose)
|
|
184
|
+
lines.push(`- **Formål**: ${c.purpose}`);
|
|
185
|
+
const secNames = c.secondary_names;
|
|
186
|
+
if (secNames?.length) {
|
|
187
|
+
lines.push(`- **Binavne**: ${secNames.join(", ")}`);
|
|
188
|
+
}
|
|
189
|
+
// Økonomi og registrering
|
|
190
|
+
if (c.capital)
|
|
191
|
+
lines.push(`- **Kapital**: ${Number(c.capital).toLocaleString("da-DK")} ${c.capital_currency || "DKK"}`);
|
|
192
|
+
if (c.signing_rule)
|
|
193
|
+
lines.push(`- **Tegningsregel**: ${c.signing_rule}`);
|
|
194
|
+
if (c.accounting_class)
|
|
195
|
+
lines.push(`- **Regnskabsklasse**: ${c.accounting_class}`);
|
|
196
|
+
if (c.fiscal_year_start || c.fiscal_year_end) {
|
|
197
|
+
lines.push(`- **Regnskabsår**: ${c.fiscal_year_start || "?"} → ${c.fiscal_year_end || "?"}`);
|
|
198
|
+
}
|
|
199
|
+
if (c.audit_form)
|
|
200
|
+
lines.push(`- **Revisionsform**: ${c.audit_form}`);
|
|
201
|
+
// Registreringsoplysninger
|
|
202
|
+
if (c.employer_registration_date)
|
|
203
|
+
lines.push(`- **Arbejdsgiverregistrering**: ${c.employer_registration_date}`);
|
|
204
|
+
if (c.vat_registration_date)
|
|
205
|
+
lines.push(`- **Momsregistrering**: ${c.vat_registration_date}`);
|
|
206
|
+
if (c.import_registered)
|
|
207
|
+
lines.push(`- **Importregistreret**: Ja`);
|
|
208
|
+
if (c.export_registered)
|
|
209
|
+
lines.push(`- **Eksportregistreret**: Ja`);
|
|
210
|
+
const excise = c.excise_registrations;
|
|
211
|
+
if (excise?.length) {
|
|
212
|
+
lines.push(`- **Punktafgiftsregistreringer**: ${excise.join(", ")}`);
|
|
213
|
+
}
|
|
214
|
+
// Legacy owners: kept for backwards compatibility. Prefer register_entries,
|
|
215
|
+
// executives and board_members when those split fields are available.
|
|
216
|
+
const owners = c.owners;
|
|
217
|
+
if (owners?.length) {
|
|
218
|
+
lines.push("");
|
|
219
|
+
lines.push("### Legacy owners");
|
|
220
|
+
for (const o of owners) {
|
|
221
|
+
const parts = [o.name];
|
|
222
|
+
if (o.title)
|
|
223
|
+
parts.push(`(${o.title})`);
|
|
224
|
+
if (o.ownership_share != null)
|
|
225
|
+
parts.push(`— ${o.ownership_share}%`);
|
|
226
|
+
if (o.person_id)
|
|
227
|
+
parts.push(`[ID: ${o.person_id}]`);
|
|
228
|
+
lines.push(`- ${parts.join(" ")}`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// Revisorer
|
|
232
|
+
const auditors = c.auditors;
|
|
233
|
+
if (auditors?.length) {
|
|
234
|
+
lines.push("");
|
|
235
|
+
lines.push("### Revisorer");
|
|
236
|
+
for (const a of auditors) {
|
|
237
|
+
const parts = [a.name];
|
|
238
|
+
if (a.title)
|
|
239
|
+
parts.push(`(${a.title})`);
|
|
240
|
+
lines.push(`- ${parts.join(" ")}`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
// Phase 5: udvidede ERST-felter
|
|
244
|
+
if (c.is_listed === true)
|
|
245
|
+
lines.push(`- **Børsnoteret**: Ja`);
|
|
246
|
+
if (c.audit_opted_out === true)
|
|
247
|
+
lines.push(`- **Revision fravalgt**: Ja`);
|
|
248
|
+
if (c.has_share_classes === true)
|
|
249
|
+
lines.push(`- **Aktieklasser**: Ja`);
|
|
250
|
+
if (c.subject_to_aml_law === true)
|
|
251
|
+
lines.push(`- **Hvidvasklov**: Omfattet`);
|
|
252
|
+
else if (c.subject_to_aml_law === false)
|
|
253
|
+
lines.push(`- **Hvidvasklov**: Ikke omfattet`);
|
|
254
|
+
if (c.articles_last_amended)
|
|
255
|
+
lines.push(`- **Seneste vedtægtsændring**: ${c.articles_last_amended}`);
|
|
256
|
+
const dissolution = c.dissolution_threat;
|
|
257
|
+
if (dissolution?.date) {
|
|
258
|
+
lines.push(`- **Opløsningstrussel**: ${dissolution.date}${dissolution.reason ? ` (${dissolution.reason})` : ""}`);
|
|
259
|
+
}
|
|
260
|
+
if (c.archive_registration_number) {
|
|
261
|
+
lines.push(`- **Arkivregistreringsnummer**: ${c.archive_registration_number}`);
|
|
262
|
+
}
|
|
263
|
+
if (c.name_identity)
|
|
264
|
+
lines.push(`- **Navn-identitet**: ${c.name_identity}`);
|
|
265
|
+
if (c.has_pseudo_cvr === true)
|
|
266
|
+
lines.push(`- **Pseudo-CVR**: Ja`);
|
|
267
|
+
if (c.first_fiscal_period_start || c.first_fiscal_period_end) {
|
|
268
|
+
lines.push(`- **Første regnskabsperiode**: ${c.first_fiscal_period_start || "?"} → ${c.first_fiscal_period_end || "?"}`);
|
|
269
|
+
}
|
|
270
|
+
// Helper: render et governance-medlem med navn, funktion, dato, business_address
|
|
271
|
+
const formatMember = (m, opts) => {
|
|
272
|
+
const parts = [m.name];
|
|
273
|
+
if (opts?.showFunction !== false && m.function)
|
|
274
|
+
parts.push(`(${m.function})`);
|
|
275
|
+
const period = [];
|
|
276
|
+
if (m.joined_date)
|
|
277
|
+
period.push(`siden ${m.joined_date}`);
|
|
278
|
+
if (m.left_date)
|
|
279
|
+
period.push(`indtil ${m.left_date}`);
|
|
280
|
+
if (period.length)
|
|
281
|
+
parts.push(period.join(", "));
|
|
282
|
+
if (m.business_address) {
|
|
283
|
+
// FORRETNINGSADRESSE er fri tekst med newlines — sæt på samme linje
|
|
284
|
+
const addr = String(m.business_address).replace(/\s+/g, " ").trim();
|
|
285
|
+
parts.push(`@ ${addr}`);
|
|
286
|
+
}
|
|
287
|
+
if (m.cvr)
|
|
288
|
+
parts.push(`[CVR ${m.cvr}]`);
|
|
289
|
+
if (m.person_id)
|
|
290
|
+
parts.push(`[ID: ${m.person_id}]`);
|
|
291
|
+
return `- ${parts.join(" ")}`;
|
|
292
|
+
};
|
|
293
|
+
// Direktion (Pro+)
|
|
294
|
+
const executives = c.executives;
|
|
295
|
+
if (executives?.length) {
|
|
296
|
+
lines.push("");
|
|
297
|
+
lines.push(`### Direktion (${executives.length})`);
|
|
298
|
+
for (const e of executives)
|
|
299
|
+
lines.push(formatMember(e));
|
|
300
|
+
}
|
|
301
|
+
// Bestyrelse (Pro+)
|
|
302
|
+
const board = c.board_members;
|
|
303
|
+
if (board?.length) {
|
|
304
|
+
lines.push("");
|
|
305
|
+
lines.push(`### Bestyrelse (${board.length})`);
|
|
306
|
+
for (const b of board) {
|
|
307
|
+
const base = formatMember(b);
|
|
308
|
+
// Tilføj election_method i parentes hvis sat
|
|
309
|
+
const withElection = b.election_method ? `${base} [${b.election_method}]` : base;
|
|
310
|
+
lines.push(withElection);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
// Suppleanter (Pro+) — link til primær via alternate_for_enhedsnummer
|
|
314
|
+
const alternates = c.alternates;
|
|
315
|
+
if (alternates?.length) {
|
|
316
|
+
lines.push("");
|
|
317
|
+
lines.push(`### Suppleanter (${alternates.length})`);
|
|
318
|
+
for (const a of alternates) {
|
|
319
|
+
const base = formatMember(a);
|
|
320
|
+
const withLink = a.alternate_for_enhedsnummer
|
|
321
|
+
? `${base} (suppleant for #${a.alternate_for_enhedsnummer})`
|
|
322
|
+
: base;
|
|
323
|
+
lines.push(withLink);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
// Stiftere (Pro+)
|
|
327
|
+
const founders = c.founders;
|
|
328
|
+
if (founders?.length) {
|
|
329
|
+
lines.push("");
|
|
330
|
+
lines.push(`### Stiftere (${founders.length})`);
|
|
331
|
+
for (const f of founders)
|
|
332
|
+
lines.push(formatMember(f, { showFunction: false }));
|
|
333
|
+
}
|
|
334
|
+
// Likvidatorer (Pro+)
|
|
335
|
+
const liquidators = c.liquidators;
|
|
336
|
+
if (liquidators?.length) {
|
|
337
|
+
lines.push("");
|
|
338
|
+
lines.push(`### Likvidatorer (${liquidators.length})`);
|
|
339
|
+
for (const l of liquidators)
|
|
340
|
+
lines.push(formatMember(l, { showFunction: false }));
|
|
341
|
+
}
|
|
342
|
+
// Bæredygtighedsrevisorer (Pro+)
|
|
343
|
+
const sustAuditors = c.sustainability_auditors;
|
|
344
|
+
if (sustAuditors?.length) {
|
|
345
|
+
lines.push("");
|
|
346
|
+
lines.push(`### Bæredygtighedsrevisorer (${sustAuditors.length})`);
|
|
347
|
+
for (const s of sustAuditors)
|
|
348
|
+
lines.push(formatMember(s, { showFunction: false }));
|
|
349
|
+
}
|
|
350
|
+
// Auditor offices (Pro+) — revisorers kontoradresser
|
|
351
|
+
const auditorOffices = c.auditor_offices;
|
|
352
|
+
if (auditorOffices?.length) {
|
|
353
|
+
lines.push("");
|
|
354
|
+
lines.push(`### Revisor-kontorer (${auditorOffices.length})`);
|
|
355
|
+
for (const office of auditorOffices) {
|
|
356
|
+
const addr = office.address;
|
|
357
|
+
const addrParts = [];
|
|
358
|
+
if (addr?.street) {
|
|
359
|
+
addrParts.push(`${addr.street}${addr.house_number_from ? " " + addr.house_number_from : ""}`);
|
|
360
|
+
}
|
|
361
|
+
if (addr?.zipcode || addr?.city) {
|
|
362
|
+
addrParts.push(`${addr.zipcode || ""} ${addr.city || ""}`.trim());
|
|
363
|
+
}
|
|
364
|
+
const cvrPart = office.auditor_cvr ? ` [CVR ${office.auditor_cvr}]` : "";
|
|
365
|
+
lines.push(`- **${office.auditor_name}**${cvrPart}: ${addrParts.join(", ") || "—"}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
// Ejerregister (Pro+) — register_entries med ejerandele
|
|
369
|
+
const registerEntries = c.register_entries;
|
|
370
|
+
if (registerEntries?.length) {
|
|
371
|
+
lines.push("");
|
|
372
|
+
lines.push(`### Ejerregister (${registerEntries.length})`);
|
|
373
|
+
for (const entry of registerEntries) {
|
|
374
|
+
const parts = [];
|
|
375
|
+
if (entry.ownership_percentage != null)
|
|
376
|
+
parts.push(`${entry.ownership_percentage}% ejerandel`);
|
|
377
|
+
if (entry.voting_percentage != null)
|
|
378
|
+
parts.push(`${entry.voting_percentage}% stemmeret`);
|
|
379
|
+
if (entry.share_class)
|
|
380
|
+
parts.push(`klasse ${entry.share_class}`);
|
|
381
|
+
if (entry.notification_date)
|
|
382
|
+
parts.push(`anmeldt ${entry.notification_date}`);
|
|
383
|
+
if (entry.valid_to)
|
|
384
|
+
parts.push(`udløbet ${entry.valid_to}`);
|
|
385
|
+
lines.push(`- ${parts.join(", ") || "—"}`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
// Fuldt ansvarlige deltagere (Pro+)
|
|
389
|
+
const partners = c.unlimited_liability_partners;
|
|
390
|
+
if (partners?.length) {
|
|
391
|
+
lines.push("");
|
|
392
|
+
lines.push(`### Fuldt ansvarlige deltagere (${partners.length})`);
|
|
393
|
+
for (const p of partners)
|
|
394
|
+
lines.push(formatMember(p));
|
|
395
|
+
}
|
|
396
|
+
return lines.join("\n");
|
|
397
|
+
}
|
|
398
|
+
function formatFinancialsMarkdown(data) {
|
|
399
|
+
const financials = data.financials;
|
|
400
|
+
if (!financials?.length)
|
|
401
|
+
return "*Ingen regnskabsdata tilgængelig.*";
|
|
402
|
+
const lines = ["### Regnskaber", ""];
|
|
403
|
+
if (data.years_included)
|
|
404
|
+
lines.push(`*Inkluderede år: ${data.years_included}*`, "");
|
|
405
|
+
// Helper: only push the line if value is non-null. Reduces repetition.
|
|
406
|
+
const pushIf = (out, value, label, fmt = dkk) => {
|
|
407
|
+
if (value != null)
|
|
408
|
+
out.push(`- ${label}: ${fmt(value)}`);
|
|
409
|
+
};
|
|
410
|
+
for (const f of financials) {
|
|
411
|
+
const reportType = f.report_type ?? "";
|
|
412
|
+
const reportLabel = reportType && reportType !== "annual" ? ` [${reportType}]` : "";
|
|
413
|
+
lines.push(`#### ${f.year} (${f.period_start} → ${f.period_end})${reportLabel}`);
|
|
414
|
+
// ── Resultatopgørelse ─────────────────────────────────────────
|
|
415
|
+
pushIf(lines, f.revenue, "Omsætning");
|
|
416
|
+
pushIf(lines, f.cost_of_sales, "Vareforbrug");
|
|
417
|
+
pushIf(lines, f.gross_profit, "Bruttofortjeneste");
|
|
418
|
+
pushIf(lines, f.employee_expenses, "Lønudgifter");
|
|
419
|
+
pushIf(lines, f.other_operating_expenses, "Andre driftsudgifter");
|
|
420
|
+
pushIf(lines, f.average_employees, "Gns. antal ansatte", (v) => Number(v).toLocaleString("da-DK"));
|
|
421
|
+
pushIf(lines, f.operating_profit, "Driftsresultat");
|
|
422
|
+
pushIf(lines, f.ebitda, "EBITDA");
|
|
423
|
+
pushIf(lines, f.depreciation, "Afskrivninger");
|
|
424
|
+
pushIf(lines, f.interest_income, "Finansielle indtægter");
|
|
425
|
+
pushIf(lines, f.interest_expense, "Finansielle udgifter");
|
|
426
|
+
pushIf(lines, f.profit_before_tax, "Resultat før skat");
|
|
427
|
+
pushIf(lines, f.tax_expense, "Skat");
|
|
428
|
+
pushIf(lines, f.net_profit, "Resultat");
|
|
429
|
+
pushIf(lines, f.dividends_paid, "Udbetalt udbytte");
|
|
430
|
+
pushIf(lines, f.proposed_dividend, "Foreslået udbytte");
|
|
431
|
+
// ── Balance ───────────────────────────────────────────────────
|
|
432
|
+
pushIf(lines, f.equity, "Egenkapital");
|
|
433
|
+
pushIf(lines, f.share_capital, "Selskabskapital");
|
|
434
|
+
pushIf(lines, f.retained_earnings, "Overført resultat");
|
|
435
|
+
pushIf(lines, f.total_assets, "Aktiver i alt");
|
|
436
|
+
pushIf(lines, f.fixed_assets, "Anlægsaktiver");
|
|
437
|
+
pushIf(lines, f.intangible_assets, "Immaterielle anlægsaktiver");
|
|
438
|
+
pushIf(lines, f.goodwill, "Goodwill");
|
|
439
|
+
pushIf(lines, f.tangible_assets, "Materielle anlægsaktiver");
|
|
440
|
+
pushIf(lines, f.financial_assets, "Finansielle anlægsaktiver");
|
|
441
|
+
pushIf(lines, f.current_assets, "Omsætningsaktiver");
|
|
442
|
+
pushIf(lines, f.inventories, "Varebeholdninger");
|
|
443
|
+
pushIf(lines, f.trade_receivables, "Tilgodehavender fra salg");
|
|
444
|
+
pushIf(lines, f.cash, "Likvider");
|
|
445
|
+
pushIf(lines, f.total_liabilities, "Forpligtelser i alt");
|
|
446
|
+
pushIf(lines, f.provisions, "Hensættelser");
|
|
447
|
+
pushIf(lines, f.long_term_liabilities, "Langfristet gæld");
|
|
448
|
+
pushIf(lines, f.bank_debt_long, "Langfristet bankgæld");
|
|
449
|
+
pushIf(lines, f.current_liabilities, "Kortfristet gæld");
|
|
450
|
+
pushIf(lines, f.bank_debt_short, "Kortfristet bankgæld");
|
|
451
|
+
// ── Pengestrømme ──────────────────────────────────────────────
|
|
452
|
+
const cashflowFields = [
|
|
453
|
+
["cash_from_operations", "Pengestrøm fra drift"],
|
|
454
|
+
["cash_from_investing", "Pengestrøm fra investering"],
|
|
455
|
+
["cash_from_financing", "Pengestrøm fra finansiering"],
|
|
456
|
+
["free_cash_flow", "Frit cash flow"],
|
|
457
|
+
];
|
|
458
|
+
if (cashflowFields.some(([k]) => f[k] != null)) {
|
|
459
|
+
lines.push("- Pengestrømme:");
|
|
460
|
+
for (const [k, label] of cashflowFields) {
|
|
461
|
+
if (f[k] != null)
|
|
462
|
+
lines.push(` - ${label}: ${dkk(f[k])}`);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
// ── Nøgletal ──────────────────────────────────────────────────
|
|
466
|
+
const ratios = f.ratios;
|
|
467
|
+
if (ratios) {
|
|
468
|
+
const parts = [];
|
|
469
|
+
if (ratios.profit_margin != null)
|
|
470
|
+
parts.push(`Overskudsgrad: ${pct(ratios.profit_margin)}`);
|
|
471
|
+
if (ratios.gross_margin != null)
|
|
472
|
+
parts.push(`Bruttomargin: ${pct(ratios.gross_margin)}`);
|
|
473
|
+
if (ratios.ebitda_margin != null)
|
|
474
|
+
parts.push(`EBITDA-margin: ${pct(ratios.ebitda_margin)}`);
|
|
475
|
+
if (ratios.solvency_ratio != null)
|
|
476
|
+
parts.push(`Soliditet: ${pct(ratios.solvency_ratio)}`);
|
|
477
|
+
if (ratios.current_ratio != null)
|
|
478
|
+
parts.push(`Likviditetsgrad: ${ratios.current_ratio.toFixed(2)}`);
|
|
479
|
+
if (ratios.quick_ratio != null)
|
|
480
|
+
parts.push(`Likv.grad II: ${ratios.quick_ratio.toFixed(2)}`);
|
|
481
|
+
if (ratios.debt_to_equity != null)
|
|
482
|
+
parts.push(`Gæld/egenkapital: ${ratios.debt_to_equity.toFixed(2)}`);
|
|
483
|
+
if (ratios.interest_coverage != null)
|
|
484
|
+
parts.push(`Rentedækning: ${ratios.interest_coverage.toFixed(2)}`);
|
|
485
|
+
if (ratios.return_on_equity != null)
|
|
486
|
+
parts.push(`ROE: ${pct(ratios.return_on_equity)}`);
|
|
487
|
+
if (ratios.return_on_assets != null)
|
|
488
|
+
parts.push(`ROA: ${pct(ratios.return_on_assets)}`);
|
|
489
|
+
if (parts.length)
|
|
490
|
+
lines.push(`- Nøgletal: ${parts.join(", ")}`);
|
|
491
|
+
}
|
|
492
|
+
// ── Vækst (year-over-year) ────────────────────────────────────
|
|
493
|
+
const growth = f.growth;
|
|
494
|
+
if (growth) {
|
|
495
|
+
const gParts = [];
|
|
496
|
+
if (growth.revenue_yoy != null)
|
|
497
|
+
gParts.push(`Omsætning: ${pct(growth.revenue_yoy)}`);
|
|
498
|
+
if (growth.gross_profit_yoy != null)
|
|
499
|
+
gParts.push(`Bruttofortjeneste: ${pct(growth.gross_profit_yoy)}`);
|
|
500
|
+
if (growth.profit_yoy != null)
|
|
501
|
+
gParts.push(`Resultat: ${pct(growth.profit_yoy)}`);
|
|
502
|
+
if (growth.equity_yoy != null)
|
|
503
|
+
gParts.push(`Egenkapital: ${pct(growth.equity_yoy)}`);
|
|
504
|
+
if (growth.total_assets_yoy != null)
|
|
505
|
+
gParts.push(`Aktiver: ${pct(growth.total_assets_yoy)}`);
|
|
506
|
+
if (gParts.length)
|
|
507
|
+
lines.push(`- Vækst (YoY): ${gParts.join(", ")}`);
|
|
508
|
+
}
|
|
509
|
+
// ── Revision ──────────────────────────────────────────────────
|
|
510
|
+
if (f.audit_opinion)
|
|
511
|
+
lines.push(`- Revisionspåtegning: ${f.audit_opinion}`);
|
|
512
|
+
if (f.going_concern_flag)
|
|
513
|
+
lines.push(`- **Going concern-forbehold**: Ja`);
|
|
514
|
+
// ── Link til regnskabsrapport ─────────────────────────────────
|
|
515
|
+
if (f.report_url)
|
|
516
|
+
lines.push(`- Rapport: ${f.report_url}`);
|
|
517
|
+
lines.push("");
|
|
518
|
+
}
|
|
519
|
+
return lines.join("\n");
|
|
520
|
+
}
|
|
521
|
+
/** Cap a list at HISTORY_TRUNCATE_AT items + add a "showing X of Y" footer. */
|
|
522
|
+
const HISTORY_TRUNCATE_AT = 25;
|
|
523
|
+
function pushTruncatedList(lines, items, formatter) {
|
|
524
|
+
const visible = items.slice(0, HISTORY_TRUNCATE_AT);
|
|
525
|
+
for (let i = 0; i < visible.length; i++) {
|
|
526
|
+
lines.push(formatter(visible[i], i));
|
|
527
|
+
}
|
|
528
|
+
if (items.length > HISTORY_TRUNCATE_AT) {
|
|
529
|
+
lines.push(`- *... ${items.length - HISTORY_TRUNCATE_AT} ældre poster udeladt (brug ?include=history på direkte API-kald for fuld liste)*`);
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
function formatHistoryMarkdown(history) {
|
|
533
|
+
const lines = ["### Historik", ""];
|
|
534
|
+
const sections = [
|
|
535
|
+
["names", "Navneændringer"],
|
|
536
|
+
["addresses", "Adresseændringer"],
|
|
537
|
+
["statuses", "Statusændringer"],
|
|
538
|
+
["industries", "Brancheændringer"],
|
|
539
|
+
["employees", "Ansatændringer"],
|
|
540
|
+
["company_forms", "Selskabsformændringer"],
|
|
541
|
+
["secondary_names", "Binavneændringer"],
|
|
542
|
+
];
|
|
543
|
+
for (const [key, title] of sections) {
|
|
544
|
+
const items = history[key];
|
|
545
|
+
if (!items?.length)
|
|
546
|
+
continue;
|
|
547
|
+
lines.push(`#### ${title} (${items.length})`);
|
|
548
|
+
pushTruncatedList(lines, items, (item) => {
|
|
549
|
+
const period = `${item.valid_from || "?"}${item.valid_to ? ` → ${item.valid_to}` : " → nu"}`;
|
|
550
|
+
if (key === "names")
|
|
551
|
+
return `- ${item.name} (${period})`;
|
|
552
|
+
if (key === "addresses") {
|
|
553
|
+
return `- ${item.address}, ${item.zipcode} ${item.city}${item.municipality_name ? ` (${item.municipality_name})` : ""} (${period})`;
|
|
554
|
+
}
|
|
555
|
+
if (key === "statuses")
|
|
556
|
+
return `- ${item.status} (${period})`;
|
|
557
|
+
if (key === "industries")
|
|
558
|
+
return `- ${item.text} (${item.code}) (${period})`;
|
|
559
|
+
if (key === "employees")
|
|
560
|
+
return `- ${item.employees} (${period})`;
|
|
561
|
+
if (key === "company_forms")
|
|
562
|
+
return `- ${item.form} (${period})`;
|
|
563
|
+
if (key === "secondary_names")
|
|
564
|
+
return `- ${item.name} (${period})`;
|
|
565
|
+
return `- ${JSON.stringify(item)}`;
|
|
566
|
+
});
|
|
567
|
+
lines.push("");
|
|
568
|
+
}
|
|
569
|
+
// Phase 5 history arrays — only present when API returned them (Standard+/Pro+)
|
|
570
|
+
// Quarterly employment (Standard+)
|
|
571
|
+
const quarterly = history.quarterly_employment;
|
|
572
|
+
if (quarterly?.length) {
|
|
573
|
+
lines.push(`#### Kvartalvis beskæftigelse (${quarterly.length})`);
|
|
574
|
+
pushTruncatedList(lines, quarterly, (q) => {
|
|
575
|
+
const label = q.employees_label || (q.employees != null ? `${q.employees} ansatte` : "—");
|
|
576
|
+
const fte = q.fte_label || (q.fte != null ? `${q.fte} årsværk` : null);
|
|
577
|
+
return `- ${q.year} Q${q.quarter}: ${label}${fte ? `, ${fte}` : ""}`;
|
|
578
|
+
});
|
|
579
|
+
lines.push("");
|
|
580
|
+
}
|
|
581
|
+
// Monthly employment (Standard+)
|
|
582
|
+
const monthly = history.monthly_employment;
|
|
583
|
+
if (monthly?.length) {
|
|
584
|
+
lines.push(`#### Månedlig beskæftigelse (${monthly.length})`);
|
|
585
|
+
pushTruncatedList(lines, monthly, (m) => {
|
|
586
|
+
const label = m.employees_label || (m.employees != null ? `${m.employees} ansatte` : "—");
|
|
587
|
+
const fte = m.fte_label || (m.fte != null ? `${m.fte} årsværk` : null);
|
|
588
|
+
return `- ${m.year}-${String(m.month).padStart(2, "0")}: ${label}${fte ? `, ${fte}` : ""}`;
|
|
589
|
+
});
|
|
590
|
+
lines.push("");
|
|
591
|
+
}
|
|
592
|
+
// Email history (Pro+)
|
|
593
|
+
const emails = history.emails;
|
|
594
|
+
if (emails?.length) {
|
|
595
|
+
lines.push(`#### Email-historik (${emails.length})`);
|
|
596
|
+
pushTruncatedList(lines, emails, (e) => {
|
|
597
|
+
const period = `${e.valid_from || "?"}${e.valid_to ? ` → ${e.valid_to}` : " → nu"}`;
|
|
598
|
+
const adProtected = e.ad_protected ? " [reklamebeskyttet]" : "";
|
|
599
|
+
return `- ${e.value} (${period})${adProtected}`;
|
|
600
|
+
});
|
|
601
|
+
lines.push("");
|
|
602
|
+
}
|
|
603
|
+
// Phone history (Pro+)
|
|
604
|
+
const phones = history.phones;
|
|
605
|
+
if (phones?.length) {
|
|
606
|
+
lines.push(`#### Telefon-historik (${phones.length})`);
|
|
607
|
+
pushTruncatedList(lines, phones, (p) => {
|
|
608
|
+
const period = `${p.valid_from || "?"}${p.valid_to ? ` → ${p.valid_to}` : " → nu"}`;
|
|
609
|
+
const adProtected = p.ad_protected ? " [reklamebeskyttet]" : "";
|
|
610
|
+
return `- ${p.value} (${period})${adProtected}`;
|
|
611
|
+
});
|
|
612
|
+
lines.push("");
|
|
613
|
+
}
|
|
614
|
+
// Website history (Pro+)
|
|
615
|
+
const websites = history.websites;
|
|
616
|
+
if (websites?.length) {
|
|
617
|
+
lines.push(`#### Webside-historik (${websites.length})`);
|
|
618
|
+
pushTruncatedList(lines, websites, (w) => {
|
|
619
|
+
const period = `${w.valid_from || "?"}${w.valid_to ? ` → ${w.valid_to}` : " → nu"}`;
|
|
620
|
+
return `- ${w.value} (${period})`;
|
|
621
|
+
});
|
|
622
|
+
lines.push("");
|
|
623
|
+
}
|
|
624
|
+
// Registration numbers (Pro+) — historic A/S- and selskabsformnumre
|
|
625
|
+
const regNumbers = history.registration_numbers;
|
|
626
|
+
if (regNumbers?.length) {
|
|
627
|
+
lines.push(`#### Historiske registreringsnumre (${regNumbers.length})`);
|
|
628
|
+
pushTruncatedList(lines, regNumbers, (r) => {
|
|
629
|
+
const period = `${r.valid_from || "?"}${r.valid_to ? ` → ${r.valid_to}` : " → nu"}`;
|
|
630
|
+
return `- ${r.number} (${period})`;
|
|
631
|
+
});
|
|
632
|
+
lines.push("");
|
|
633
|
+
}
|
|
634
|
+
// Register entries (Pro+) — ejerregister-historik
|
|
635
|
+
const registerHistory = history.register_entries;
|
|
636
|
+
if (registerHistory?.length) {
|
|
637
|
+
lines.push(`#### Ejerregister-historik (${registerHistory.length})`);
|
|
638
|
+
pushTruncatedList(lines, registerHistory, (e) => {
|
|
639
|
+
const period = `${e.valid_from || "?"}${e.valid_to ? ` → ${e.valid_to}` : " → nu"}`;
|
|
640
|
+
const parts = [];
|
|
641
|
+
if (e.ownership_percentage != null)
|
|
642
|
+
parts.push(`${e.ownership_percentage}% ejerandel`);
|
|
643
|
+
if (e.voting_percentage != null)
|
|
644
|
+
parts.push(`${e.voting_percentage}% stemmer`);
|
|
645
|
+
if (e.share_class)
|
|
646
|
+
parts.push(`klasse ${e.share_class}`);
|
|
647
|
+
return `- ${parts.join(", ") || "—"} (${period})`;
|
|
648
|
+
});
|
|
649
|
+
lines.push("");
|
|
650
|
+
}
|
|
651
|
+
return lines.join("\n");
|
|
652
|
+
}
|
|
653
|
+
function formatEventsMarkdown(data) {
|
|
654
|
+
const lines = ["### Hændelser", ""];
|
|
655
|
+
const lifecycle = data.lifecycle;
|
|
656
|
+
if (lifecycle?.length) {
|
|
657
|
+
lines.push("#### Livscyklus");
|
|
658
|
+
for (const lc of lifecycle) {
|
|
659
|
+
lines.push(`- ${lc.valid_from || "?"}${lc.valid_to ? ` → ${lc.valid_to}` : " → nu"}`);
|
|
660
|
+
}
|
|
661
|
+
lines.push("");
|
|
662
|
+
}
|
|
663
|
+
const mergers = data.mergers;
|
|
664
|
+
if (mergers?.length) {
|
|
665
|
+
lines.push("#### Fusioner og spaltninger");
|
|
666
|
+
for (const m of mergers) {
|
|
667
|
+
lines.push(`- **${m.type}** (${m.effective_date})`);
|
|
668
|
+
}
|
|
669
|
+
lines.push("");
|
|
670
|
+
}
|
|
671
|
+
const events = data.events;
|
|
672
|
+
if (events?.length) {
|
|
673
|
+
lines.push("#### Tidslinje");
|
|
674
|
+
for (const e of events) {
|
|
675
|
+
// CompanyEvent emits `occurred_at` (not date/effective_date).
|
|
676
|
+
lines.push(`- ${e.occurred_at}: ${e.type}${e.description ? ` — ${e.description}` : ""}`);
|
|
677
|
+
}
|
|
678
|
+
lines.push("");
|
|
679
|
+
}
|
|
680
|
+
return lines.join("\n");
|
|
681
|
+
}
|
|
682
|
+
function formatProductionUnitsMarkdown(data) {
|
|
683
|
+
const units = data.production_units;
|
|
684
|
+
if (!units?.length)
|
|
685
|
+
return "*Ingen produktionsenheder.*";
|
|
686
|
+
const lines = [`### Produktionsenheder (${data.production_unit_count || units.length})`, ""];
|
|
687
|
+
for (const u of units) {
|
|
688
|
+
const parts = [`**${u.name}** (P-nr. ${u.p_number})`];
|
|
689
|
+
if (u.address)
|
|
690
|
+
parts.push(`${u.address}, ${u.zipcode} ${u.city}`);
|
|
691
|
+
if (u.industry_text)
|
|
692
|
+
parts.push(`${u.industry_text} (${u.industry_code})`);
|
|
693
|
+
if (u.employees)
|
|
694
|
+
parts.push(`${u.employees} ansatte`);
|
|
695
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
696
|
+
}
|
|
697
|
+
return lines.join("\n");
|
|
698
|
+
}
|
|
699
|
+
function formatRelationsMarkdown(relations) {
|
|
700
|
+
const lines = ["### Koncernrelationer", ""];
|
|
701
|
+
const formatRelation = (r) => {
|
|
702
|
+
const parts = [`**${r.name ?? "(ukendt)"}** (CVR ${r.cvr})`];
|
|
703
|
+
if (r.ownership_share != null)
|
|
704
|
+
parts.push(`ejerandel: ${r.ownership_share}%`);
|
|
705
|
+
if (r.voting_share != null)
|
|
706
|
+
parts.push(`stemmer: ${r.voting_share}%`);
|
|
707
|
+
if (r.control_share != null)
|
|
708
|
+
parts.push(`kontrol: ${r.control_share}%`);
|
|
709
|
+
if (r.status)
|
|
710
|
+
parts.push(`status: ${r.status}`);
|
|
711
|
+
if (r.unresolved)
|
|
712
|
+
parts.push(`(uafklaret)`);
|
|
713
|
+
return `- ${parts.join(" — ")}`;
|
|
714
|
+
};
|
|
715
|
+
const parents = relations.parents;
|
|
716
|
+
if (parents?.length) {
|
|
717
|
+
lines.push("#### Moderselskaber");
|
|
718
|
+
for (const p of parents)
|
|
719
|
+
lines.push(formatRelation(p));
|
|
720
|
+
lines.push("");
|
|
721
|
+
}
|
|
722
|
+
const subsidiaries = relations.subsidiaries;
|
|
723
|
+
if (subsidiaries?.length) {
|
|
724
|
+
lines.push("#### Datterselskaber");
|
|
725
|
+
for (const s of subsidiaries)
|
|
726
|
+
lines.push(formatRelation(s));
|
|
727
|
+
lines.push("");
|
|
728
|
+
}
|
|
729
|
+
return lines.join("\n");
|
|
730
|
+
}
|
|
731
|
+
// ── Server ───────────────────────────────────────────────────────
|
|
732
|
+
export const SERVER_NAME = "firmaapi-mcp-server";
|
|
733
|
+
export const SERVER_INSTRUCTIONS = "FirmaAPI giver adgang til danske virksomhedsdata fra CVR-registret: stamdata, regnskaber, ejere, ledelse, personer og produktionsenheder. " +
|
|
734
|
+
"Start med firmaapi_search_companies, hvis du kun kender et navn, og firmaapi_lookup_company, når du har et CVR-nummer. " +
|
|
735
|
+
"Hvert værktøj oplyser sit API-forbrug; kaldene tæller i brugerens månedlige kvote. " +
|
|
736
|
+
"Oplysningerne er registerdata og beregnede nøgletal, ikke vurderinger eller anbefalinger.";
|
|
737
|
+
/**
|
|
738
|
+
* Builds a server with every FirmaAPI tool. One instance serves one stdio
|
|
739
|
+
* connection or one HTTP request, so everything a tool needs is created in
|
|
740
|
+
* here and nothing is shared between callers. The body is not indented, so
|
|
741
|
+
* the tools read the same as before they were wrapped.
|
|
742
|
+
*/
|
|
743
|
+
export function createFirmaApiServer(options = {}) {
|
|
744
|
+
const api = options.api ?? defaultApiClient;
|
|
745
|
+
const apiRequest = (path, params) => api.request(path, params);
|
|
746
|
+
const apiPost = (path, body) => api.post(path, body);
|
|
747
|
+
const server = new McpServer({ name: SERVER_NAME, version: CLIENT_VERSION }, { instructions: SERVER_INSTRUCTIONS });
|
|
748
|
+
options.skills?.attach(server);
|
|
749
|
+
// Append the API cost ("API-forbrug: ...") to every tool description, including
|
|
750
|
+
// the factual tools registered from factual-tools.ts.
|
|
751
|
+
const registerToolWithoutCost = server.registerTool.bind(server);
|
|
752
|
+
server.registerTool = ((name, config, callback) => registerToolWithoutCost(name, { ...config, description: withApiCost(name, config.description) }, callback));
|
|
753
|
+
// ── Tool 1: Company lookup ───────────────────────────────────────
|
|
754
|
+
server.registerTool("firmaapi_lookup_company", {
|
|
755
|
+
title: "Sl\u00e5 virksomhed op via CVR",
|
|
756
|
+
description: `Hent detaljerede oplysninger om en dansk virksomhed via CVR-nummer.
|
|
757
|
+
|
|
758
|
+
Returnerer altid: Stamdata (navn, adresse, branche, status, stiftet, ansatte),
|
|
759
|
+
formål, tegningsregel, kapital, kontaktinfo (telefon, email, website),
|
|
760
|
+
børsnoteret-flag, revision-fravalgt-flag.
|
|
761
|
+
|
|
762
|
+
Valgfrie ekstrablokke (include):
|
|
763
|
+
- **finance** (Standard+): Regnskabsdata (omsætning, resultat, egenkapital,
|
|
764
|
+
nøgletal, vækst). Pro+ giver også cash flow og audit opinion.
|
|
765
|
+
- **history** (Basis+): Historiske ændringer (navne, adresser, status,
|
|
766
|
+
branche, ansatte). Standard+ får også beskæftigelseshistorik.
|
|
767
|
+
Basis+ får ejerregister; Pro+ får også email/phone/website-historik.
|
|
768
|
+
- **events** (Standard+): Livscyklushændelser (stiftelse, fusioner, konkurser)
|
|
769
|
+
- **production_units** (Standard+): Produktionsenheder med P-numre. Pro+
|
|
770
|
+
giver fuld adresse, branche og ansatte pr. P-enhed.
|
|
771
|
+
- **relations** (Pro+): Koncernrelationer (moderselskab, datterselskaber).
|
|
772
|
+
|
|
773
|
+
Eksempler:
|
|
774
|
+
- "Sl\u00e5 CVR 24256790 op" \u2192 cvr="24256790"
|
|
775
|
+
- "Vis regnskab for 10150817" \u2192 cvr="10150817", include="finance"
|
|
776
|
+
- "Fuld profil" \u2192 cvr="34824770", include="finance,history,events,production_units,relations"
|
|
777
|
+
|
|
778
|
+
${PLAN.any} Inkluder-blokke gates pr. plan (se ovenfor).`,
|
|
779
|
+
inputSchema: {
|
|
780
|
+
cvr: z.string().regex(/^\d{8}$/, "CVR skal v\u00e6re pr\u00e6cis 8 cifre").describe("8-cifret CVR-nummer"),
|
|
781
|
+
include: z.string().optional().describe("Kommasepareret: finance, history, events, production_units, relations"),
|
|
782
|
+
format: FORMAT_SCHEMA,
|
|
783
|
+
},
|
|
784
|
+
annotations: {
|
|
785
|
+
readOnlyHint: true,
|
|
786
|
+
destructiveHint: false,
|
|
787
|
+
idempotentHint: true,
|
|
788
|
+
openWorldHint: true,
|
|
789
|
+
},
|
|
790
|
+
}, async ({ cvr, include, format }) => {
|
|
791
|
+
try {
|
|
792
|
+
const data = await apiRequest(`/company/${cvr}`, {
|
|
793
|
+
include: include || undefined,
|
|
794
|
+
});
|
|
795
|
+
if (!data || typeof data !== "object" || !data.name) {
|
|
796
|
+
return { content: [{ type: "text", text: `Fejl: API returnerede ugyldige data for CVR ${cvr}. Prøv igen.` }], isError: true };
|
|
797
|
+
}
|
|
798
|
+
if (format === "json")
|
|
799
|
+
return jsonText(data);
|
|
800
|
+
const sections = [formatCompanyMarkdown(data)];
|
|
801
|
+
// Include-blokke
|
|
802
|
+
if (data.financials)
|
|
803
|
+
sections.push("", formatFinancialsMarkdown(data));
|
|
804
|
+
if (data.history)
|
|
805
|
+
sections.push("", formatHistoryMarkdown(data.history));
|
|
806
|
+
if (data.events || data.lifecycle || data.mergers)
|
|
807
|
+
sections.push("", formatEventsMarkdown(data));
|
|
808
|
+
if (data.production_units)
|
|
809
|
+
sections.push("", formatProductionUnitsMarkdown(data));
|
|
810
|
+
if (data.relations)
|
|
811
|
+
sections.push("", formatRelationsMarkdown(data.relations));
|
|
812
|
+
return { content: [{ type: "text", text: truncate(sections.join("\n")) }] };
|
|
813
|
+
}
|
|
814
|
+
catch (error) {
|
|
815
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
816
|
+
}
|
|
817
|
+
});
|
|
818
|
+
// ── Tool 2: Search companies ─────────────────────────────────────
|
|
819
|
+
server.registerTool("firmaapi_search_companies", {
|
|
820
|
+
title: "S\u00f8g virksomheder p\u00e5 navn",
|
|
821
|
+
description: `Hurtig navnesøgning i danske virksomheder via fuzzy matching på selskabsnavn
|
|
822
|
+
og binavne. Resultater rankes efter match-score (eksakt > prefix > fuzzy)
|
|
823
|
+
og dernæst alfabetisk for stabilt output.
|
|
824
|
+
|
|
825
|
+
Til avancerede filtreringer (branche, ansatte, omsætning, by, status osv.),
|
|
826
|
+
brug firmaapi_advanced_search i stedet.
|
|
827
|
+
|
|
828
|
+
Eksempler:
|
|
829
|
+
- "Find Mærsk" → query="Mærsk"
|
|
830
|
+
- "Søg efter Novo" → query="Novo"
|
|
831
|
+
- "Pizzarestauranter" → query="pizza"
|
|
832
|
+
|
|
833
|
+
${PLAN.any}`,
|
|
834
|
+
inputSchema: {
|
|
835
|
+
query: z.string().min(2, "S\u00f8gestreng skal v\u00e6re mindst 2 tegn").describe("Virksomhedsnavn eller n\u00f8gleord"),
|
|
836
|
+
limit: z.number().int().min(1).max(50).default(10).describe("Maks antal resultater (1-50)"),
|
|
837
|
+
format: FORMAT_SCHEMA,
|
|
838
|
+
},
|
|
839
|
+
annotations: {
|
|
840
|
+
readOnlyHint: true,
|
|
841
|
+
destructiveHint: false,
|
|
842
|
+
idempotentHint: true,
|
|
843
|
+
openWorldHint: true,
|
|
844
|
+
},
|
|
845
|
+
}, async ({ query, limit, format }) => {
|
|
846
|
+
try {
|
|
847
|
+
const data = await apiRequest(`/company/search`, { q: query, limit });
|
|
848
|
+
if (format === "json")
|
|
849
|
+
return jsonText(data);
|
|
850
|
+
const results = (data.results || data.companies || []);
|
|
851
|
+
if (!results.length) {
|
|
852
|
+
return { content: [{ type: "text", text: `Ingen virksomheder fundet for "${query}".` }] };
|
|
853
|
+
}
|
|
854
|
+
const lines = [`# S\u00f8geresultater: "${query}"`, `Fundet ${data.total || results.length} virksomheder`, ""];
|
|
855
|
+
for (const c of results) {
|
|
856
|
+
lines.push(`- **${c.name}** (CVR ${c.cvr}) \u2014 ${c.status}, ${c.city || ""}${c.industry_text ? `, ${c.industry_text}` : ""}`);
|
|
857
|
+
}
|
|
858
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
859
|
+
}
|
|
860
|
+
catch (error) {
|
|
861
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
862
|
+
}
|
|
863
|
+
});
|
|
864
|
+
// ── Tool 3: Advanced search ──────────────────────────────────────
|
|
865
|
+
server.registerTool("firmaapi_advanced_search", {
|
|
866
|
+
title: "Avanceret virksomhedss\u00f8gning",
|
|
867
|
+
description: `S\u00f8g danske virksomheder med 30+ filtre. Perfekt til leadgenerering, markedsanalyse og prospecting.
|
|
868
|
+
|
|
869
|
+
Vigtige filtre:
|
|
870
|
+
- status: Case-insensitiv. V\u00e6rdier: "Aktiv", "Oph\u00f8rt", "Opløst efter konkurs", "Tvangsopløst", "Under konkurs", "Slettet" m.fl.
|
|
871
|
+
- employees: "5+" (minimum), "10-49" (interval), "42" (pr\u00e6cis), eller CVR-kode "ANTAL_10_19"
|
|
872
|
+
- industry: Branchekode som prefix (fx "62" finder alle 62xxxx IT-brancher) eller fritekst
|
|
873
|
+
- ad_protected: "false" = ikke reklamebeskyttet, "true" = reklamebeskyttet. Ikke dokumentation for samtykke
|
|
874
|
+
- has_phone/has_email/has_website: Filtrer p\u00e5 kontaktoplysninger
|
|
875
|
+
|
|
876
|
+
Eksempler:
|
|
877
|
+
- "Aktive IT-firmaer med telefon" \u2192 q="*", industry="62", status="Aktiv", has_phone=true
|
|
878
|
+
- "Virksomheder med 50+ ansatte og 10M+ oms\u00e6tning" \u2192 q="*", employees="50+", revenue_min=10000000
|
|
879
|
+
- "Ikke-reklamebeskyttede i Aarhus" \u2192 q="*", city="Aarhus", ad_protected="false", has_phone=true
|
|
880
|
+
- "Nye ApS'er i 2024" \u2192 q="*", company_type="ApS", founded_after="2024-01-01"
|
|
881
|
+
- "Byggevirksomheder i K\u00f8benhavn med hjemmeside" \u2192 q="*", city="K\u00f8benhavn", industry="41", has_website=true`,
|
|
882
|
+
inputSchema: {
|
|
883
|
+
q: z.string().optional().describe("Navnes\u00f8gning (* for alle, eller delvis match fx 'Novo')"),
|
|
884
|
+
city: z.string().optional().describe("Bynavn (case-insensitiv, fx 'aarhus' eller 'Aarhus')"),
|
|
885
|
+
zipcode: z.string().optional().describe("Postnummer (eksakt, fx '2100')"),
|
|
886
|
+
municipality: z.string().optional().describe("Kommunenavn eller -kode (fx 'K\u00f8benhavn', '101' eller '0101')"),
|
|
887
|
+
municipality_list: z.string().optional().describe("Komma-adskilt liste af kommuner (OR-match), fx 'K\u00f8benhavn,Aarhus,Odense'"),
|
|
888
|
+
region: z.string().optional().describe("Dansk region (5 regioner): 'Hovedstaden', 'Sj\u00e6lland', 'Syddanmark', 'Midtjylland', 'Nordjylland'"),
|
|
889
|
+
region_list: z.string().optional().describe("Komma-adskilt liste af regioner (OR-match)"),
|
|
890
|
+
industry: z.string().optional().describe("Branchekode som prefix (fx '62' for IT) eller fritekst (fx 'restaurant')"),
|
|
891
|
+
industry_list: z.string().optional().describe("Komma-adskilt liste af branchekode-prefixer (OR-match), fx '62,70,73'"),
|
|
892
|
+
industry_exclude: z.string().optional().describe("Komma-adskilt liste af branchekoder der ekskluderes (prefix-match)"),
|
|
893
|
+
company_type: z.string().optional().describe("Selskabsform. Forkortelser (ApS, A/S, IVS, I/S, K/S, P/S, SMBA, AMBA, FMBA, ENK, PMV) matcher den præcise CVR-form; andre værdier matches delvist på den lange betegnelse (fx 'Enkeltmandsvirksomhed')"),
|
|
894
|
+
company_type_list: z.string().optional().describe("Komma-adskilt liste af selskabsformer (OR-match), fx 'ApS,A/S'. Hver værdi tolkes som company_type"),
|
|
895
|
+
owner_kind: z.string().optional().describe("Komma-adskilt liste af ejertyper for de aktive, direkte legale ejere (OR-match): person, holding, fund, company, foreign (uden dansk CVR). Fx 'holding,fund'"),
|
|
896
|
+
status: z.string().optional().describe("Case-insensitiv: 'Aktiv', 'Oph\u00f8rt', 'Under konkurs' m.fl."),
|
|
897
|
+
employees: z.string().optional().describe("'5+' (minimum), '10-49' (interval), '42' (pr\u00e6cis), eller 'ANTAL_10_19'"),
|
|
898
|
+
revenue_min: z.number().optional().describe("Min. oms\u00e6tning i DKK (fx 5000000 for 5M+)"),
|
|
899
|
+
revenue_max: z.number().optional().describe("Maks. oms\u00e6tning i DKK"),
|
|
900
|
+
capital_min: z.number().optional().describe("Min. selskabskapital i DKK"),
|
|
901
|
+
capital_max: z.number().optional().describe("Maks. selskabskapital i DKK"),
|
|
902
|
+
founded_after: z.string().optional().describe("Stiftet efter dato (YYYY-MM-DD)"),
|
|
903
|
+
founded_before: z.string().optional().describe("Stiftet f\u00f8r dato (YYYY-MM-DD)"),
|
|
904
|
+
founded_year: z.string().optional().describe("Pr\u00e6cist stiftelses\u00e5r (YYYY) \u2014 genvej"),
|
|
905
|
+
founded_year_min: z.string().optional().describe("Tidligste stiftelses\u00e5r (YYYY)"),
|
|
906
|
+
founded_year_max: z.string().optional().describe("Seneste stiftelses\u00e5r (YYYY)"),
|
|
907
|
+
dissolved_after: z.string().optional().describe("Opl\u00f8st efter dato (YYYY-MM-DD)"),
|
|
908
|
+
dissolved_before: z.string().optional().describe("Opl\u00f8st f\u00f8r dato (YYYY-MM-DD)"),
|
|
909
|
+
dissolved_year: z.string().optional().describe("Pr\u00e6cist opl\u00f8sningsr\u00e5r (YYYY)"),
|
|
910
|
+
dissolved_year_min: z.string().optional().describe("Tidligste opl\u00f8sningsr\u00e5r (YYYY)"),
|
|
911
|
+
dissolved_year_max: z.string().optional().describe("Seneste opl\u00f8sningsr\u00e5r (YYYY)"),
|
|
912
|
+
is_dissolved: z.boolean().optional().describe("true = kun opl\u00f8ste virksomheder, false = kun stadig aktive"),
|
|
913
|
+
age_min: z.number().int().nonnegative().optional().describe("Minimum alder i fulde \u00e5r (alder = nu - founded)"),
|
|
914
|
+
age_max: z.number().int().nonnegative().optional().describe("Maks alder i fulde \u00e5r"),
|
|
915
|
+
last_report_year_min: z.string().optional().describe("Tidligste \u00e5r for seneste regnskab (YYYY)"),
|
|
916
|
+
last_report_year_max: z.string().optional().describe("Seneste \u00e5r for seneste regnskab (YYYY)"),
|
|
917
|
+
has_financials: z.boolean().optional().describe("Kun virksomheder med regnskabsdata"),
|
|
918
|
+
ad_protected: z.string().optional().describe("'false' = ikke reklamebeskyttet, 'true' = reklamebeskyttet; ikke et samtykke"),
|
|
919
|
+
has_phone: z.boolean().optional().describe("Kun virksomheder med telefonnummer"),
|
|
920
|
+
has_email: z.boolean().optional().describe("Kun virksomheder med email"),
|
|
921
|
+
has_website: z.boolean().optional().describe("Kun virksomheder med hjemmeside"),
|
|
922
|
+
limit: z.number().int().min(1).max(100).default(20).describe("Maks resultater (1-100, default 20)"),
|
|
923
|
+
offset: z.number().int().min(0).default(0).describe("Pagination offset (ignoreres hvis cursor er sat)"),
|
|
924
|
+
cursor: z.string().optional().describe("Opaque cursor fra forrige svars next_cursor. Tilrådes for stabile resultater ved store datas\u00e6t \u2014 erstatter offset."),
|
|
925
|
+
format: FORMAT_SCHEMA,
|
|
926
|
+
fields: FIELDS_SCHEMA,
|
|
927
|
+
verbose: VERBOSE_SCHEMA,
|
|
928
|
+
},
|
|
929
|
+
annotations: {
|
|
930
|
+
readOnlyHint: true,
|
|
931
|
+
destructiveHint: false,
|
|
932
|
+
idempotentHint: true,
|
|
933
|
+
openWorldHint: true,
|
|
934
|
+
},
|
|
935
|
+
}, async (params) => {
|
|
936
|
+
try {
|
|
937
|
+
const { format, fields, verbose, ...apiParams } = params;
|
|
938
|
+
const data = await apiRequest(`/search/advanced`, {
|
|
939
|
+
...apiParams,
|
|
940
|
+
include_total: true,
|
|
941
|
+
});
|
|
942
|
+
const rawResults = (data.results || []);
|
|
943
|
+
if (format === "json") {
|
|
944
|
+
return jsonText({ ...data, results: selectListFields(rawResults, fields, verbose) });
|
|
945
|
+
}
|
|
946
|
+
const results = rawResults;
|
|
947
|
+
const totalRaw = data.total;
|
|
948
|
+
const totalKnown = typeof totalRaw === "number";
|
|
949
|
+
const total = totalKnown ? totalRaw : results.length;
|
|
950
|
+
const offset = params.offset ?? 0;
|
|
951
|
+
const usingCursorEarly = typeof params.cursor === "string" && params.cursor !== "";
|
|
952
|
+
const positionLabel = usingCursorEarly ? "via cursor" : `offset ${offset}`;
|
|
953
|
+
if (!results.length) {
|
|
954
|
+
let text;
|
|
955
|
+
if (totalKnown && total === 0) {
|
|
956
|
+
text = "Ingen virksomheder matchede dine filtre.";
|
|
957
|
+
}
|
|
958
|
+
else if (usingCursorEarly) {
|
|
959
|
+
text = "Ingen flere virksomheder efter denne cursor.";
|
|
960
|
+
}
|
|
961
|
+
else if (totalKnown) {
|
|
962
|
+
text = `Ingen virksomheder p\u00e5 offset ${offset} (total: ${total}). Pr\u00f8v et lavere offset.`;
|
|
963
|
+
}
|
|
964
|
+
else {
|
|
965
|
+
text = `Ingen virksomheder p\u00e5 offset ${offset}. Pr\u00f8v et lavere offset.`;
|
|
966
|
+
}
|
|
967
|
+
return { content: [{ type: "text", text }] };
|
|
968
|
+
}
|
|
969
|
+
const header = totalKnown
|
|
970
|
+
? total === results.length && offset === 0 && !usingCursorEarly
|
|
971
|
+
? `Fundet ${total} virksomheder`
|
|
972
|
+
: `Fundet ${total} virksomheder (viser ${results.length}, ${positionLabel})`
|
|
973
|
+
: `Viser ${results.length} virksomheder (${positionLabel})`;
|
|
974
|
+
const lines = [`# Avanceret s\u00f8gning`, header, ""];
|
|
975
|
+
const customFields = !verbose && fields && fields.length > 0;
|
|
976
|
+
for (const c of results) {
|
|
977
|
+
if (customFields) {
|
|
978
|
+
lines.push(formatPickedRow(c, fields));
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
const parts = [`**${c.name}** (CVR ${c.cvr})`];
|
|
982
|
+
if (c.city)
|
|
983
|
+
parts.push(c.city);
|
|
984
|
+
if (verbose && c.industry_text) {
|
|
985
|
+
parts.push(c.industry_text);
|
|
986
|
+
}
|
|
987
|
+
else if (c.industry_code) {
|
|
988
|
+
parts.push(c.industry_code);
|
|
989
|
+
}
|
|
990
|
+
if (c.employees)
|
|
991
|
+
parts.push(`${c.employees} ansatte`);
|
|
992
|
+
lines.push(`- ${parts.join(" \u2014 ")}`);
|
|
993
|
+
}
|
|
994
|
+
const usingCursor = usingCursorEarly;
|
|
995
|
+
const hasMore = usingCursor
|
|
996
|
+
? Boolean(data.has_more)
|
|
997
|
+
: (totalKnown ? total > offset + results.length : Boolean(data.has_more));
|
|
998
|
+
if (hasMore) {
|
|
999
|
+
const nextCursor = data.next_cursor;
|
|
1000
|
+
if (typeof nextCursor === "string" && nextCursor.length > 0) {
|
|
1001
|
+
// Prefer cursor-based pagination — stable under concurrent updates
|
|
1002
|
+
// and avoids the linear cost of large offsets.
|
|
1003
|
+
lines.push("", `*Flere resultater tilg\u00e6ngelige \u2014 brug cursor=${nextCursor}*`);
|
|
1004
|
+
}
|
|
1005
|
+
else if (!usingCursor) {
|
|
1006
|
+
// Only fall back to offset if the caller wasn't already using a cursor.
|
|
1007
|
+
// In cursor mode the server's offset is 0, so suggesting offset=N
|
|
1008
|
+
// would point into the wrong slice of the result set.
|
|
1009
|
+
lines.push("", `*Flere resultater tilg\u00e6ngelige \u2014 brug offset=${offset + results.length}*`);
|
|
1010
|
+
}
|
|
1011
|
+
else {
|
|
1012
|
+
lines.push("", "*Flere resultater tilg\u00e6ngelige, men API'et returnerede ingen next_cursor.*");
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1016
|
+
}
|
|
1017
|
+
catch (error) {
|
|
1018
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1019
|
+
}
|
|
1020
|
+
});
|
|
1021
|
+
// ── Tool 4: Person lookup ────────────────────────────────────────
|
|
1022
|
+
server.registerTool("firmaapi_get_person", {
|
|
1023
|
+
title: "Hent personprofil",
|
|
1024
|
+
description: `Hent en personprofil med alle virksomhedstilknytninger via UUID.
|
|
1025
|
+
|
|
1026
|
+
Hvor finder jeg person_id?
|
|
1027
|
+
Kald firmaapi_lookup_company først og find \`person_id\` på \`executives[]\`,
|
|
1028
|
+
\`board_members[]\`, \`auditors[]\` eller \`person_affiliations[]\`.
|
|
1029
|
+
Legacy-feltet \`owners[]\` kan også indeholde \`person_id\`, men bør ikke være
|
|
1030
|
+
primær kilde i nye integrationer.
|
|
1031
|
+
Eksempel UUID-format: "a1b2c3d4-e5f6-7890-abcd-ef1234567890".
|
|
1032
|
+
|
|
1033
|
+
Args:
|
|
1034
|
+
- id (string): Person UUID
|
|
1035
|
+
- format (markdown|json)
|
|
1036
|
+
|
|
1037
|
+
Returnerer: Navn, aktive/historiske virksomhedstilknytninger, roller, perioder,
|
|
1038
|
+
ejerandele/stemmeret, source_type ('cvr'/'manual'), match-confidence.
|
|
1039
|
+
|
|
1040
|
+
${PLAN.pro}`,
|
|
1041
|
+
inputSchema: {
|
|
1042
|
+
id: z.string().uuid("Ugyldig UUID").describe("Person UUID fra company-responsen"),
|
|
1043
|
+
format: FORMAT_SCHEMA,
|
|
1044
|
+
},
|
|
1045
|
+
annotations: {
|
|
1046
|
+
readOnlyHint: true,
|
|
1047
|
+
destructiveHint: false,
|
|
1048
|
+
idempotentHint: true,
|
|
1049
|
+
openWorldHint: true,
|
|
1050
|
+
},
|
|
1051
|
+
}, async ({ id, format }) => {
|
|
1052
|
+
try {
|
|
1053
|
+
const data = await apiRequest(`/person/${id}`);
|
|
1054
|
+
if (format === "json")
|
|
1055
|
+
return jsonText(data);
|
|
1056
|
+
const lines = [];
|
|
1057
|
+
lines.push(`## ${data.canonical_name}`);
|
|
1058
|
+
lines.push(`- Aktive tilknytninger: ${data.active_company_count}`);
|
|
1059
|
+
lines.push(`- Historiske tilknytninger: ${data.historical_company_count}`);
|
|
1060
|
+
const aliases = data.aliases;
|
|
1061
|
+
if (aliases?.length)
|
|
1062
|
+
lines.push(`- Alias: ${aliases.join(", ")}`);
|
|
1063
|
+
if (data.match_strategy)
|
|
1064
|
+
lines.push(`- Match-strategi: ${data.match_strategy}`);
|
|
1065
|
+
if (data.match_confidence != null)
|
|
1066
|
+
lines.push(`- Match-confidence: ${data.match_confidence}`);
|
|
1067
|
+
const affiliations = (data.affiliations || []);
|
|
1068
|
+
if (affiliations.length) {
|
|
1069
|
+
lines.push("", "### Tilknytninger");
|
|
1070
|
+
for (const a of affiliations) {
|
|
1071
|
+
const status = a.left_date ? `historisk, fratr\u00e5dt ${a.left_date}` : "aktiv";
|
|
1072
|
+
const joined = a.joined_date ? `tiltr\u00e5dt ${a.joined_date}` : "";
|
|
1073
|
+
const extras = [];
|
|
1074
|
+
if (a.duration_days != null)
|
|
1075
|
+
extras.push(`${a.duration_days} dage`);
|
|
1076
|
+
if (a.ownership_share != null)
|
|
1077
|
+
extras.push(`ejerandel: ${a.ownership_share}%`);
|
|
1078
|
+
if (a.voting_share != null)
|
|
1079
|
+
extras.push(`stemmer: ${a.voting_share}%`);
|
|
1080
|
+
if (a.confidence != null)
|
|
1081
|
+
extras.push(`confidence: ${a.confidence}`);
|
|
1082
|
+
const extrasStr = extras.length ? ` — ${extras.join(", ")}` : "";
|
|
1083
|
+
lines.push(`- **${a.company_name}** (CVR ${a.cvr}) \u2014 ${a.role_title} [${status}]${joined ? ` (${joined})` : ""}${extrasStr}`);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1087
|
+
}
|
|
1088
|
+
catch (error) {
|
|
1089
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1090
|
+
}
|
|
1091
|
+
});
|
|
1092
|
+
// ── Tool 5: Person search ────────────────────────────────────────
|
|
1093
|
+
server.registerTool("firmaapi_search_persons", {
|
|
1094
|
+
title: "S\u00f8g personprofiler",
|
|
1095
|
+
description: `S\u00f8g efter personprofiler p\u00e5 navn, alias eller numerisk enhedsnummer/CVR (7+ cifre).
|
|
1096
|
+
|
|
1097
|
+
Resultater rangordnes efter match-type (exact > alias > prefix > fuzzy), derefter
|
|
1098
|
+
\`total_company_count\` (flest virksomheder f\u00f8rst) og til sidst alfabetisk for
|
|
1099
|
+
stabil paginering. Hvert hit har \`id\` (UUID til firmaapi_get_person), \`canonical_name\`,
|
|
1100
|
+
\`active_company_count\`, \`historical_company_count\`, \`total_company_count\`,
|
|
1101
|
+
\`match_type\` og \`match_confidence\`.
|
|
1102
|
+
|
|
1103
|
+
Args:
|
|
1104
|
+
- query (string): Personnavn, alias eller numerisk enhedsnummer/CVR (min 2 tegn)
|
|
1105
|
+
- limit (number, valgfri): Maks resultater (default 10, max 50)
|
|
1106
|
+
|
|
1107
|
+
Eksempler:
|
|
1108
|
+
- "Find Lars Larsen" \u2192 query="Lars Larsen"
|
|
1109
|
+
- "Hvem er J\u00f8rgen Fuglsang?" \u2192 query="J\u00f8rgen Fuglsang"
|
|
1110
|
+
- "Find person med enhedsnummer 4001234567" \u2192 query="4001234567"
|
|
1111
|
+
|
|
1112
|
+
${PLAN.pro}`,
|
|
1113
|
+
inputSchema: {
|
|
1114
|
+
query: z.string().min(2, "S\u00f8gestreng skal v\u00e6re mindst 2 tegn").describe("Personnavn"),
|
|
1115
|
+
limit: z.number().int().min(1).max(50).default(10).describe("Maks resultater"),
|
|
1116
|
+
format: FORMAT_SCHEMA,
|
|
1117
|
+
},
|
|
1118
|
+
annotations: {
|
|
1119
|
+
readOnlyHint: true,
|
|
1120
|
+
destructiveHint: false,
|
|
1121
|
+
idempotentHint: true,
|
|
1122
|
+
openWorldHint: true,
|
|
1123
|
+
},
|
|
1124
|
+
}, async ({ query, limit, format }) => {
|
|
1125
|
+
try {
|
|
1126
|
+
const data = await apiRequest(`/person/search`, { q: query, limit });
|
|
1127
|
+
if (format === "json")
|
|
1128
|
+
return jsonText(data);
|
|
1129
|
+
const results = (data.results || []);
|
|
1130
|
+
if (!results.length) {
|
|
1131
|
+
return { content: [{ type: "text", text: `Ingen personprofiler fundet for "${query}".` }] };
|
|
1132
|
+
}
|
|
1133
|
+
const lines = [`# Persons\u00f8gning: "${query}"`, ""];
|
|
1134
|
+
for (const p of results) {
|
|
1135
|
+
const parts = [`**${p.canonical_name}**`];
|
|
1136
|
+
parts.push(`${p.active_company_count} aktive, ${p.historical_company_count} historiske tilknytninger`);
|
|
1137
|
+
if (p.match_type)
|
|
1138
|
+
parts.push(`match: ${p.match_type}`);
|
|
1139
|
+
if (p.match_confidence != null)
|
|
1140
|
+
parts.push(`confidence: ${p.match_confidence}`);
|
|
1141
|
+
parts.push(`ID: ${p.id}`);
|
|
1142
|
+
lines.push(`- ${parts.join(" \u2014 ")}`);
|
|
1143
|
+
}
|
|
1144
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1145
|
+
}
|
|
1146
|
+
catch (error) {
|
|
1147
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1148
|
+
}
|
|
1149
|
+
});
|
|
1150
|
+
// ── Tool 6: Batch company lookup ─────────────────────────────────
|
|
1151
|
+
server.registerTool("firmaapi_batch_lookup", {
|
|
1152
|
+
title: "Batch-opslag af virksomheder",
|
|
1153
|
+
description: `Sl\u00e5 flere virksomheder op p\u00e5 \u00e9n gang via en liste af CVR-numre. Returnerer
|
|
1154
|
+
basis-stamdata pr. selskab + en \`errors[]\`-liste for CVR'er der ikke kunne hentes.
|
|
1155
|
+
|
|
1156
|
+
Bemærk: Batch-endpointet inkluderer IKKE tunge include-blokke (finance, history,
|
|
1157
|
+
relations, events). Brug firmaapi_lookup_company til ét selskab ad gangen hvis
|
|
1158
|
+
du har brug for de tunge blokke.
|
|
1159
|
+
|
|
1160
|
+
Args:
|
|
1161
|
+
- cvr_numbers (string): Kommasepareret liste af 8-cifrede CVR-numre (højst din plans batch-grænse, og højst 1.000 pr. kald)
|
|
1162
|
+
- fields (string[]): Kun hent specifikke felter pr. række (token-besparelse)
|
|
1163
|
+
- verbose (boolean): Hent fulde rækker (default: kompakt format)
|
|
1164
|
+
|
|
1165
|
+
Eksempler:
|
|
1166
|
+
- "Sl\u00e5 24256790 og 10150817 op" \u2192 cvr_numbers="24256790,10150817"
|
|
1167
|
+
- "Batch-opslag på CVR'er: 12345678, 87654321" \u2192 cvr_numbers="12345678,87654321"
|
|
1168
|
+
|
|
1169
|
+
${PLAN.basis} Per-plan batch-grænser: Basis 100, Standard 200, Professionel 500, Enterprise 1.000.`,
|
|
1170
|
+
inputSchema: {
|
|
1171
|
+
cvr_numbers: z.string().describe("Kommasepareret liste af 8-cifrede CVR-numre"),
|
|
1172
|
+
format: FORMAT_SCHEMA,
|
|
1173
|
+
fields: FIELDS_SCHEMA,
|
|
1174
|
+
verbose: VERBOSE_SCHEMA,
|
|
1175
|
+
},
|
|
1176
|
+
annotations: {
|
|
1177
|
+
readOnlyHint: true,
|
|
1178
|
+
destructiveHint: false,
|
|
1179
|
+
idempotentHint: true,
|
|
1180
|
+
openWorldHint: true,
|
|
1181
|
+
},
|
|
1182
|
+
}, async ({ cvr_numbers, format, fields, verbose }) => {
|
|
1183
|
+
try {
|
|
1184
|
+
const cvrList = cvr_numbers.split(",").map((s) => s.trim()).filter(Boolean);
|
|
1185
|
+
if (!cvrList.length) {
|
|
1186
|
+
return { content: [{ type: "text", text: "Fejl: Ingen CVR-numre angivet." }], isError: true };
|
|
1187
|
+
}
|
|
1188
|
+
// Hard upper bound — server håndhæver per-plan batch-grænser, men vi stopper
|
|
1189
|
+
// åbenlyst overdrevne kald før de spilder API-quota.
|
|
1190
|
+
if (cvrList.length > 1000) {
|
|
1191
|
+
return {
|
|
1192
|
+
content: [{
|
|
1193
|
+
type: "text",
|
|
1194
|
+
text: `Fejl: ${cvrList.length} CVR-numre angivet, max 1.000 pr. batch (Enterprise; Professionel 500). Brug færre eller del op i flere kald.`,
|
|
1195
|
+
}],
|
|
1196
|
+
isError: true,
|
|
1197
|
+
};
|
|
1198
|
+
}
|
|
1199
|
+
// Validate format up-front so an invalid CVR doesn't burn the whole batch
|
|
1200
|
+
const invalid = cvrList.filter((c) => !/^\d{8}$/.test(c));
|
|
1201
|
+
if (invalid.length) {
|
|
1202
|
+
return {
|
|
1203
|
+
content: [{
|
|
1204
|
+
type: "text",
|
|
1205
|
+
text: `Fejl: ${invalid.length} ugyldige CVR-numre (skal være 8 cifre): ${invalid.slice(0, 5).join(", ")}${invalid.length > 5 ? "..." : ""}`,
|
|
1206
|
+
}],
|
|
1207
|
+
isError: true,
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
const data = await apiPost(`/company/batch`, { cvr_numbers: cvrList });
|
|
1211
|
+
const rawResults = (data.results || []);
|
|
1212
|
+
if (format === "json") {
|
|
1213
|
+
return jsonText({ ...data, results: selectListFields(rawResults, fields, verbose) });
|
|
1214
|
+
}
|
|
1215
|
+
const results = rawResults;
|
|
1216
|
+
const errors = (data.errors || []);
|
|
1217
|
+
const lines = [`# Batch-opslag`, `${results.length} fundet, ${errors.length} fejl, kvota brugt: ${data.quota_used || results.length}`, ""];
|
|
1218
|
+
const customFields = !verbose && fields && fields.length > 0;
|
|
1219
|
+
for (const c of results) {
|
|
1220
|
+
if (customFields) {
|
|
1221
|
+
lines.push(formatPickedRow(c, fields));
|
|
1222
|
+
continue;
|
|
1223
|
+
}
|
|
1224
|
+
const parts = [`**${c.name}** (CVR ${c.cvr})`];
|
|
1225
|
+
if (c.status)
|
|
1226
|
+
parts.push(c.status);
|
|
1227
|
+
if (c.city)
|
|
1228
|
+
parts.push(c.city);
|
|
1229
|
+
if (verbose && c.industry_text) {
|
|
1230
|
+
parts.push(c.industry_text);
|
|
1231
|
+
}
|
|
1232
|
+
else if (c.industry_code) {
|
|
1233
|
+
parts.push(c.industry_code);
|
|
1234
|
+
}
|
|
1235
|
+
if (c.employees)
|
|
1236
|
+
parts.push(`${c.employees} ansatte`);
|
|
1237
|
+
lines.push(`- ${parts.join(" \u2014 ")}`);
|
|
1238
|
+
}
|
|
1239
|
+
if (errors.length) {
|
|
1240
|
+
lines.push("", "### Fejl");
|
|
1241
|
+
for (const e of errors) {
|
|
1242
|
+
lines.push(`- CVR ${e.cvr}: ${e.error}`);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1246
|
+
}
|
|
1247
|
+
catch (error) {
|
|
1248
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1249
|
+
}
|
|
1250
|
+
});
|
|
1251
|
+
// ── Tool 7: Industries ───────────────────────────────────────────
|
|
1252
|
+
server.registerTool("firmaapi_industries", {
|
|
1253
|
+
title: "Hent branchekoder (DB07)",
|
|
1254
|
+
description: `Hent danske branchekoder med hierarki og antal virksomheder.
|
|
1255
|
+
|
|
1256
|
+
Brug dette tool til at finde den korrekte branchekode inden du s\u00f8ger med firmaapi_advanced_search.
|
|
1257
|
+
Branchekoder er hierarkiske: "62" matcher alle IT-brancher (620100, 620200 osv.).
|
|
1258
|
+
|
|
1259
|
+
Eksempler:
|
|
1260
|
+
- "Hvilke IT-brancher findes?" \u2192 filter="IT"
|
|
1261
|
+
- "Find branchekode for byggeri" \u2192 filter="byggeri"
|
|
1262
|
+
- "Alle brancher under 62" \u2192 parent="62"
|
|
1263
|
+
- "Top-niveau brancher med v\u00e6kst" \u2192 max_depth=1, include_growth=true
|
|
1264
|
+
- "V\u00e6kst i IT-undergrupper" \u2192 parent="62", max_depth=3, include_growth=true`,
|
|
1265
|
+
inputSchema: {
|
|
1266
|
+
filter: z.string().optional().describe("Filtrer branchelisten p\u00e5 navn eller kode (lokal filtrering)"),
|
|
1267
|
+
parent: z.string().optional().describe("Begr\u00e6ns til en specifik gren \u2014 inkluderer den givne kode plus alle dens children (server-side prefix-match)"),
|
|
1268
|
+
max_depth: z.number().int().min(1).max(4).optional().describe("Maks. dybde i hierarkiet: 1=division (2 cifre), 2=group, 3=class, 4=branch (6 cifre)"),
|
|
1269
|
+
include_growth: z.boolean().optional().describe("Tilf\u00f8j founded_last_12m pr. branche \u2014 antal stiftede sidste 12 m\u00e5neder, rolled-up over alle child-koder"),
|
|
1270
|
+
format: FORMAT_SCHEMA,
|
|
1271
|
+
},
|
|
1272
|
+
annotations: {
|
|
1273
|
+
readOnlyHint: true,
|
|
1274
|
+
destructiveHint: false,
|
|
1275
|
+
idempotentHint: true,
|
|
1276
|
+
openWorldHint: true,
|
|
1277
|
+
},
|
|
1278
|
+
}, async ({ filter, parent, max_depth, include_growth, format }) => {
|
|
1279
|
+
try {
|
|
1280
|
+
// Server-side params: parent + max_depth + include_growth.
|
|
1281
|
+
// Local-only param: filter (text search across the trimmed list).
|
|
1282
|
+
const apiParams = {};
|
|
1283
|
+
if (parent)
|
|
1284
|
+
apiParams.parent = parent;
|
|
1285
|
+
if (max_depth !== undefined)
|
|
1286
|
+
apiParams.max_depth = max_depth;
|
|
1287
|
+
if (include_growth)
|
|
1288
|
+
apiParams.include_growth = true;
|
|
1289
|
+
const data = await apiRequest(`/industries`, apiParams);
|
|
1290
|
+
let items = (data.items || []);
|
|
1291
|
+
if (filter) {
|
|
1292
|
+
const f = filter.toLowerCase();
|
|
1293
|
+
items = items.filter((i) => i.label.toLowerCase().includes(f) ||
|
|
1294
|
+
i.code.includes(f) ||
|
|
1295
|
+
i.display_code?.includes(f));
|
|
1296
|
+
}
|
|
1297
|
+
if (!items.length) {
|
|
1298
|
+
let emptyText;
|
|
1299
|
+
if (filter) {
|
|
1300
|
+
emptyText = `Ingen brancher matcher "${filter}".`;
|
|
1301
|
+
}
|
|
1302
|
+
else if (parent) {
|
|
1303
|
+
emptyText = `Ingen brancher fundet under "${parent}".`;
|
|
1304
|
+
}
|
|
1305
|
+
else {
|
|
1306
|
+
emptyText = "Ingen branchedata tilg\u00e6ngelig.";
|
|
1307
|
+
}
|
|
1308
|
+
return { content: [{ type: "text", text: emptyText }] };
|
|
1309
|
+
}
|
|
1310
|
+
if (format === "json") {
|
|
1311
|
+
return jsonText({ items, meta: data.meta, total: items.length, filter: filter ?? null });
|
|
1312
|
+
}
|
|
1313
|
+
const meta = data.meta;
|
|
1314
|
+
const filterParts = [];
|
|
1315
|
+
if (filter)
|
|
1316
|
+
filterParts.push(`tekst="${filter}"`);
|
|
1317
|
+
if (parent)
|
|
1318
|
+
filterParts.push(`parent="${parent}"`);
|
|
1319
|
+
if (max_depth !== undefined)
|
|
1320
|
+
filterParts.push(`max_depth=${max_depth}`);
|
|
1321
|
+
const filterSuffix = filterParts.length ? ` (filtre: ${filterParts.join(", ")})` : "";
|
|
1322
|
+
const growthUnavailable = include_growth && meta?.growth_unavailable === true;
|
|
1323
|
+
const headerLines = [
|
|
1324
|
+
`# Branchekoder`,
|
|
1325
|
+
`${items.length} brancher${filterSuffix}${meta?.refreshed_at ? ` \u2014 sidst opdateret: ${meta.refreshed_at}` : ""}`,
|
|
1326
|
+
];
|
|
1327
|
+
if (growthUnavailable) {
|
|
1328
|
+
headerLines.push("", "\u26a0\ufe0f V\u00e6kstdata kunne ikke beregnes \u2014 founded_last_12m vises som 0 men er ikke en faktisk m\u00e5ling.");
|
|
1329
|
+
}
|
|
1330
|
+
headerLines.push("");
|
|
1331
|
+
const itemLines = [];
|
|
1332
|
+
for (const i of items) {
|
|
1333
|
+
const count = i.company_count ? ` (${i.company_count} virksomheder)` : "";
|
|
1334
|
+
// Suppress growth annotation when backend flagged it as unavailable —
|
|
1335
|
+
// we don't want users mistaking placeholder zeros for real signals.
|
|
1336
|
+
const growth = include_growth && !growthUnavailable && typeof i.founded_last_12m === "number"
|
|
1337
|
+
? `, +${i.founded_last_12m.toLocaleString("da-DK")} sidste 12 mdr`
|
|
1338
|
+
: "";
|
|
1339
|
+
itemLines.push(`- **${i.display_code || i.code}** ${i.label}${count}${growth}`);
|
|
1340
|
+
}
|
|
1341
|
+
const FOOTER_BUDGET = 400;
|
|
1342
|
+
const headerText = headerLines.join("\n");
|
|
1343
|
+
let availableForItems = CHARACTER_LIMIT - headerText.length - FOOTER_BUDGET;
|
|
1344
|
+
let cutoff = itemLines.length;
|
|
1345
|
+
let used = 0;
|
|
1346
|
+
for (let idx = 0; idx < itemLines.length; idx++) {
|
|
1347
|
+
const lineLength = itemLines[idx].length + 1;
|
|
1348
|
+
if (used + lineLength > availableForItems) {
|
|
1349
|
+
cutoff = idx;
|
|
1350
|
+
break;
|
|
1351
|
+
}
|
|
1352
|
+
used += lineLength;
|
|
1353
|
+
}
|
|
1354
|
+
const truncatedCount = itemLines.length - cutoff;
|
|
1355
|
+
const includedLines = itemLines.slice(0, cutoff);
|
|
1356
|
+
const lines = [...headerLines, ...includedLines];
|
|
1357
|
+
if (truncatedCount > 0) {
|
|
1358
|
+
let hint;
|
|
1359
|
+
if (filter) {
|
|
1360
|
+
hint = `Indsn\u00e6vr filteret yderligere (fx 'filter=\"${filter}.\"' eller brug parent/max_depth).`;
|
|
1361
|
+
}
|
|
1362
|
+
else if (parent) {
|
|
1363
|
+
hint = `Reducer scope under "${parent}" \u2014 fx max_depth=${Math.max(1, (max_depth ?? 4) - 1)} eller en mere specifik parent.`;
|
|
1364
|
+
}
|
|
1365
|
+
else {
|
|
1366
|
+
hint = "Brug 'parent' (fx '62'), 'max_depth' (1-4), eller 'filter' for at sn\u00e6vre listen.";
|
|
1367
|
+
}
|
|
1368
|
+
lines.push("", `\u26a0\ufe0f ${truncatedCount} brancher er udeladt for at holde svaret under ${CHARACTER_LIMIT.toLocaleString("da-DK")} tegn.`, `Hint: ${hint}`, `Fuld liste: ${items.length} brancher \u2014 viser ${cutoff}, mangler ${truncatedCount}.`);
|
|
1369
|
+
}
|
|
1370
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
1371
|
+
}
|
|
1372
|
+
catch (error) {
|
|
1373
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1376
|
+
// ── Tool 8: Municipalities ───────────────────────────────────────
|
|
1377
|
+
server.registerTool("firmaapi_municipalities", {
|
|
1378
|
+
title: "Hent kommuneliste",
|
|
1379
|
+
description: `Hent listen over danske kommuner med koder.
|
|
1380
|
+
|
|
1381
|
+
Brug dette tool til at finde den korrekte kommunekode til avanceret s\u00f8gning.
|
|
1382
|
+
|
|
1383
|
+
Eksempler:
|
|
1384
|
+
- "Hvilke kommunekoder findes der?" \u2192 (ingen parametre)
|
|
1385
|
+
- "Find koden for Aarhus kommune" \u2192 filter="Aarhus"`,
|
|
1386
|
+
inputSchema: {
|
|
1387
|
+
filter: z.string().optional().describe("Filtrer p\u00e5 kommunenavn"),
|
|
1388
|
+
format: FORMAT_SCHEMA,
|
|
1389
|
+
},
|
|
1390
|
+
annotations: {
|
|
1391
|
+
readOnlyHint: true,
|
|
1392
|
+
destructiveHint: false,
|
|
1393
|
+
idempotentHint: true,
|
|
1394
|
+
openWorldHint: true,
|
|
1395
|
+
},
|
|
1396
|
+
}, async ({ filter, format }) => {
|
|
1397
|
+
try {
|
|
1398
|
+
const data = await apiRequest(`/municipalities`);
|
|
1399
|
+
let items = (data.items || []);
|
|
1400
|
+
if (filter) {
|
|
1401
|
+
const f = filter.toLowerCase();
|
|
1402
|
+
items = items.filter((i) => i.name.toLowerCase().includes(f));
|
|
1403
|
+
}
|
|
1404
|
+
if (!items.length) {
|
|
1405
|
+
return { content: [{ type: "text", text: filter ? `Ingen kommuner matcher "${filter}".` : "Ingen kommunedata tilg\u00e6ngelig." }] };
|
|
1406
|
+
}
|
|
1407
|
+
if (format === "json") {
|
|
1408
|
+
return jsonText({ items, total: items.length, filter: filter ?? null });
|
|
1409
|
+
}
|
|
1410
|
+
const lines = [`# Kommuner`, `${items.length} kommuner${filter ? ` (filtreret p\u00e5 "${filter}")` : ""}`, ""];
|
|
1411
|
+
for (const i of items) {
|
|
1412
|
+
lines.push(`- **${i.code}** (${i.numeric_code}) ${i.name}`);
|
|
1413
|
+
}
|
|
1414
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1415
|
+
}
|
|
1416
|
+
catch (error) {
|
|
1417
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1418
|
+
}
|
|
1419
|
+
});
|
|
1420
|
+
// ── Tool 33: Regions ─────────────────────────────────────────────
|
|
1421
|
+
server.registerTool("firmaapi_regions", {
|
|
1422
|
+
title: "Hent danske regioner med kommune-medlemskab",
|
|
1423
|
+
description: `Hent de 5 officielle danske regioner (Hovedstaden, Sjælland, Syddanmark,
|
|
1424
|
+
Midtjylland, Nordjylland) med fuld kommune-medlemskab.
|
|
1425
|
+
|
|
1426
|
+
Brug dette tool når du vil:
|
|
1427
|
+
- Slå op hvilke kommuner der hører under en region
|
|
1428
|
+
- Finde gyldige værdier til \`region\`/\`region_list\`-filtre på advanced_search
|
|
1429
|
+
- Visualisere geografisk struktur på dansk niveau
|
|
1430
|
+
|
|
1431
|
+
Output indeholder pr. region: navn, full_name (med "Region"-prefix),
|
|
1432
|
+
municipality_count, og array af municipalities med numeric_code og name.
|
|
1433
|
+
|
|
1434
|
+
Bornholm og Christiansø-enklaven hører under Region Hovedstaden.
|
|
1435
|
+
|
|
1436
|
+
Args:
|
|
1437
|
+
- filter (string, valgfri): Filtrer på regionsnavn (case-insensitivt)
|
|
1438
|
+
- format (markdown|json)
|
|
1439
|
+
|
|
1440
|
+
Eksempler:
|
|
1441
|
+
- "Vis alle regioner" → (ingen parametre)
|
|
1442
|
+
- "Hvilke kommuner er i Region Hovedstaden?" → filter="Hovedstaden"
|
|
1443
|
+
- "Vis Sjælland" → filter="Sjælland"
|
|
1444
|
+
|
|
1445
|
+
${PLAN.any} Pure reference-data, ingen plan-restriktion. Kilde: Danmarks
|
|
1446
|
+
Statistik / regionsinddelingen.`,
|
|
1447
|
+
inputSchema: {
|
|
1448
|
+
filter: z.string().optional().describe("Filtrer på regionsnavn (case-insensitivt)"),
|
|
1449
|
+
format: FORMAT_SCHEMA,
|
|
1450
|
+
},
|
|
1451
|
+
annotations: {
|
|
1452
|
+
readOnlyHint: true,
|
|
1453
|
+
destructiveHint: false,
|
|
1454
|
+
idempotentHint: true,
|
|
1455
|
+
openWorldHint: true,
|
|
1456
|
+
},
|
|
1457
|
+
}, async ({ filter, format }) => {
|
|
1458
|
+
try {
|
|
1459
|
+
const data = await apiRequest(`/regions`);
|
|
1460
|
+
let items = (data.items || []);
|
|
1461
|
+
if (filter) {
|
|
1462
|
+
const f = filter.toLowerCase().replace(/^region\s+/i, "");
|
|
1463
|
+
items = items.filter((r) => String(r.name).toLowerCase().includes(f));
|
|
1464
|
+
}
|
|
1465
|
+
if (!items.length) {
|
|
1466
|
+
return {
|
|
1467
|
+
content: [{
|
|
1468
|
+
type: "text",
|
|
1469
|
+
text: filter ? `Ingen regioner matcher "${filter}".` : "Ingen region-data tilgængelig.",
|
|
1470
|
+
}],
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
if (format === "json") {
|
|
1474
|
+
return jsonText({ items, meta: data.meta, filter: filter ?? null });
|
|
1475
|
+
}
|
|
1476
|
+
const meta = data.meta;
|
|
1477
|
+
const lines = [`# Danske regioner`, ""];
|
|
1478
|
+
if (meta?.total != null) {
|
|
1479
|
+
lines.push(`*${meta.total} regioner, ${meta.total_municipalities ?? "?"} kommuner i alt. Kilde: ${meta.source ?? "Danmarks Statistik"}*`, "");
|
|
1480
|
+
}
|
|
1481
|
+
for (const r of items) {
|
|
1482
|
+
lines.push(`### ${r.full_name} (${r.municipality_count} kommuner)`);
|
|
1483
|
+
const municipalities = (r.municipalities || []);
|
|
1484
|
+
const grouped = municipalities.map((m) => `${m.name} (${m.numeric_code})`);
|
|
1485
|
+
lines.push(grouped.join(", "));
|
|
1486
|
+
lines.push("");
|
|
1487
|
+
}
|
|
1488
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1489
|
+
}
|
|
1490
|
+
catch (error) {
|
|
1491
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1492
|
+
}
|
|
1493
|
+
});
|
|
1494
|
+
// ── Tool 9: Production unit lookup ───────────────────────────────
|
|
1495
|
+
server.registerTool("firmaapi_production_unit", {
|
|
1496
|
+
title: "Sl\u00e5 produktionsenhed op via P-nummer",
|
|
1497
|
+
description: `Hent oplysninger om en produktionsenhed (P-enhed) via dens P-nummer.
|
|
1498
|
+
|
|
1499
|
+
En P-enhed er en fysisk lokation tilknyttet en CVR-virksomhed (én virksomhed
|
|
1500
|
+
kan have mange P-enheder — fx en restaurantkæde med filialer).
|
|
1501
|
+
|
|
1502
|
+
Args:
|
|
1503
|
+
- p_number (string): 10-cifret P-nummer
|
|
1504
|
+
|
|
1505
|
+
Returnerer: P-nummer, navn, link til CVR-virksomhed, adresse, branche, antal
|
|
1506
|
+
ansatte (interval), kontaktoplysninger hvis tilgængelige.
|
|
1507
|
+
|
|
1508
|
+
Eksempler:
|
|
1509
|
+
- "Sl\u00e5 P-nummer 1234567890 op" \u2192 p_number="1234567890"
|
|
1510
|
+
|
|
1511
|
+
${PLAN.standard}`,
|
|
1512
|
+
inputSchema: {
|
|
1513
|
+
p_number: z.string().regex(/^\d{10}$/, "P-nummer skal v\u00e6re pr\u00e6cis 10 cifre").describe("10-cifret P-nummer"),
|
|
1514
|
+
format: FORMAT_SCHEMA,
|
|
1515
|
+
},
|
|
1516
|
+
annotations: {
|
|
1517
|
+
readOnlyHint: true,
|
|
1518
|
+
destructiveHint: false,
|
|
1519
|
+
idempotentHint: true,
|
|
1520
|
+
openWorldHint: true,
|
|
1521
|
+
},
|
|
1522
|
+
}, async ({ p_number, format }) => {
|
|
1523
|
+
try {
|
|
1524
|
+
const data = await apiRequest(`/production-unit/${p_number}`);
|
|
1525
|
+
if (format === "json")
|
|
1526
|
+
return jsonText(data);
|
|
1527
|
+
const lines = [];
|
|
1528
|
+
lines.push(`## ${data.name || "Produktionsenhed"} (P-nr. ${data.p_number})`);
|
|
1529
|
+
lines.push("");
|
|
1530
|
+
if (data.cvr)
|
|
1531
|
+
lines.push(`- **CVR**: ${data.cvr}`);
|
|
1532
|
+
if (data.address)
|
|
1533
|
+
lines.push(`- **Adresse**: ${data.address}, ${data.zipcode} ${data.city}`);
|
|
1534
|
+
if (data.industry_text)
|
|
1535
|
+
lines.push(`- **Branche**: ${data.industry_text} (${data.industry_code})`);
|
|
1536
|
+
if (data.employees)
|
|
1537
|
+
lines.push(`- **Ansatte**: ${data.employees}`);
|
|
1538
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
1539
|
+
}
|
|
1540
|
+
catch (error) {
|
|
1541
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1542
|
+
}
|
|
1543
|
+
});
|
|
1544
|
+
// ── Shared filter schema (explain_query, aggregate, timeseries) ──
|
|
1545
|
+
const SHARED_SEARCH_FILTERS = {
|
|
1546
|
+
q: z.string().optional().describe("Navnes\u00f8gning (* for alle, eller delvis match fx 'Novo')"),
|
|
1547
|
+
city: z.string().optional().describe("Bynavn (case-insensitiv)"),
|
|
1548
|
+
zipcode: z.string().optional().describe("Postnummer (eksakt)"),
|
|
1549
|
+
municipality: z.string().optional().describe("Kommunenavn eller -kode"),
|
|
1550
|
+
municipality_list: z.string().optional().describe("Komma-adskilt liste af kommunenavne/-koder (OR-match), fx 'K\u00f8benhavn,Aarhus,101'"),
|
|
1551
|
+
region: z.string().optional().describe("Dansk region: 'Hovedstaden', 'Sj\u00e6lland', 'Syddanmark', 'Midtjylland' eller 'Nordjylland'"),
|
|
1552
|
+
region_list: z.string().optional().describe("Komma-adskilt liste af regioner (OR-match)"),
|
|
1553
|
+
industry: z.string().optional().describe("Branchekode som prefix (fx '62') eller fritekst"),
|
|
1554
|
+
industry_list: z.string().optional().describe("Komma-adskilt liste af branchekoder (OR-match), fx '62,70,73'"),
|
|
1555
|
+
industry_exclude: z.string().optional().describe("Komma-adskilt liste af branchekoder der ekskluderes (prefix-match)"),
|
|
1556
|
+
company_type: z.string().optional().describe("Selskabsform. Forkortelser (ApS, A/S, IVS, I/S, K/S, P/S, SMBA, AMBA, FMBA, ENK, PMV) matcher den præcise CVR-form; andre værdier matches delvist på den lange betegnelse"),
|
|
1557
|
+
company_type_list: z.string().optional().describe("Komma-adskilt liste af selskabsformer (OR-match), fx 'ApS,A/S'. Hver værdi tolkes som company_type"),
|
|
1558
|
+
owner_kind: z.string().optional().describe("Komma-adskilt liste af ejertyper for de aktive, direkte legale ejere (OR-match): person, holding, fund, company, foreign (uden dansk CVR). Fx 'holding,fund'"),
|
|
1559
|
+
status: z.string().optional().describe("Case-insensitiv: 'Aktiv', 'Oph\u00f8rt' m.fl."),
|
|
1560
|
+
employees: z.string().optional().describe("'5+', '10-49', '42' eller 'ANTAL_10_19'"),
|
|
1561
|
+
revenue_min: z.number().optional().describe("Min. oms\u00e6tning i DKK"),
|
|
1562
|
+
revenue_max: z.number().optional().describe("Maks. oms\u00e6tning i DKK"),
|
|
1563
|
+
capital_min: z.number().optional().describe("Min. selskabskapital i DKK"),
|
|
1564
|
+
capital_max: z.number().optional().describe("Maks. selskabskapital i DKK"),
|
|
1565
|
+
founded_after: z.string().optional().describe("Stiftet efter dato (YYYY-MM-DD)"),
|
|
1566
|
+
founded_before: z.string().optional().describe("Stiftet f\u00f8r dato (YYYY-MM-DD)"),
|
|
1567
|
+
founded_year: z.string().optional().describe("Pr\u00e6cist stiftelses\u00e5r (YYYY)"),
|
|
1568
|
+
founded_year_min: z.string().optional().describe("Tidligste stiftelses\u00e5r (YYYY)"),
|
|
1569
|
+
founded_year_max: z.string().optional().describe("Seneste stiftelses\u00e5r (YYYY)"),
|
|
1570
|
+
dissolved_after: z.string().optional().describe("Opl\u00f8st efter dato (YYYY-MM-DD)"),
|
|
1571
|
+
dissolved_before: z.string().optional().describe("Opl\u00f8st f\u00f8r dato (YYYY-MM-DD)"),
|
|
1572
|
+
dissolved_year: z.string().optional().describe("Pr\u00e6cist opl\u00f8sningsr\u00e5r (YYYY)"),
|
|
1573
|
+
dissolved_year_min: z.string().optional().describe("Tidligste opl\u00f8sningsr\u00e5r (YYYY)"),
|
|
1574
|
+
dissolved_year_max: z.string().optional().describe("Seneste opl\u00f8sningsr\u00e5r (YYYY)"),
|
|
1575
|
+
is_dissolved: z.boolean().optional().describe("'true' = kun opl\u00f8ste virksomheder, 'false' = kun stadig aktive"),
|
|
1576
|
+
age_min: z.number().int().nonnegative().optional().describe("Minimum alder i fulde \u00e5r"),
|
|
1577
|
+
age_max: z.number().int().nonnegative().optional().describe("Maks alder i fulde \u00e5r"),
|
|
1578
|
+
last_report_year_min: z.string().optional().describe("Tidligste \u00e5r for seneste regnskab (YYYY)"),
|
|
1579
|
+
last_report_year_max: z.string().optional().describe("Seneste \u00e5r for seneste regnskab (YYYY)"),
|
|
1580
|
+
has_financials: z.boolean().optional().describe("Kun virksomheder med regnskabsdata"),
|
|
1581
|
+
ad_protected: z.string().optional().describe("'false' = ikke reklamebeskyttet, 'true' = reklamebeskyttet; ikke et samtykke"),
|
|
1582
|
+
has_phone: z.boolean().optional().describe("Kun virksomheder med telefonnummer"),
|
|
1583
|
+
has_email: z.boolean().optional().describe("Kun virksomheder med email"),
|
|
1584
|
+
has_website: z.boolean().optional().describe("Kun virksomheder med hjemmeside"),
|
|
1585
|
+
// Numeric employees-filtre — renere end string-formatet ovenfor til ICP-targeting
|
|
1586
|
+
employees_min: z.number().int().nonnegative().optional().describe("Min. antal ansatte (numerisk; rammer indekseret employees_max)"),
|
|
1587
|
+
employees_max: z.number().int().nonnegative().optional().describe("Maks. antal ansatte (numerisk; rammer indekseret employees_min)"),
|
|
1588
|
+
// Change-detection: find virksomheder hvor source-dataet er ændret efter en dato
|
|
1589
|
+
updated_after: z.string().optional().describe("Kun virksomheder med ændringer efter denne ISO-dato (YYYY-MM-DD eller fuld ISO-timestamp)"),
|
|
1590
|
+
updated_before: z.string().optional().describe("Kun virksomheder uden ændringer efter denne ISO-dato"),
|
|
1591
|
+
// Sortering — default er updated_at:desc. Andre værdier bryder cursor-pagination.
|
|
1592
|
+
sort: z
|
|
1593
|
+
.string()
|
|
1594
|
+
.optional()
|
|
1595
|
+
.describe("Sortering: '<field>:asc' eller '<field>:desc'. Felter: revenue, capital, employees, founded, dissolved, last_report_year, name, updated_at. Default: updated_at:desc"),
|
|
1596
|
+
};
|
|
1597
|
+
function describeFilters(filters) {
|
|
1598
|
+
const parts = [];
|
|
1599
|
+
for (const [key, value] of Object.entries(filters)) {
|
|
1600
|
+
if (value === undefined || value === "" || value === null)
|
|
1601
|
+
continue;
|
|
1602
|
+
parts.push(`${key}=${value}`);
|
|
1603
|
+
}
|
|
1604
|
+
return parts;
|
|
1605
|
+
}
|
|
1606
|
+
function explainSizeNote(total) {
|
|
1607
|
+
if (total === 0)
|
|
1608
|
+
return "Ingen match. Lemp filtrene eller tjek stavning.";
|
|
1609
|
+
if (total <= 50)
|
|
1610
|
+
return "Lille resultats\u00e6t \u2014 sikkert at hente alle.";
|
|
1611
|
+
if (total <= 1_000)
|
|
1612
|
+
return "Moderat resultats\u00e6t \u2014 hent gerne alle, men forvent ~"
|
|
1613
|
+
+ Math.ceil(total / 100) + " sider ved limit=100.";
|
|
1614
|
+
if (total <= 10_000)
|
|
1615
|
+
return "Stort resultats\u00e6t \u2014 overvej at indsn\u00e6vre med flere filtre f\u00f8r du henter alle.";
|
|
1616
|
+
return "Meget stort resultats\u00e6t \u2014 anbefales at indsn\u00e6vre kraftigt (fx ved by, branche eller stiftelses\u00e5r) f\u00f8r du henter.";
|
|
1617
|
+
}
|
|
1618
|
+
const REFINEMENT_DIMENSIONS = [
|
|
1619
|
+
{ group_by: "industry", filter_param: "industry", conflicts_with: ["industry", "industry_list", "industry_exclude"], label: "Branche" },
|
|
1620
|
+
{ group_by: "municipality", filter_param: "municipality", conflicts_with: ["municipality", "municipality_list", "region", "region_list", "city", "zipcode"], label: "Kommune" },
|
|
1621
|
+
{ group_by: "employees_bucket", filter_param: "employees", conflicts_with: ["employees"], label: "Ansatte" },
|
|
1622
|
+
];
|
|
1623
|
+
const EMPLOYEES_BUCKET_FILTER = {
|
|
1624
|
+
solo: "1",
|
|
1625
|
+
mikro_2_9: "2-9",
|
|
1626
|
+
lille_10_49: "10-49",
|
|
1627
|
+
mellem_50_249: "50-249",
|
|
1628
|
+
stor_250_plus: "250+",
|
|
1629
|
+
};
|
|
1630
|
+
function refinementHint(g, top) {
|
|
1631
|
+
if (g.filter_param === "employees") {
|
|
1632
|
+
const value = EMPLOYEES_BUCKET_FILTER[top.key] ?? top.key;
|
|
1633
|
+
return `employees="${value}" \u2192 ca. ${top.count.toLocaleString("da-DK")} matches (${top.share.toFixed(1)}%)`;
|
|
1634
|
+
}
|
|
1635
|
+
return `${g.filter_param}="${top.key}" \u2192 ca. ${top.count.toLocaleString("da-DK")} matches (${top.share.toFixed(1)}%)`;
|
|
1636
|
+
}
|
|
1637
|
+
async function fetchRefinement(dim, filters, total) {
|
|
1638
|
+
// Skip dimensions that the caller has already filtered on — refinements
|
|
1639
|
+
// only make sense for *new* axes the user hasn't constrained yet.
|
|
1640
|
+
// We check every related param so e.g. industry_list also disables the
|
|
1641
|
+
// industry refinement, not just the bare 'industry' param.
|
|
1642
|
+
const f = filters;
|
|
1643
|
+
for (const param of dim.conflicts_with) {
|
|
1644
|
+
const value = f[param];
|
|
1645
|
+
if (value != null && value !== "")
|
|
1646
|
+
return null;
|
|
1647
|
+
}
|
|
1648
|
+
try {
|
|
1649
|
+
const data = await apiRequest(`/search/aggregate`, {
|
|
1650
|
+
...filters,
|
|
1651
|
+
group_by: dim.group_by,
|
|
1652
|
+
top_n: 5,
|
|
1653
|
+
});
|
|
1654
|
+
const top = data.results
|
|
1655
|
+
.filter((r) => r.key !== null && r.key !== "")
|
|
1656
|
+
.map((r) => ({
|
|
1657
|
+
key: r.key,
|
|
1658
|
+
count: r.count,
|
|
1659
|
+
share: total > 0 ? (r.count / total) * 100 : 0,
|
|
1660
|
+
}));
|
|
1661
|
+
if (top.length === 0)
|
|
1662
|
+
return null;
|
|
1663
|
+
return {
|
|
1664
|
+
dimension: dim.group_by,
|
|
1665
|
+
filter_param: dim.filter_param,
|
|
1666
|
+
label: dim.label,
|
|
1667
|
+
total_groups: data.total_groups,
|
|
1668
|
+
top,
|
|
1669
|
+
};
|
|
1670
|
+
}
|
|
1671
|
+
catch {
|
|
1672
|
+
// Refinements are best-effort; never let a single dimension failure
|
|
1673
|
+
// break the explain_query response.
|
|
1674
|
+
return null;
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
server.registerTool("firmaapi_explain_query", {
|
|
1678
|
+
title: "T\u00e6l matches uden at hente data",
|
|
1679
|
+
description: `Returnerer kun antallet af matches for en avanceret s\u00f8gning \u2014 ikke selve virksomhederne.
|
|
1680
|
+
|
|
1681
|
+
Brug dette tool n\u00e5r du vil vide hvor stor en s\u00f8gning er, f\u00f8r du beslutter at hente alle resultater.
|
|
1682
|
+
Sparer tokens og kvota sammenlignet med at paginere et stort datas\u00e6t blindt.
|
|
1683
|
+
|
|
1684
|
+
Tager samme filtre som firmaapi_advanced_search. Mindst \u00e9t filter er p\u00e5kr\u00e6vet.
|
|
1685
|
+
|
|
1686
|
+
Eksempler:
|
|
1687
|
+
- "Hvor mange aktive IT-firmaer findes?" \u2192 industry="62", status="Aktiv"
|
|
1688
|
+
- "Hvor mange ApS'er stiftet i 2024?" \u2192 company_type="ApS", founded_after="2024-01-01", founded_before="2024-12-31"
|
|
1689
|
+
- "Stort er datas\u00e6ttet for K\u00f8benhavn?" \u2192 city="K\u00f8benhavn", status="Aktiv"`,
|
|
1690
|
+
inputSchema: {
|
|
1691
|
+
...SHARED_SEARCH_FILTERS,
|
|
1692
|
+
format: FORMAT_SCHEMA,
|
|
1693
|
+
},
|
|
1694
|
+
annotations: {
|
|
1695
|
+
readOnlyHint: true,
|
|
1696
|
+
destructiveHint: false,
|
|
1697
|
+
idempotentHint: true,
|
|
1698
|
+
openWorldHint: true,
|
|
1699
|
+
},
|
|
1700
|
+
}, async (params) => {
|
|
1701
|
+
try {
|
|
1702
|
+
const { format, ...filters } = params;
|
|
1703
|
+
const filterDescriptions = describeFilters(filters);
|
|
1704
|
+
// Backend tæller q="*" som "ingen navnefilter" (ikke en søgeparameter).
|
|
1705
|
+
// Spejl den regel her, så vi giver en hjælpsom dansk fejlbesked
|
|
1706
|
+
// i stedet for backend's engelske 400.
|
|
1707
|
+
const meaningfulFilters = filterDescriptions.filter((d) => d !== "q=*");
|
|
1708
|
+
if (meaningfulFilters.length === 0) {
|
|
1709
|
+
return {
|
|
1710
|
+
content: [
|
|
1711
|
+
{
|
|
1712
|
+
type: "text",
|
|
1713
|
+
text: "Fejl: Mindst \u00e9t reelt filter er p\u00e5kr\u00e6vet (q=* alene t\u00e6ller ikke). Tilf\u00f8j fx industry, city, status, employees eller founded_after.",
|
|
1714
|
+
},
|
|
1715
|
+
],
|
|
1716
|
+
isError: true,
|
|
1717
|
+
};
|
|
1718
|
+
}
|
|
1719
|
+
const apiParams = {
|
|
1720
|
+
...filters,
|
|
1721
|
+
limit: 1,
|
|
1722
|
+
offset: 0,
|
|
1723
|
+
include_total: true,
|
|
1724
|
+
};
|
|
1725
|
+
const data = await apiRequest(`/search/advanced`, apiParams);
|
|
1726
|
+
const totalRaw = data.total;
|
|
1727
|
+
if (typeof totalRaw !== "number") {
|
|
1728
|
+
return {
|
|
1729
|
+
content: [
|
|
1730
|
+
{
|
|
1731
|
+
type: "text",
|
|
1732
|
+
text: "Fejl: API'et returnerede ikke et total-felt. Pr\u00f8v firmaapi_advanced_search direkte.",
|
|
1733
|
+
},
|
|
1734
|
+
],
|
|
1735
|
+
isError: true,
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
const total = totalRaw;
|
|
1739
|
+
// For very small result sets, refinements aren't useful — skip them.
|
|
1740
|
+
// Same when we have no matches (nothing to break down).
|
|
1741
|
+
const refinements = total > 50
|
|
1742
|
+
? (await Promise.all(REFINEMENT_DIMENSIONS.map((d) => fetchRefinement(d, filters, total))))
|
|
1743
|
+
.filter((r) => r !== null)
|
|
1744
|
+
: [];
|
|
1745
|
+
if (format === "json") {
|
|
1746
|
+
return jsonText({
|
|
1747
|
+
total_matches: total,
|
|
1748
|
+
filters,
|
|
1749
|
+
note: explainSizeNote(total),
|
|
1750
|
+
suggested_refinements: refinements.map((g) => ({
|
|
1751
|
+
dimension: g.dimension,
|
|
1752
|
+
filter_param: g.filter_param,
|
|
1753
|
+
total_groups: g.total_groups,
|
|
1754
|
+
top: g.top,
|
|
1755
|
+
})),
|
|
1756
|
+
});
|
|
1757
|
+
}
|
|
1758
|
+
const lines = [
|
|
1759
|
+
`# Explain query`,
|
|
1760
|
+
`Filtre: ${filterDescriptions.join(", ")}`,
|
|
1761
|
+
"",
|
|
1762
|
+
`**total_matches**: ${total.toLocaleString("da-DK")}`,
|
|
1763
|
+
"",
|
|
1764
|
+
explainSizeNote(total),
|
|
1765
|
+
];
|
|
1766
|
+
if (refinements.length > 0) {
|
|
1767
|
+
lines.push("", "## Foresl\u00e5ede filtre");
|
|
1768
|
+
for (const g of refinements) {
|
|
1769
|
+
lines.push("", `### ${g.label} (${g.total_groups.toLocaleString("da-DK")} grupper)`);
|
|
1770
|
+
for (const top of g.top) {
|
|
1771
|
+
lines.push(`- ${refinementHint(g, top)}`);
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1776
|
+
}
|
|
1777
|
+
catch (error) {
|
|
1778
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1779
|
+
}
|
|
1780
|
+
});
|
|
1781
|
+
// ── Tool 11: Aggregate (group by) ────────────────────────────────
|
|
1782
|
+
const AGGREGATE_GROUP_BY = [
|
|
1783
|
+
"industry",
|
|
1784
|
+
"municipality",
|
|
1785
|
+
"region",
|
|
1786
|
+
"zipcode",
|
|
1787
|
+
"zipcode_prefix",
|
|
1788
|
+
"company_type",
|
|
1789
|
+
"status",
|
|
1790
|
+
"founded_year",
|
|
1791
|
+
"founded_quarter",
|
|
1792
|
+
"founded_month",
|
|
1793
|
+
"dissolved_year",
|
|
1794
|
+
"dissolved_quarter",
|
|
1795
|
+
"dissolved_month",
|
|
1796
|
+
"employees_bucket",
|
|
1797
|
+
"has_financials",
|
|
1798
|
+
];
|
|
1799
|
+
server.registerTool("firmaapi_aggregate", {
|
|
1800
|
+
title: "Aggreger virksomheder pr. gruppe",
|
|
1801
|
+
description: `T\u00e6l hvordan virksomheder fordeler sig p\u00e5 fx branche, kommune, selskabsform eller stiftelses\u00e5r.
|
|
1802
|
+
Returnerer top-N grupper sorteret efter antal. Tager samme filtre som firmaapi_advanced_search.
|
|
1803
|
+
|
|
1804
|
+
Mindst \u00e9t filter er p\u00e5kr\u00e6vet, fx status="Aktiv".
|
|
1805
|
+
|
|
1806
|
+
group_by-v\u00e6rdier:
|
|
1807
|
+
- industry: branchekode (DB07)
|
|
1808
|
+
- municipality: kommunekode
|
|
1809
|
+
- region: dansk region (Hovedstaden, Sj\u00e6lland, Syddanmark, Midtjylland, Nordjylland)
|
|
1810
|
+
- zipcode: fuldt postnummer (top_n op til 1200 for hele landet)
|
|
1811
|
+
- zipcode_prefix: f\u00f8rste 2 cifre af postnummer (geografisk omr\u00e5de)
|
|
1812
|
+
- company_type: selskabsform som lang CVR-betegnelse (Anpartsselskab, Aktieselskab, ...)
|
|
1813
|
+
- status: virksomhedsstatus
|
|
1814
|
+
- founded_year / founded_quarter / founded_month: stiftelsesperiode
|
|
1815
|
+
- dissolved_year / dissolved_quarter / dissolved_month: opl\u00f8sningsperiode
|
|
1816
|
+
- employees_bucket: solo / mikro / lille / mellem / stor
|
|
1817
|
+
- has_financials: med/uden regnskabsdata
|
|
1818
|
+
|
|
1819
|
+
Eksempler:
|
|
1820
|
+
- "Top 20 brancher med flest aktive virksomheder" → group_by="industry", status="Aktiv"
|
|
1821
|
+
- "Stiftede pr. år i København" → group_by="founded_year", city="København"
|
|
1822
|
+
- "Selskabsformer med over 50M omsætning" → group_by="company_type", revenue_min=50000000
|
|
1823
|
+
|
|
1824
|
+
Truncation: Hvis output rammer 25.000-tegns budget, indsnævr filtrene
|
|
1825
|
+
eller reducer top_n.
|
|
1826
|
+
|
|
1827
|
+
${PLAN.any} revenue_min/capital_min-filtre kræver Standard+ for at virke (filtrerer
|
|
1828
|
+
selskaber med regnskab); andre group_by-værdier virker på alle planer.`,
|
|
1829
|
+
inputSchema: {
|
|
1830
|
+
...SHARED_SEARCH_FILTERS,
|
|
1831
|
+
group_by: z.enum(AGGREGATE_GROUP_BY).describe("Hvilken dimension der grupperes p\u00e5"),
|
|
1832
|
+
top_n: z.number().int().min(1).max(1200).default(20).describe("Maks antal grupper i output (1-200, op til 1200 for group_by=zipcode)"),
|
|
1833
|
+
format: FORMAT_SCHEMA,
|
|
1834
|
+
},
|
|
1835
|
+
annotations: {
|
|
1836
|
+
readOnlyHint: true,
|
|
1837
|
+
destructiveHint: false,
|
|
1838
|
+
idempotentHint: true,
|
|
1839
|
+
openWorldHint: true,
|
|
1840
|
+
},
|
|
1841
|
+
}, async (params) => {
|
|
1842
|
+
try {
|
|
1843
|
+
const { format, group_by, top_n, ...filters } = params;
|
|
1844
|
+
const filterDescriptions = describeFilters(filters);
|
|
1845
|
+
const meaningfulFilters = filterDescriptions.filter((d) => d !== "q=*");
|
|
1846
|
+
if (meaningfulFilters.length === 0) {
|
|
1847
|
+
return {
|
|
1848
|
+
content: [
|
|
1849
|
+
{
|
|
1850
|
+
type: "text",
|
|
1851
|
+
text: "Fejl: Mindst \u00e9t reelt filter er p\u00e5kr\u00e6vet (q=* alene t\u00e6ller ikke).",
|
|
1852
|
+
},
|
|
1853
|
+
],
|
|
1854
|
+
isError: true,
|
|
1855
|
+
};
|
|
1856
|
+
}
|
|
1857
|
+
const apiParams = {
|
|
1858
|
+
...filters,
|
|
1859
|
+
group_by,
|
|
1860
|
+
top_n: top_n ?? 20,
|
|
1861
|
+
};
|
|
1862
|
+
const data = await apiRequest(`/search/aggregate`, apiParams);
|
|
1863
|
+
if (format === "json")
|
|
1864
|
+
return jsonText(data);
|
|
1865
|
+
const lines = [
|
|
1866
|
+
`# Aggregering: ${data.group_by}`,
|
|
1867
|
+
`Filtre: ${filterDescriptions.join(", ")}`,
|
|
1868
|
+
`Total matches: ${data.total_matches.toLocaleString("da-DK")} fordelt p\u00e5 ${data.total_groups.toLocaleString("da-DK")} grupper`,
|
|
1869
|
+
`Viser top ${data.results.length}`,
|
|
1870
|
+
"",
|
|
1871
|
+
];
|
|
1872
|
+
for (const r of data.results) {
|
|
1873
|
+
const label = r.key === null ? "(ukendt)" : r.key;
|
|
1874
|
+
const share = data.total_matches > 0 ? ` (${(r.count / data.total_matches * 100).toFixed(1)}%)` : "";
|
|
1875
|
+
lines.push(`- **${label}**: ${r.count.toLocaleString("da-DK")}${share}`);
|
|
1876
|
+
}
|
|
1877
|
+
if (data.total_groups > data.results.length) {
|
|
1878
|
+
lines.push("", `*${(data.total_groups - data.results.length).toLocaleString("da-DK")} yderligere grupper er udeladt. \u00d8g top_n for at se flere.*`);
|
|
1879
|
+
}
|
|
1880
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1881
|
+
}
|
|
1882
|
+
catch (error) {
|
|
1883
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1884
|
+
}
|
|
1885
|
+
});
|
|
1886
|
+
// ── Tool 12: Timeseries ──────────────────────────────────────────
|
|
1887
|
+
const TIMESERIES_GRANULARITY = ["day", "week", "month", "quarter", "year"];
|
|
1888
|
+
const TIMESERIES_DATE_FIELD = ["founded", "dissolved"];
|
|
1889
|
+
server.registerTool("firmaapi_timeseries", {
|
|
1890
|
+
title: "Tidsserie over stiftelser",
|
|
1891
|
+
description: `Returnerer antal virksomheder pr. tidsbucket (m\u00e5ned, kvartal, \u00e5r m.fl.) baseret p\u00e5 stiftelsesdato.
|
|
1892
|
+
Tager samme filtre som firmaapi_advanced_search. Mindst \u00e9t filter er p\u00e5kr\u00e6vet.
|
|
1893
|
+
|
|
1894
|
+
Bruges til at finde brancher i v\u00e6kst, sammenligne perioder, eller visualisere udvikling.
|
|
1895
|
+
|
|
1896
|
+
Eksempler:
|
|
1897
|
+
- "Stiftelser pr. måned i 2024 i IT-branchen" → granularity="month", industry="62", from="2024-01-01", to="2024-12-31"
|
|
1898
|
+
- "Aktive selskaber stiftet pr. år" → granularity="year", status="Aktiv"
|
|
1899
|
+
- "Stiftelser pr. kvartal i København" → granularity="quarter", city="København"
|
|
1900
|
+
- "Konkurser pr. måned" → date_field="dissolved", granularity="month"
|
|
1901
|
+
|
|
1902
|
+
Truncation: For brede tidsspand kan output blive afkortet — typisk grænser:
|
|
1903
|
+
~600 day-buckets, ~200 month-buckets, ~150 year-buckets. Indsnævr from/to
|
|
1904
|
+
eller vælg grovere granularity hvis serien afkortes.
|
|
1905
|
+
|
|
1906
|
+
date_field-semantik:
|
|
1907
|
+
- 'founded' tæller stiftelser pr. periode (positivt vækstmål)
|
|
1908
|
+
- 'dissolved' tæller opløsninger/konkurser pr. periode (afgangsmål)
|
|
1909
|
+
|
|
1910
|
+
${PLAN.any}`,
|
|
1911
|
+
inputSchema: {
|
|
1912
|
+
...SHARED_SEARCH_FILTERS,
|
|
1913
|
+
date_field: z.enum(TIMESERIES_DATE_FIELD).default("founded").describe("Hvilket datofelt der bucketes p\u00e5: 'founded' (stiftelse) eller 'dissolved' (opl\u00f8sning)"),
|
|
1914
|
+
granularity: z.enum(TIMESERIES_GRANULARITY).default("month").describe("Bucket-st\u00f8rrelse"),
|
|
1915
|
+
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "from skal v\u00e6re YYYY-MM-DD").optional().describe("Tidligste dato (YYYY-MM-DD)"),
|
|
1916
|
+
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "to skal v\u00e6re YYYY-MM-DD").optional().describe("Seneste dato (YYYY-MM-DD)"),
|
|
1917
|
+
format: FORMAT_SCHEMA,
|
|
1918
|
+
},
|
|
1919
|
+
annotations: {
|
|
1920
|
+
readOnlyHint: true,
|
|
1921
|
+
destructiveHint: false,
|
|
1922
|
+
idempotentHint: true,
|
|
1923
|
+
openWorldHint: true,
|
|
1924
|
+
},
|
|
1925
|
+
}, async (params) => {
|
|
1926
|
+
try {
|
|
1927
|
+
const { format, date_field, granularity, from, to, ...filters } = params;
|
|
1928
|
+
const filterDescriptions = describeFilters(filters);
|
|
1929
|
+
const meaningfulFilters = filterDescriptions.filter((d) => d !== "q=*");
|
|
1930
|
+
if (meaningfulFilters.length === 0 && !from && !to) {
|
|
1931
|
+
return {
|
|
1932
|
+
content: [
|
|
1933
|
+
{
|
|
1934
|
+
type: "text",
|
|
1935
|
+
text: "Fejl: Mindst \u00e9t reelt filter er p\u00e5kr\u00e6vet (status, industry, from/to mv.).",
|
|
1936
|
+
},
|
|
1937
|
+
],
|
|
1938
|
+
isError: true,
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
const apiParams = {
|
|
1942
|
+
...filters,
|
|
1943
|
+
date_field: date_field ?? "founded",
|
|
1944
|
+
granularity: granularity ?? "month",
|
|
1945
|
+
from,
|
|
1946
|
+
to,
|
|
1947
|
+
};
|
|
1948
|
+
const data = await apiRequest(`/search/timeseries`, apiParams);
|
|
1949
|
+
if (format === "json")
|
|
1950
|
+
return jsonText(data);
|
|
1951
|
+
const periodParts = [];
|
|
1952
|
+
if (data.from)
|
|
1953
|
+
periodParts.push(`fra ${data.from}`);
|
|
1954
|
+
if (data.to)
|
|
1955
|
+
periodParts.push(`til ${data.to}`);
|
|
1956
|
+
const periodText = periodParts.length ? ` (${periodParts.join(" ")})` : "";
|
|
1957
|
+
const lines = [
|
|
1958
|
+
`# Tidsserie: ${data.date_field}, ${data.granularity}${periodText}`,
|
|
1959
|
+
`Filtre: ${filterDescriptions.length ? filterDescriptions.join(", ") : "ingen"}`,
|
|
1960
|
+
`Total: ${data.total_matches.toLocaleString("da-DK")} fordelt p\u00e5 ${data.bucket_count.toLocaleString("da-DK")} buckets`,
|
|
1961
|
+
"",
|
|
1962
|
+
];
|
|
1963
|
+
for (const r of data.results) {
|
|
1964
|
+
const label = r.bucket ?? "(ukendt)";
|
|
1965
|
+
lines.push(`- ${label}: ${r.count.toLocaleString("da-DK")}`);
|
|
1966
|
+
}
|
|
1967
|
+
if (data.truncated) {
|
|
1968
|
+
lines.push("", "\u26a0\ufe0f Tidsserien er afkortet. Indsn\u00e6vr perioden med from/to eller v\u00e6lg en grovere granularity.");
|
|
1969
|
+
}
|
|
1970
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
1971
|
+
}
|
|
1972
|
+
catch (error) {
|
|
1973
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
1974
|
+
}
|
|
1975
|
+
});
|
|
1976
|
+
const NET_GROWTH_GRANULARITY = ["month", "quarter", "year"];
|
|
1977
|
+
server.registerTool("firmaapi_net_growth", {
|
|
1978
|
+
title: "Netto-vækst (stiftelser minus opløsninger)",
|
|
1979
|
+
description: `Returnerer pr. tidsbucket: antal stiftelser, antal opløsninger og netto-vækst (stiftelser - opløsninger).
|
|
1980
|
+
Tager samme filtre som firmaapi_advanced_search (industry, municipality, city, employees osv.), men status-filteret ignoreres
|
|
1981
|
+
fordi opløsningstællingen pr. definition er 0 for status=Aktiv.
|
|
1982
|
+
|
|
1983
|
+
Bruges til at se hvilke brancher/byer der vokser eller skrumper netto over tid.
|
|
1984
|
+
|
|
1985
|
+
Eksempler:
|
|
1986
|
+
- "Netto-vækst i IT-branchen pr. år de sidste 10 år" → granularity="year", industry="62", from="2016-01-01"
|
|
1987
|
+
- "Netto-vækst i Aarhus pr. kvartal 2024" → granularity="quarter", city="Aarhus", from="2024-01-01", to="2024-12-31"
|
|
1988
|
+
- "Hvilke kommuner mister flest virksomheder?" → granularity="year", from="2024-01-01" (kombiner med flere kald)
|
|
1989
|
+
|
|
1990
|
+
Vigtige semantik-noter:
|
|
1991
|
+
- **status-filteret IGNORERES** silently fordi en aktiv virksomhed pr.
|
|
1992
|
+
definition ikke kan være opløst. Lad være med at sætte det.
|
|
1993
|
+
- "founded" tæller stiftelser i perioden uanset selskabets nuværende status.
|
|
1994
|
+
- "dissolved" tæller alle former for opløsning (konkurs, likvidation, fusion).
|
|
1995
|
+
|
|
1996
|
+
${PLAN.any}`,
|
|
1997
|
+
inputSchema: {
|
|
1998
|
+
...SHARED_SEARCH_FILTERS,
|
|
1999
|
+
granularity: z.enum(NET_GROWTH_GRANULARITY).default("year").describe("Bucket-st\u00f8rrelse"),
|
|
2000
|
+
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "from skal v\u00e6re YYYY-MM-DD").optional().describe("Tidligste dato (YYYY-MM-DD)"),
|
|
2001
|
+
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "to skal v\u00e6re YYYY-MM-DD").optional().describe("Seneste dato (YYYY-MM-DD)"),
|
|
2002
|
+
format: FORMAT_SCHEMA,
|
|
2003
|
+
},
|
|
2004
|
+
annotations: {
|
|
2005
|
+
readOnlyHint: true,
|
|
2006
|
+
destructiveHint: false,
|
|
2007
|
+
idempotentHint: true,
|
|
2008
|
+
openWorldHint: true,
|
|
2009
|
+
},
|
|
2010
|
+
}, async (params) => {
|
|
2011
|
+
try {
|
|
2012
|
+
const { format, granularity, from, to, ...filters } = params;
|
|
2013
|
+
const filterDescriptions = describeFilters(filters);
|
|
2014
|
+
const meaningfulFilters = filterDescriptions.filter((d) => d !== "q=*");
|
|
2015
|
+
if (meaningfulFilters.length === 0 && !from && !to) {
|
|
2016
|
+
return {
|
|
2017
|
+
content: [
|
|
2018
|
+
{
|
|
2019
|
+
type: "text",
|
|
2020
|
+
text: "Fejl: Mindst \u00e9t reelt filter er p\u00e5kr\u00e6vet (industry, municipality, from/to mv.).",
|
|
2021
|
+
},
|
|
2022
|
+
],
|
|
2023
|
+
isError: true,
|
|
2024
|
+
};
|
|
2025
|
+
}
|
|
2026
|
+
const apiParams = {
|
|
2027
|
+
...filters,
|
|
2028
|
+
granularity: granularity ?? "year",
|
|
2029
|
+
from,
|
|
2030
|
+
to,
|
|
2031
|
+
};
|
|
2032
|
+
const data = await apiRequest(`/search/net-growth`, apiParams);
|
|
2033
|
+
if (format === "json")
|
|
2034
|
+
return jsonText(data);
|
|
2035
|
+
const periodParts = [];
|
|
2036
|
+
if (data.from)
|
|
2037
|
+
periodParts.push(`fra ${data.from}`);
|
|
2038
|
+
if (data.to)
|
|
2039
|
+
periodParts.push(`til ${data.to}`);
|
|
2040
|
+
const periodText = periodParts.length ? ` (${periodParts.join(" ")})` : "";
|
|
2041
|
+
const fmt = (n) => n.toLocaleString("da-DK");
|
|
2042
|
+
const signedFmt = (n) => (n > 0 ? `+${fmt(n)}` : fmt(n));
|
|
2043
|
+
const lines = [
|
|
2044
|
+
`# Netto-v\u00e6kst: ${data.granularity}${periodText}`,
|
|
2045
|
+
`Filtre: ${filterDescriptions.length ? filterDescriptions.join(", ") : "ingen"}`,
|
|
2046
|
+
`Total: ${fmt(data.totals.founded)} stiftet, ${fmt(data.totals.dissolved)} opl\u00f8st, netto ${signedFmt(data.totals.net_growth)}`,
|
|
2047
|
+
"",
|
|
2048
|
+
"| Periode | Stiftet | Opl\u00f8st | Netto |",
|
|
2049
|
+
"|---|---:|---:|---:|",
|
|
2050
|
+
];
|
|
2051
|
+
for (const r of data.results) {
|
|
2052
|
+
lines.push(`| ${r.bucket} | ${fmt(r.founded)} | ${fmt(r.dissolved)} | ${signedFmt(r.net_growth)} |`);
|
|
2053
|
+
}
|
|
2054
|
+
if (data.truncated) {
|
|
2055
|
+
lines.push("", "\u26a0\ufe0f Serien er afkortet. Indsn\u00e6vr perioden med from/to eller v\u00e6lg en grovere granularity.");
|
|
2056
|
+
}
|
|
2057
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2058
|
+
}
|
|
2059
|
+
catch (error) {
|
|
2060
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2061
|
+
}
|
|
2062
|
+
});
|
|
2063
|
+
registerFactualTools(server, (path, params) => apiRequest(path, params));
|
|
2064
|
+
// ── Tool 15: Compare companies side-by-side ──────────────────────
|
|
2065
|
+
server.registerTool("firmaapi_compare_companies", {
|
|
2066
|
+
title: "Sammenlign 2-4 virksomheder side-by-side",
|
|
2067
|
+
description: `Fetch 2-4 virksomheder samtidig og render en side-by-side sammenligning af stamdata + nøgletal + seneste regnskab.
|
|
2068
|
+
|
|
2069
|
+
Brug ved benchmarking, M&A-screening eller "hvilken konkurrent er størst".
|
|
2070
|
+
|
|
2071
|
+
Returnerer 17 metrics som markdown-tabel:
|
|
2072
|
+
- Stamdata: status, selskabsform, branche, stiftet, ansatte, by, kapital, børsnoteret
|
|
2073
|
+
- Seneste årsregnskab: regnskabsår, omsætning, bruttofortjeneste, resultat,
|
|
2074
|
+
egenkapital, aktiver i alt
|
|
2075
|
+
- Nøgletal: profit margin, soliditet, ROE
|
|
2076
|
+
- Vækst: YoY omsætning
|
|
2077
|
+
|
|
2078
|
+
Args:
|
|
2079
|
+
- cvr_numbers (string): Kommasepareret liste af 2-4 CVR-numre (anbefal 2-3
|
|
2080
|
+
for læsbarhed; 4 selskaber giver bred tabel)
|
|
2081
|
+
- format (markdown|json)
|
|
2082
|
+
|
|
2083
|
+
Eksempler:
|
|
2084
|
+
- "Sammenlign Novo og LEGO" → cvr_numbers="24256790,47458714"
|
|
2085
|
+
- "Hvem er størst af 12345678, 87654321, 11223344?" → cvr_numbers="12345678,87654321,11223344"
|
|
2086
|
+
|
|
2087
|
+
${PLAN.standard} På Gratis/Basis vises kun stamdata (regnskabskolonner bliver tomme).`,
|
|
2088
|
+
inputSchema: {
|
|
2089
|
+
cvr_numbers: z
|
|
2090
|
+
.string()
|
|
2091
|
+
.describe("Kommasepareret liste af 2-4 CVR-numre"),
|
|
2092
|
+
format: FORMAT_SCHEMA,
|
|
2093
|
+
},
|
|
2094
|
+
annotations: {
|
|
2095
|
+
readOnlyHint: true,
|
|
2096
|
+
destructiveHint: false,
|
|
2097
|
+
idempotentHint: true,
|
|
2098
|
+
openWorldHint: true,
|
|
2099
|
+
},
|
|
2100
|
+
}, async ({ cvr_numbers, format }) => {
|
|
2101
|
+
try {
|
|
2102
|
+
const cvrList = cvr_numbers
|
|
2103
|
+
.split(",")
|
|
2104
|
+
.map((s) => s.trim())
|
|
2105
|
+
.filter((s) => /^\d{8}$/.test(s));
|
|
2106
|
+
if (cvrList.length < 2) {
|
|
2107
|
+
return {
|
|
2108
|
+
content: [{ type: "text", text: "Fejl: Angiv mindst 2 gyldige CVR-numre (8 cifre, kommasepareret)." }],
|
|
2109
|
+
isError: true,
|
|
2110
|
+
};
|
|
2111
|
+
}
|
|
2112
|
+
if (cvrList.length > 4) {
|
|
2113
|
+
return {
|
|
2114
|
+
content: [{ type: "text", text: "Fejl: Maks 4 CVR-numre kan sammenlignes ad gangen." }],
|
|
2115
|
+
isError: true,
|
|
2116
|
+
};
|
|
2117
|
+
}
|
|
2118
|
+
// Hent alle parallelt
|
|
2119
|
+
const results = await Promise.all(cvrList.map((cvr) => apiRequest(`/company/${cvr}`, { include: "finance" })
|
|
2120
|
+
.then((data) => ({ cvr, data, error: null }))
|
|
2121
|
+
.catch((err) => ({ cvr, data: null, error: handleApiError(err) }))));
|
|
2122
|
+
const successful = results.filter((r) => r.data !== null);
|
|
2123
|
+
const failed = results.filter((r) => r.data === null);
|
|
2124
|
+
if (format === "json") {
|
|
2125
|
+
return jsonText({
|
|
2126
|
+
comparison: successful.map((r) => r.data),
|
|
2127
|
+
errors: failed.map((r) => ({ cvr: r.cvr, error: r.error })),
|
|
2128
|
+
});
|
|
2129
|
+
}
|
|
2130
|
+
if (successful.length === 0) {
|
|
2131
|
+
return {
|
|
2132
|
+
content: [{ type: "text", text: `Kunne ikke hente nogen af de angivne CVR'er.\n\n${failed.map((f) => `- ${f.cvr}: ${f.error}`).join("\n")}` }],
|
|
2133
|
+
isError: true,
|
|
2134
|
+
};
|
|
2135
|
+
}
|
|
2136
|
+
const lines = [];
|
|
2137
|
+
lines.push(`# Sammenligning af ${successful.length} virksomheder`);
|
|
2138
|
+
lines.push("");
|
|
2139
|
+
const latestFinancial = (c) => {
|
|
2140
|
+
const fin = c.financials;
|
|
2141
|
+
return fin?.length ? fin[fin.length - 1] : null;
|
|
2142
|
+
};
|
|
2143
|
+
const metrics = [
|
|
2144
|
+
{ label: "Status", get: (c) => String(c.status || "—") },
|
|
2145
|
+
{ label: "Selskabsform", get: (c) => String(c.company_type || "—") },
|
|
2146
|
+
{ label: "Branche", get: (c) => `${c.industry_text || "—"}${c.industry_code ? ` (${c.industry_code})` : ""}` },
|
|
2147
|
+
{ label: "Stiftet", get: (c) => String(c.founded || "—") },
|
|
2148
|
+
{ label: "Ansatte", get: (c) => String(c.employees || "—") },
|
|
2149
|
+
{ label: "By", get: (c) => `${c.zipcode || ""} ${c.city || ""}`.trim() || "—" },
|
|
2150
|
+
{ label: "Kapital", get: (c) => (c.capital != null ? dkk(c.capital) : "—") },
|
|
2151
|
+
{ label: "Børsnoteret", get: (c) => (c.is_listed === true ? "Ja" : "Nej") },
|
|
2152
|
+
{
|
|
2153
|
+
label: "Seneste regnskabsår",
|
|
2154
|
+
get: (c) => {
|
|
2155
|
+
const f = latestFinancial(c);
|
|
2156
|
+
return f ? String(f.year) : "—";
|
|
2157
|
+
},
|
|
2158
|
+
},
|
|
2159
|
+
{
|
|
2160
|
+
label: "Omsætning",
|
|
2161
|
+
get: (c) => {
|
|
2162
|
+
const f = latestFinancial(c);
|
|
2163
|
+
return f?.revenue != null ? dkk(f.revenue) : "—";
|
|
2164
|
+
},
|
|
2165
|
+
},
|
|
2166
|
+
{
|
|
2167
|
+
label: "Bruttofortjeneste",
|
|
2168
|
+
get: (c) => {
|
|
2169
|
+
const f = latestFinancial(c);
|
|
2170
|
+
return f?.gross_profit != null ? dkk(f.gross_profit) : "—";
|
|
2171
|
+
},
|
|
2172
|
+
},
|
|
2173
|
+
{
|
|
2174
|
+
label: "Resultat",
|
|
2175
|
+
get: (c) => {
|
|
2176
|
+
const f = latestFinancial(c);
|
|
2177
|
+
return f?.net_profit != null ? dkk(f.net_profit) : "—";
|
|
2178
|
+
},
|
|
2179
|
+
},
|
|
2180
|
+
{
|
|
2181
|
+
label: "Egenkapital",
|
|
2182
|
+
get: (c) => {
|
|
2183
|
+
const f = latestFinancial(c);
|
|
2184
|
+
return f?.equity != null ? dkk(f.equity) : "—";
|
|
2185
|
+
},
|
|
2186
|
+
},
|
|
2187
|
+
{
|
|
2188
|
+
label: "Aktiver i alt",
|
|
2189
|
+
get: (c) => {
|
|
2190
|
+
const f = latestFinancial(c);
|
|
2191
|
+
return f?.total_assets != null ? dkk(f.total_assets) : "—";
|
|
2192
|
+
},
|
|
2193
|
+
},
|
|
2194
|
+
{
|
|
2195
|
+
label: "Profit margin",
|
|
2196
|
+
get: (c) => {
|
|
2197
|
+
const f = latestFinancial(c);
|
|
2198
|
+
const r = f?.ratios;
|
|
2199
|
+
return r?.profit_margin != null ? pct(r.profit_margin) : "—";
|
|
2200
|
+
},
|
|
2201
|
+
},
|
|
2202
|
+
{
|
|
2203
|
+
label: "Soliditet",
|
|
2204
|
+
get: (c) => {
|
|
2205
|
+
const f = latestFinancial(c);
|
|
2206
|
+
const r = f?.ratios;
|
|
2207
|
+
return r?.solvency_ratio != null ? pct(r.solvency_ratio) : "—";
|
|
2208
|
+
},
|
|
2209
|
+
},
|
|
2210
|
+
{
|
|
2211
|
+
label: "ROE",
|
|
2212
|
+
get: (c) => {
|
|
2213
|
+
const f = latestFinancial(c);
|
|
2214
|
+
const r = f?.ratios;
|
|
2215
|
+
return r?.return_on_equity != null ? pct(r.return_on_equity) : "—";
|
|
2216
|
+
},
|
|
2217
|
+
},
|
|
2218
|
+
{
|
|
2219
|
+
label: "Vækst (omsætning YoY)",
|
|
2220
|
+
get: (c) => {
|
|
2221
|
+
const f = latestFinancial(c);
|
|
2222
|
+
const g = f?.growth;
|
|
2223
|
+
return g?.revenue_yoy != null ? pct(g.revenue_yoy) : "—";
|
|
2224
|
+
},
|
|
2225
|
+
},
|
|
2226
|
+
];
|
|
2227
|
+
// Markdown table — virksomheder som kolonner, metrics som rækker
|
|
2228
|
+
const headers = ["Felt", ...successful.map((r) => `${r.data.name} (${r.cvr})`)];
|
|
2229
|
+
lines.push(`| ${headers.join(" | ")} |`);
|
|
2230
|
+
lines.push(`| ${headers.map(() => "---").join(" | ")} |`);
|
|
2231
|
+
for (const m of metrics) {
|
|
2232
|
+
const row = [m.label, ...successful.map((r) => m.get(r.data))];
|
|
2233
|
+
lines.push(`| ${row.join(" | ")} |`);
|
|
2234
|
+
}
|
|
2235
|
+
if (failed.length) {
|
|
2236
|
+
lines.push("");
|
|
2237
|
+
lines.push("### Kunne ikke hentes");
|
|
2238
|
+
for (const f of failed)
|
|
2239
|
+
lines.push(`- CVR ${f.cvr}: ${f.error}`);
|
|
2240
|
+
}
|
|
2241
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2242
|
+
}
|
|
2243
|
+
catch (error) {
|
|
2244
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2245
|
+
}
|
|
2246
|
+
});
|
|
2247
|
+
// ── Tool 16: Ownership tree ───────────────────────────────────────
|
|
2248
|
+
server.registerTool("firmaapi_ownership_tree", {
|
|
2249
|
+
title: "Rekursiv ejerskabskæde for en virksomhed",
|
|
2250
|
+
description: `Spor moderselskaber opad eller datterselskaber nedad gennem flere niveauer
|
|
2251
|
+
i en koncernstruktur.
|
|
2252
|
+
|
|
2253
|
+
Vis registrerede ejerrelationer. Ejerkæden identificerer ikke i sig selv reelle ejere.
|
|
2254
|
+
Brug firmaapi_ultimate_owners til beregnede effektive ejerandele for fysiske personer (op til 10 niveauer).
|
|
2255
|
+
|
|
2256
|
+
Implementation:
|
|
2257
|
+
- BFS-traversering per direction
|
|
2258
|
+
- Cycle-prevention via visited-set (krydsejerskaber giver ikke uendelig løkke)
|
|
2259
|
+
- **Call-budget på 80 API-calls** pr. invocation. Ved store koncerner (10+
|
|
2260
|
+
datterselskaber pr. niveau på dybde 3+) ramme grænsen — output viser
|
|
2261
|
+
⚠️-banner og budget_exceeded=true. Reducér da max_depth eller direction.
|
|
2262
|
+
|
|
2263
|
+
Args:
|
|
2264
|
+
- cvr (string): 8-cifret start-CVR
|
|
2265
|
+
- direction (up|down|both): 'up' = moderselskaber, 'down' = datterselskaber,
|
|
2266
|
+
'both' = begge (default)
|
|
2267
|
+
- max_depth (int 1-4): maksimal rekursionsdybde. Default 2.
|
|
2268
|
+
- format (markdown|json)
|
|
2269
|
+
|
|
2270
|
+
Eksempler:
|
|
2271
|
+
- "Hvem ejer KIRKBI A/S?" → cvr="...", direction="up", max_depth=3
|
|
2272
|
+
- "Hvilke datterselskaber har KIRKBI?" → cvr="...", direction="down"
|
|
2273
|
+
- "Vis fuld koncernkort" → direction="both", max_depth=3
|
|
2274
|
+
|
|
2275
|
+
${PLAN.pro} Ved manglende adgang til relationer returneres 403.`,
|
|
2276
|
+
inputSchema: {
|
|
2277
|
+
cvr: z.string().regex(/^\d{8}$/).describe("8-cifret CVR-nummer som startpunkt"),
|
|
2278
|
+
direction: z.enum(["up", "down", "both"]).optional().describe("Default 'both'"),
|
|
2279
|
+
max_depth: z.number().int().min(1).max(4).optional().describe("Default 2"),
|
|
2280
|
+
format: FORMAT_SCHEMA,
|
|
2281
|
+
},
|
|
2282
|
+
annotations: {
|
|
2283
|
+
readOnlyHint: true,
|
|
2284
|
+
destructiveHint: false,
|
|
2285
|
+
idempotentHint: true,
|
|
2286
|
+
openWorldHint: true,
|
|
2287
|
+
},
|
|
2288
|
+
}, async ({ cvr, direction, max_depth, format }) => {
|
|
2289
|
+
try {
|
|
2290
|
+
const dir = direction || "both";
|
|
2291
|
+
const maxDepth = max_depth || 2;
|
|
2292
|
+
// BFS expansion with call budget — large groups can have hundreds of
|
|
2293
|
+
// entities, and at max_depth=4 a fan-out of 5/node would spawn 625 API
|
|
2294
|
+
// calls. We cap total calls at MAX_CALLS and surface partial results.
|
|
2295
|
+
const MAX_CALLS = 80;
|
|
2296
|
+
let callCount = 0;
|
|
2297
|
+
let budgetExceeded = false;
|
|
2298
|
+
const errors = [];
|
|
2299
|
+
const visited = new Set([cvr]);
|
|
2300
|
+
const root = await apiRequest(`/company/${cvr}`, { include: "relations" });
|
|
2301
|
+
callCount++;
|
|
2302
|
+
const rootName = String(root.name || cvr);
|
|
2303
|
+
const tree = { up: [], down: [] };
|
|
2304
|
+
async function expand(currentCvr, depth, side) {
|
|
2305
|
+
if (depth > maxDepth)
|
|
2306
|
+
return;
|
|
2307
|
+
if (callCount >= MAX_CALLS) {
|
|
2308
|
+
budgetExceeded = true;
|
|
2309
|
+
return;
|
|
2310
|
+
}
|
|
2311
|
+
let data;
|
|
2312
|
+
try {
|
|
2313
|
+
data = await apiRequest(`/company/${currentCvr}`, { include: "relations" });
|
|
2314
|
+
callCount++;
|
|
2315
|
+
}
|
|
2316
|
+
catch (err) {
|
|
2317
|
+
errors.push({ cvr: currentCvr, error: handleApiError(err) });
|
|
2318
|
+
return;
|
|
2319
|
+
}
|
|
2320
|
+
const relations = data.relations;
|
|
2321
|
+
if (!relations)
|
|
2322
|
+
return;
|
|
2323
|
+
const list = side === "up" ? relations.parents || [] : relations.subsidiaries || [];
|
|
2324
|
+
for (const rel of list) {
|
|
2325
|
+
const relCvr = rel.cvr;
|
|
2326
|
+
if (!relCvr || visited.has(relCvr))
|
|
2327
|
+
continue;
|
|
2328
|
+
visited.add(relCvr);
|
|
2329
|
+
const node = {
|
|
2330
|
+
cvr: relCvr,
|
|
2331
|
+
name: String(rel.name || "?"),
|
|
2332
|
+
depth,
|
|
2333
|
+
relation: side === "up" ? "parent" : "subsidiary",
|
|
2334
|
+
share: rel.ownership_share ?? rel.control_share ?? null,
|
|
2335
|
+
};
|
|
2336
|
+
tree[side].push(node);
|
|
2337
|
+
await expand(relCvr, depth + 1, side);
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
// Sequential rather than Promise.all — keeps the budget meaningful and
|
|
2341
|
+
// avoids spamming the API with concurrent calls.
|
|
2342
|
+
if (dir === "up" || dir === "both")
|
|
2343
|
+
await expand(cvr, 1, "up");
|
|
2344
|
+
if (dir === "down" || dir === "both")
|
|
2345
|
+
await expand(cvr, 1, "down");
|
|
2346
|
+
if (format === "json") {
|
|
2347
|
+
return jsonText({
|
|
2348
|
+
root: { cvr, name: rootName },
|
|
2349
|
+
max_depth: maxDepth,
|
|
2350
|
+
calls_made: callCount,
|
|
2351
|
+
budget_exceeded: budgetExceeded,
|
|
2352
|
+
errors,
|
|
2353
|
+
...tree,
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
const lines = [`# Ejerskabskæde: ${rootName} (CVR ${cvr})`, ""];
|
|
2357
|
+
if (budgetExceeded) {
|
|
2358
|
+
lines.push(`⚠️ *Resultater er afkortet — tree-traversal nåede ${MAX_CALLS}-call budget. Reducer max_depth eller indsnævr direction.*`, "");
|
|
2359
|
+
}
|
|
2360
|
+
if (errors.length) {
|
|
2361
|
+
lines.push(`⚠️ *${errors.length} CVR-opslag fejlede under traversering.*`, "");
|
|
2362
|
+
}
|
|
2363
|
+
const renderSide = (label, nodes) => {
|
|
2364
|
+
if (!nodes.length) {
|
|
2365
|
+
lines.push(`*Ingen ${label} fundet.*`, "");
|
|
2366
|
+
return;
|
|
2367
|
+
}
|
|
2368
|
+
lines.push(`### ${label}`);
|
|
2369
|
+
const sorted = nodes.sort((a, b) => a.depth - b.depth);
|
|
2370
|
+
for (const n of sorted) {
|
|
2371
|
+
const indent = " ".repeat(n.depth - 1);
|
|
2372
|
+
const sharePart = n.share != null ? ` — ${n.share}%` : "";
|
|
2373
|
+
lines.push(`${indent}- **${n.name}** (CVR ${n.cvr})${sharePart}`);
|
|
2374
|
+
}
|
|
2375
|
+
lines.push("");
|
|
2376
|
+
};
|
|
2377
|
+
if (dir === "up" || dir === "both")
|
|
2378
|
+
renderSide(`Moderselskaber (op til ${maxDepth} niveau${maxDepth > 1 ? "er" : ""})`, tree.up);
|
|
2379
|
+
if (dir === "down" || dir === "both")
|
|
2380
|
+
renderSide(`Datterselskaber (op til ${maxDepth} niveau${maxDepth > 1 ? "er" : ""})`, tree.down);
|
|
2381
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2382
|
+
}
|
|
2383
|
+
catch (error) {
|
|
2384
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2385
|
+
}
|
|
2386
|
+
});
|
|
2387
|
+
function formatOwnershipRange(range) {
|
|
2388
|
+
const f = (v) => v.toLocaleString("da-DK", { maximumFractionDigits: 2 });
|
|
2389
|
+
return range.min === range.max ? `${f(range.min)} %` : `${f(range.min)}-${f(range.max)} %`;
|
|
2390
|
+
}
|
|
2391
|
+
server.registerTool("firmaapi_ultimate_owners", {
|
|
2392
|
+
title: "Beregnede ultimative ejere (effektiv ejerandel gennem ejerkæden)",
|
|
2393
|
+
description: `Følg de legale ejere op gennem ejerkæden (op til 10 niveauer) til fysiske personer, og
|
|
2394
|
+
beregn hver persons effektive ejerandel: produktet af andelene langs kæden, summeret over alle grene.
|
|
2395
|
+
|
|
2396
|
+
VIGTIGT: Resultatet er beregnet af FirmaAPI ud fra de registrerede legale ejere. Det er IKKE
|
|
2397
|
+
Erhvervsstyrelsens register over reelle ejere og skal altid præsenteres som en beregning.
|
|
2398
|
+
|
|
2399
|
+
Sådan læses svaret:
|
|
2400
|
+
- CVR angiver andele i intervaller (fx 25-33,32 %), så effektive andele vises som min-max.
|
|
2401
|
+
- meets_threshold/threshold_status viser om personen når 25 % (met, possible eller not_met).
|
|
2402
|
+
- Grene der ikke ender i en person (udenlandske ejere = ukendt videre ejer, fonde uden ejere,
|
|
2403
|
+
selskaber uden data, dybde- eller loftgrænser) listes separat med årsag.
|
|
2404
|
+
- truncated=true betyder at dybdegrænsen eller loftet på 500 selskaber blev ramt. Resultatet
|
|
2405
|
+
er stadig gyldigt for de fulgte grene.
|
|
2406
|
+
|
|
2407
|
+
Beregningen sker på serveren i ét API-kald (cachet 24 timer), så værktøjet er billigere end at
|
|
2408
|
+
gå kæden igennem med firmaapi_ownership_tree. Data findes kun via API og MCP, ikke på de
|
|
2409
|
+
offentlige virksomhedssider på firmaapi.dk.
|
|
2410
|
+
|
|
2411
|
+
Args:
|
|
2412
|
+
- cvr (string): 8-cifret CVR
|
|
2413
|
+
- max_depth (int 1-10): antal led op ad kæden. Default 10.
|
|
2414
|
+
- limit (int 1-100): maks. antal personer og grene i output. Default 25.
|
|
2415
|
+
- format (markdown|json)
|
|
2416
|
+
|
|
2417
|
+
Eksempler:
|
|
2418
|
+
- "Hvem ejer reelt dette selskab gennem holdingselskaberne?" → cvr="..."
|
|
2419
|
+
- "Har nogen person over 25 % indirekte?" → cvr="...", læs meets_threshold
|
|
2420
|
+
|
|
2421
|
+
**Plan**: Kræver Professionel-plan eller Enterprise. Andre planer får 403 med link til priser.`,
|
|
2422
|
+
inputSchema: {
|
|
2423
|
+
cvr: z.string().regex(/^\d{8}$/).describe("8-cifret CVR-nummer"),
|
|
2424
|
+
max_depth: z.number().int().min(1).max(10).optional().describe("Default 10"),
|
|
2425
|
+
limit: z.number().int().min(1).max(100).optional().describe("Default 25"),
|
|
2426
|
+
format: FORMAT_SCHEMA,
|
|
2427
|
+
},
|
|
2428
|
+
annotations: {
|
|
2429
|
+
readOnlyHint: true,
|
|
2430
|
+
destructiveHint: false,
|
|
2431
|
+
idempotentHint: true,
|
|
2432
|
+
openWorldHint: true,
|
|
2433
|
+
},
|
|
2434
|
+
}, async ({ cvr, max_depth, limit, format }) => {
|
|
2435
|
+
try {
|
|
2436
|
+
const data = await apiRequest(`/company/${cvr}`, {
|
|
2437
|
+
include: "ultimate_owners",
|
|
2438
|
+
max_depth: String(max_depth ?? 10),
|
|
2439
|
+
});
|
|
2440
|
+
const result = data.ultimate_owners;
|
|
2441
|
+
if (!result) {
|
|
2442
|
+
return {
|
|
2443
|
+
content: [{ type: "text", text: "Beregningen af ultimative ejere kunne ikke gennemføres lige nu. Prøv igen senere." }],
|
|
2444
|
+
isError: true,
|
|
2445
|
+
};
|
|
2446
|
+
}
|
|
2447
|
+
const max = limit ?? 25;
|
|
2448
|
+
const persons = result.persons ?? [];
|
|
2449
|
+
const unresolved = result.unresolved ?? [];
|
|
2450
|
+
if (format === "json") {
|
|
2451
|
+
return jsonText({
|
|
2452
|
+
...result,
|
|
2453
|
+
persons: persons.slice(0, max),
|
|
2454
|
+
unresolved: unresolved.slice(0, max),
|
|
2455
|
+
persons_total: persons.length,
|
|
2456
|
+
unresolved_total: unresolved.length + (result.unresolved_omitted ?? 0),
|
|
2457
|
+
});
|
|
2458
|
+
}
|
|
2459
|
+
const lines = [
|
|
2460
|
+
`# Ultimative ejere (beregnet): ${result.name ?? data.name ?? cvr} (CVR ${cvr})`,
|
|
2461
|
+
"",
|
|
2462
|
+
`*${result.disclaimer ?? "Beregnet ud fra legale ejere. Ikke Erhvervsstyrelsens register over reelle ejere."}*`,
|
|
2463
|
+
"",
|
|
2464
|
+
];
|
|
2465
|
+
if (result.truncated) {
|
|
2466
|
+
for (const t of result.truncation ?? [])
|
|
2467
|
+
lines.push(`**Afkortet:** ${t.message}`);
|
|
2468
|
+
lines.push("");
|
|
2469
|
+
}
|
|
2470
|
+
if (persons.length === 0) {
|
|
2471
|
+
lines.push("Ingen fysiske personer fundet i ejerkæden.", "");
|
|
2472
|
+
}
|
|
2473
|
+
else {
|
|
2474
|
+
lines.push(`### Personer (${persons.length})`);
|
|
2475
|
+
lines.push("| Navn | Effektiv ejerandel | 25 %-tærskel | Niveau | Via |");
|
|
2476
|
+
lines.push("| --- | --- | --- | --- | --- |");
|
|
2477
|
+
for (const p of persons.slice(0, max)) {
|
|
2478
|
+
const threshold = p.threshold_status === "met" ? "Ja" : p.threshold_status === "possible" ? "Muligvis" : "Nej";
|
|
2479
|
+
const depth = p.min_chain_depth === p.max_chain_depth ? `${p.min_chain_depth}` : `${p.min_chain_depth}-${p.max_chain_depth}`;
|
|
2480
|
+
const via = p.paths?.[0]?.chain.slice(0, -1).map((link) => link.name).join(" > ") || "direkte";
|
|
2481
|
+
const extra = p.path_count > 1 ? ` (+${p.path_count - 1} stier)` : "";
|
|
2482
|
+
const unknown = p.has_unknown_shares ? " (delvist ukendt)" : "";
|
|
2483
|
+
lines.push(`| ${p.name} | ${formatOwnershipRange(p.effective_ownership_percent)}${unknown} | ${threshold} | ${depth} | ${via}${extra} |`);
|
|
2484
|
+
}
|
|
2485
|
+
if (persons.length > max)
|
|
2486
|
+
lines.push("", `*${persons.length - max} flere personer. Brug limit eller format=json.*`);
|
|
2487
|
+
lines.push("");
|
|
2488
|
+
}
|
|
2489
|
+
if (unresolved.length > 0) {
|
|
2490
|
+
lines.push(`### Grene uden identificeret person (${unresolved.length + (result.unresolved_omitted ?? 0)})`);
|
|
2491
|
+
for (const u of unresolved.slice(0, max)) {
|
|
2492
|
+
lines.push(`- **${u.name}**${u.cvr ? ` (CVR ${u.cvr})` : ""}: ${formatOwnershipRange(u.effective_ownership_percent)}, niveau ${u.min_chain_depth}. ${u.reason_text}`);
|
|
2493
|
+
}
|
|
2494
|
+
lines.push("");
|
|
2495
|
+
}
|
|
2496
|
+
if ((result.cycles ?? []).length > 0) {
|
|
2497
|
+
lines.push("### Krydsejerskaber");
|
|
2498
|
+
for (const c of result.cycles ?? [])
|
|
2499
|
+
lines.push(`- ${c.names.join(" > ")}`);
|
|
2500
|
+
lines.push("");
|
|
2501
|
+
}
|
|
2502
|
+
if (result.cache)
|
|
2503
|
+
lines.push(`*Beregnet ${result.cache.computed_at} (cache: ${result.cache.status}, max_depth ${result.max_depth ?? max_depth ?? 10}).*`);
|
|
2504
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2505
|
+
}
|
|
2506
|
+
catch (error) {
|
|
2507
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2508
|
+
}
|
|
2509
|
+
});
|
|
2510
|
+
// ── Tool 17: Find target companies (lead generation) ─────────────
|
|
2511
|
+
server.registerTool("firmaapi_find_target_companies", {
|
|
2512
|
+
title: "Find prospect-virksomheder (lead generation)",
|
|
2513
|
+
description: `Optimeret til lead generation og B2B-prospecting. Wrapper omkring advanced_search med ICP-venlige defaults:
|
|
2514
|
+
- Kun aktive selskaber (kan overrides via status-filter)
|
|
2515
|
+
- Kun virksomheder med registrerede kontaktoplysninger — vælg kanal med contact_required:
|
|
2516
|
+
'email' (default for 'any'), 'phone', 'website'
|
|
2517
|
+
- Sorteret efter omsætning (default), så største prospects kommer først
|
|
2518
|
+
- Som udgangspunkt ad_protected=false. Filteret dokumenterer ikke samtykke eller lovlig kontakt; beskyttede virksomheder kan søges til andre formål
|
|
2519
|
+
|
|
2520
|
+
Use cases:
|
|
2521
|
+
- "Find IT-selskaber i København med 10-49 ansatte og omsætning >5M"
|
|
2522
|
+
- "Vis aktive ApS'er stiftet 2018-2023 i Region Hovedstaden inden for fitness"
|
|
2523
|
+
- "B2B-leads: regnskabsfirmaer i Aarhus med email"
|
|
2524
|
+
|
|
2525
|
+
Alle advanced_search filtre er understøttet. Returnerer top 25 default sorteret efter omsætning.
|
|
2526
|
+
|
|
2527
|
+
Kræver Basis-plan eller højere.`,
|
|
2528
|
+
inputSchema: {
|
|
2529
|
+
...SHARED_SEARCH_FILTERS,
|
|
2530
|
+
limit: z.number().int().min(1).max(100).optional().describe("Default 25"),
|
|
2531
|
+
contact_required: z.enum(["any", "email", "phone", "website"]).optional().describe("'any' (default) = email ELLER phone, 'email' = kun med email, etc."),
|
|
2532
|
+
format: FORMAT_SCHEMA,
|
|
2533
|
+
fields: FIELDS_SCHEMA,
|
|
2534
|
+
verbose: VERBOSE_SCHEMA,
|
|
2535
|
+
},
|
|
2536
|
+
annotations: {
|
|
2537
|
+
readOnlyHint: true,
|
|
2538
|
+
destructiveHint: false,
|
|
2539
|
+
idempotentHint: true,
|
|
2540
|
+
openWorldHint: true,
|
|
2541
|
+
},
|
|
2542
|
+
}, async ({ limit, contact_required, format, fields, verbose, ...filters }) => {
|
|
2543
|
+
try {
|
|
2544
|
+
const params = {
|
|
2545
|
+
...filters,
|
|
2546
|
+
status: filters.status ?? "Aktiv",
|
|
2547
|
+
// Respect user's ad_protected if explicitly set; default to false
|
|
2548
|
+
// (companies not marked as advertising-protected) for prospecting use case.
|
|
2549
|
+
ad_protected: filters.ad_protected ?? "false",
|
|
2550
|
+
limit: limit ?? 25,
|
|
2551
|
+
};
|
|
2552
|
+
// Default sort by revenue when not explicitly set
|
|
2553
|
+
if (!params.sort)
|
|
2554
|
+
params.sort = "revenue:desc";
|
|
2555
|
+
// Contact filter: API doesn't support OR across columns in a single
|
|
2556
|
+
// call, so we pick the strictest sensible default per option:
|
|
2557
|
+
// - "email" → has_email=true
|
|
2558
|
+
// - "phone" → has_phone=true
|
|
2559
|
+
// - "website" → has_website=true
|
|
2560
|
+
// - "any" → has_email=true (broadest practical filter; email is
|
|
2561
|
+
// the most common B2B prospecting channel)
|
|
2562
|
+
const contact = contact_required || "any";
|
|
2563
|
+
if (contact === "email")
|
|
2564
|
+
params.has_email = true;
|
|
2565
|
+
else if (contact === "phone")
|
|
2566
|
+
params.has_phone = true;
|
|
2567
|
+
else if (contact === "website")
|
|
2568
|
+
params.has_website = true;
|
|
2569
|
+
else
|
|
2570
|
+
params.has_email = true;
|
|
2571
|
+
const data = await apiRequest(`/search/advanced`, params);
|
|
2572
|
+
const results = data.results || [];
|
|
2573
|
+
const contactContext = {
|
|
2574
|
+
consent: "unknown",
|
|
2575
|
+
advertising_protection_filter: params.ad_protected,
|
|
2576
|
+
note: "Registrerede kontaktoplysninger dokumenterer ikke samtykke eller ret til markedsføring.",
|
|
2577
|
+
};
|
|
2578
|
+
if (format === "json") {
|
|
2579
|
+
const selected = selectListFields(results, fields, verbose).map((row, i) => ({ ...row, ad_protected: results[i].ad_protected ?? null }));
|
|
2580
|
+
return jsonText({ ...data, contact_context: contactContext, results: selected });
|
|
2581
|
+
}
|
|
2582
|
+
const lines = [`# Virksomhedsmatches (${results.length})`, "", contactContext.note, ""];
|
|
2583
|
+
const filterDesc = describeFilters(filters);
|
|
2584
|
+
if (filterDesc.length)
|
|
2585
|
+
lines.push(`*Filtre: ${filterDesc.join(", ")}*`, "");
|
|
2586
|
+
if (data.total != null)
|
|
2587
|
+
lines.push(`*Total match: ${data.total.toLocaleString("da-DK")}*`, "");
|
|
2588
|
+
const customFields = !verbose && fields && fields.length > 0;
|
|
2589
|
+
for (const r of results) {
|
|
2590
|
+
if (customFields) {
|
|
2591
|
+
lines.push(formatPickedRow(r, fields));
|
|
2592
|
+
continue;
|
|
2593
|
+
}
|
|
2594
|
+
const parts = [`**${r.name}** (CVR ${r.cvr})`];
|
|
2595
|
+
if (r.city)
|
|
2596
|
+
parts.push(String(r.city));
|
|
2597
|
+
if (r.industry_text)
|
|
2598
|
+
parts.push(String(r.industry_text));
|
|
2599
|
+
if (r.employees)
|
|
2600
|
+
parts.push(`${r.employees} ansatte`);
|
|
2601
|
+
if (r.email)
|
|
2602
|
+
parts.push(`📧 ${r.email}`);
|
|
2603
|
+
if (r.phone)
|
|
2604
|
+
parts.push(`📞 ${r.phone}`);
|
|
2605
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
2606
|
+
}
|
|
2607
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2608
|
+
}
|
|
2609
|
+
catch (error) {
|
|
2610
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2611
|
+
}
|
|
2612
|
+
});
|
|
2613
|
+
// ── Tool 18: Lookalike search ────────────────────────────────────
|
|
2614
|
+
server.registerTool("firmaapi_lookalike_search", {
|
|
2615
|
+
title: "Find virksomheder der ligner en given CVR",
|
|
2616
|
+
description: `Tager én CVR som input og finder lignende virksomheder. Tool'et henter
|
|
2617
|
+
source-selskabet, ekstraherer dets karakteristika og bygger en advanced_search-query.
|
|
2618
|
+
|
|
2619
|
+
Similarity-modes:
|
|
2620
|
+
- **loose**: Kun samme branche-prefix (2 første cifre — fx "62" = alle IT-selskaber).
|
|
2621
|
+
Bredt resultat på tværs af region/størrelse/selskabsform.
|
|
2622
|
+
- **tight** (default): Samme fulde branchekode + samme kommune + samme selskabsform
|
|
2623
|
+
+ employees-bracket på 0.3x til 3x af source-størrelsen. Tæt match.
|
|
2624
|
+
|
|
2625
|
+
Resultat sorteres altid efter omsætning DESC. Source-CVR filtreres ud af resultatet.
|
|
2626
|
+
|
|
2627
|
+
Use cases:
|
|
2628
|
+
- "Find andre selskaber som CVR 24256790"
|
|
2629
|
+
- "Hvilke konkurrenter har samme profil som denne kunde?"
|
|
2630
|
+
- ICP-expansion: "Mine 5 bedste kunder har CVR ABC, DEF, GHI — find lookalikes"
|
|
2631
|
+
|
|
2632
|
+
Args:
|
|
2633
|
+
- cvr (string): 8-cifret source-CVR
|
|
2634
|
+
- limit (int 1-50): antal lookalikes (default 10)
|
|
2635
|
+
- similarity ('tight'|'loose'): default 'tight'
|
|
2636
|
+
|
|
2637
|
+
${PLAN.basis} Sortering efter omsætning kræver Standard+ for at være meningsfuld
|
|
2638
|
+
(uden regnskabsdata sorteres lookalikes vilkårligt).`,
|
|
2639
|
+
inputSchema: {
|
|
2640
|
+
cvr: z.string().regex(/^\d{8}$/).describe("Source-CVR"),
|
|
2641
|
+
limit: z.number().int().min(1).max(50).optional(),
|
|
2642
|
+
similarity: z.enum(["loose", "tight"]).optional(),
|
|
2643
|
+
format: FORMAT_SCHEMA,
|
|
2644
|
+
fields: FIELDS_SCHEMA,
|
|
2645
|
+
verbose: VERBOSE_SCHEMA,
|
|
2646
|
+
},
|
|
2647
|
+
annotations: {
|
|
2648
|
+
readOnlyHint: true,
|
|
2649
|
+
destructiveHint: false,
|
|
2650
|
+
idempotentHint: true,
|
|
2651
|
+
openWorldHint: true,
|
|
2652
|
+
},
|
|
2653
|
+
}, async ({ cvr, limit, similarity, format, fields, verbose }) => {
|
|
2654
|
+
try {
|
|
2655
|
+
const source = await apiRequest(`/company/${cvr}`);
|
|
2656
|
+
const tight = similarity !== "loose";
|
|
2657
|
+
const params = {
|
|
2658
|
+
limit: limit || 10,
|
|
2659
|
+
status: "Aktiv",
|
|
2660
|
+
};
|
|
2661
|
+
// Industry: tight uses full code, loose uses 2-digit prefix
|
|
2662
|
+
const industryCode = source.industry_code;
|
|
2663
|
+
if (industryCode) {
|
|
2664
|
+
params.industry = tight ? industryCode : industryCode.slice(0, 2);
|
|
2665
|
+
}
|
|
2666
|
+
// Company type: only on tight
|
|
2667
|
+
if (tight && source.company_type)
|
|
2668
|
+
params.company_type = String(source.company_type);
|
|
2669
|
+
// Region/municipality: tight uses municipality, loose skips
|
|
2670
|
+
if (tight && source.municipality_code) {
|
|
2671
|
+
params.municipality = String(source.municipality_code);
|
|
2672
|
+
}
|
|
2673
|
+
// Employees: bracket by source size. ERST employees can be exact
|
|
2674
|
+
// ("42"), a range ("10-49"), a min-only ("10+"), or a CVR-bracket-code
|
|
2675
|
+
// ("ANTAL_10_19"). We extract a representative number from each form.
|
|
2676
|
+
const employees = source.employees;
|
|
2677
|
+
if (tight && employees) {
|
|
2678
|
+
let baseN = null;
|
|
2679
|
+
const rangeMatch = employees.match(/^(\d+)-(\d+)$/);
|
|
2680
|
+
const plusMatch = employees.match(/^(\d+)\+$/);
|
|
2681
|
+
const bracketMatch = employees.match(/^ANTAL_(\d+)_(\d+)$/i);
|
|
2682
|
+
if (/^\d+$/.test(employees)) {
|
|
2683
|
+
baseN = parseInt(employees, 10);
|
|
2684
|
+
}
|
|
2685
|
+
else if (rangeMatch) {
|
|
2686
|
+
// Use upper bound — gives more inclusive lookalike search than midpoint
|
|
2687
|
+
baseN = parseInt(rangeMatch[2], 10);
|
|
2688
|
+
}
|
|
2689
|
+
else if (plusMatch) {
|
|
2690
|
+
baseN = parseInt(plusMatch[1], 10);
|
|
2691
|
+
}
|
|
2692
|
+
else if (bracketMatch) {
|
|
2693
|
+
baseN = parseInt(bracketMatch[2], 10);
|
|
2694
|
+
}
|
|
2695
|
+
if (baseN !== null && baseN > 0) {
|
|
2696
|
+
params.employees_min = Math.max(1, Math.floor(baseN * 0.3));
|
|
2697
|
+
params.employees_max = Math.ceil(baseN * 3);
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
params.sort = "revenue:desc";
|
|
2701
|
+
const data = await apiRequest(`/search/advanced`, params);
|
|
2702
|
+
const results = (data.results || []).filter((r) => r.cvr !== cvr);
|
|
2703
|
+
if (format === "json") {
|
|
2704
|
+
return jsonText({ source: { cvr, name: source.name }, similarity: tight ? "tight" : "loose", results: selectListFields(results, fields, verbose) });
|
|
2705
|
+
}
|
|
2706
|
+
const lines = [
|
|
2707
|
+
`# Lookalikes til ${source.name} (CVR ${cvr})`,
|
|
2708
|
+
"",
|
|
2709
|
+
`*Similarity: ${tight ? "tight (samme branchekode + kommune + størrelse)" : "loose (samme branche-prefix)"}*`,
|
|
2710
|
+
"",
|
|
2711
|
+
];
|
|
2712
|
+
for (const r of results) {
|
|
2713
|
+
const parts = [`**${r.name}** (CVR ${r.cvr})`];
|
|
2714
|
+
if (r.city)
|
|
2715
|
+
parts.push(String(r.city));
|
|
2716
|
+
if (r.industry_text)
|
|
2717
|
+
parts.push(String(r.industry_text));
|
|
2718
|
+
if (r.employees)
|
|
2719
|
+
parts.push(`${r.employees} ansatte`);
|
|
2720
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
2721
|
+
}
|
|
2722
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2723
|
+
}
|
|
2724
|
+
catch (error) {
|
|
2725
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2726
|
+
}
|
|
2727
|
+
});
|
|
2728
|
+
// ── Tool 19: Change detector ─────────────────────────────────────
|
|
2729
|
+
server.registerTool("firmaapi_change_detector", {
|
|
2730
|
+
title: "Find virksomheder med ændringer efter en dato",
|
|
2731
|
+
description: `Detekter hvilke virksomheder der har haft data-ændringer i CVR-registeret siden en given dato. Brug ved CRM-sync, change-monitoring og automatiske workflows.
|
|
2732
|
+
|
|
2733
|
+
Tidsstempel-semantik: \`since\` filtrerer på \`source_updated_at\` — det øjeblik
|
|
2734
|
+
hvor data faktisk ændrede sig i ERST/CVR-registeret. Det er IKKE last-cache-time
|
|
2735
|
+
eller last-API-call-time. En virksomhed kan blive set af brugere uden at få et
|
|
2736
|
+
nyt source_updated_at.
|
|
2737
|
+
|
|
2738
|
+
Args:
|
|
2739
|
+
- since (string): ISO-dato (YYYY-MM-DD) eller fuld timestamp — kun ændringer
|
|
2740
|
+
efter denne. Fx "2026-04-29" eller "2026-04-29T08:00:00Z".
|
|
2741
|
+
- alle advanced_search-filtre kan kombineres (fx kun ændringer i en branche)
|
|
2742
|
+
- limit (int 1-100): default 50
|
|
2743
|
+
|
|
2744
|
+
Returnerer ændrede selskaber sorteret efter senest ændret først.
|
|
2745
|
+
|
|
2746
|
+
Use cases:
|
|
2747
|
+
- "Hvilke IT-selskaber er ændret de sidste 30 dage?" → since="2026-04-01", industry="62"
|
|
2748
|
+
- "CRM-sync: alle ændringer siden i går" → since="2026-04-30"
|
|
2749
|
+
- "Find nye konkurser i sidste uge" → since="2026-04-23", status="Under konkurs"
|
|
2750
|
+
|
|
2751
|
+
${PLAN.any}`,
|
|
2752
|
+
inputSchema: {
|
|
2753
|
+
since: z.string().describe("ISO-dato (YYYY-MM-DD) — kun ændringer efter denne"),
|
|
2754
|
+
...SHARED_SEARCH_FILTERS,
|
|
2755
|
+
limit: z.number().int().min(1).max(100).optional(),
|
|
2756
|
+
format: FORMAT_SCHEMA,
|
|
2757
|
+
fields: FIELDS_SCHEMA,
|
|
2758
|
+
verbose: VERBOSE_SCHEMA,
|
|
2759
|
+
},
|
|
2760
|
+
annotations: {
|
|
2761
|
+
readOnlyHint: true,
|
|
2762
|
+
destructiveHint: false,
|
|
2763
|
+
idempotentHint: true,
|
|
2764
|
+
openWorldHint: true,
|
|
2765
|
+
},
|
|
2766
|
+
}, async ({ since, limit, format, fields, verbose, ...filters }) => {
|
|
2767
|
+
try {
|
|
2768
|
+
const params = {
|
|
2769
|
+
...filters,
|
|
2770
|
+
updated_after: since,
|
|
2771
|
+
limit: limit || 50,
|
|
2772
|
+
};
|
|
2773
|
+
// Need at least one filter — updated_after counts as one
|
|
2774
|
+
const data = await apiRequest(`/search/advanced`, params);
|
|
2775
|
+
const results = data.results || [];
|
|
2776
|
+
if (format === "json") {
|
|
2777
|
+
return jsonText({ since, ...data, results: selectListFields(results, fields, verbose) });
|
|
2778
|
+
}
|
|
2779
|
+
const lines = [
|
|
2780
|
+
`# Ændringer siden ${since}`,
|
|
2781
|
+
"",
|
|
2782
|
+
`*${results.length} virksomheder ${data.total != null ? `(af ${data.total.toLocaleString("da-DK")} total match)` : ""}*`,
|
|
2783
|
+
"",
|
|
2784
|
+
];
|
|
2785
|
+
for (const r of results) {
|
|
2786
|
+
const parts = [`**${r.name}** (CVR ${r.cvr})`];
|
|
2787
|
+
if (r.status)
|
|
2788
|
+
parts.push(String(r.status));
|
|
2789
|
+
if (r.city)
|
|
2790
|
+
parts.push(String(r.city));
|
|
2791
|
+
if (r.industry_code)
|
|
2792
|
+
parts.push(String(r.industry_code));
|
|
2793
|
+
const meta = r.meta;
|
|
2794
|
+
if (meta?.cached_at)
|
|
2795
|
+
parts.push(`opdateret ${meta.cached_at.slice(0, 10)}`);
|
|
2796
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
2797
|
+
}
|
|
2798
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2799
|
+
}
|
|
2800
|
+
catch (error) {
|
|
2801
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2802
|
+
}
|
|
2803
|
+
});
|
|
2804
|
+
// ── Tool 21: Board overlap ────────────────────────────────────────
|
|
2805
|
+
server.registerTool("firmaapi_board_overlap", {
|
|
2806
|
+
title: "Find sammenfaldende bestyrelses-/ledelsesmedlemmer mellem virksomheder",
|
|
2807
|
+
description: `Sammenlign 2 virksomheders ledelsesgrupper og find personer der sidder i begge.
|
|
2808
|
+
Tjekker executives, board_members, alternates, liquidators, founders og
|
|
2809
|
+
unlimited_liability_partners.
|
|
2810
|
+
|
|
2811
|
+
Person-matching:
|
|
2812
|
+
1. Først via person_id (UUID) — eksakt og pålideligt
|
|
2813
|
+
2. Fallback til normaliseret navn (lowercase + whitespace-collaps)
|
|
2814
|
+
|
|
2815
|
+
Begrænsninger ved navne-fallback: Kan misse variationer som "Jørgen" vs "Joergen",
|
|
2816
|
+
hyphenerede navne, eller navne med diakritiske tegn der ikke er normaliseret ens.
|
|
2817
|
+
person_id-matchning er altid foretrukket.
|
|
2818
|
+
|
|
2819
|
+
Use cases:
|
|
2820
|
+
- Konflikt-screening i M&A
|
|
2821
|
+
- Network analysis: "Er der overlap mellem disse konkurrenters bestyrelser?"
|
|
2822
|
+
- "Warm intro"-research: hvem kender begge selskaber
|
|
2823
|
+
|
|
2824
|
+
Args:
|
|
2825
|
+
- cvr_a, cvr_b (string): de to selskaber der sammenlignes
|
|
2826
|
+
|
|
2827
|
+
Eksempler:
|
|
2828
|
+
- "Har Novo og LEGO sammenfaldende bestyrelsesmedlemmer?" → cvr_a="24256790", cvr_b="47458714"
|
|
2829
|
+
|
|
2830
|
+
${PLAN.basis} Sammenligning via person_id kræver Professionel+; på Basis/Standard sammenlignes navne, hvilket kan give falske sammenfald.`,
|
|
2831
|
+
inputSchema: {
|
|
2832
|
+
cvr_a: z.string().regex(/^\d{8}$/),
|
|
2833
|
+
cvr_b: z.string().regex(/^\d{8}$/),
|
|
2834
|
+
format: FORMAT_SCHEMA,
|
|
2835
|
+
},
|
|
2836
|
+
annotations: {
|
|
2837
|
+
readOnlyHint: true,
|
|
2838
|
+
destructiveHint: false,
|
|
2839
|
+
idempotentHint: true,
|
|
2840
|
+
openWorldHint: true,
|
|
2841
|
+
},
|
|
2842
|
+
}, async ({ cvr_a, cvr_b, format }) => {
|
|
2843
|
+
try {
|
|
2844
|
+
const [a, b] = await Promise.all([
|
|
2845
|
+
apiRequest(`/company/${cvr_a}`),
|
|
2846
|
+
apiRequest(`/company/${cvr_b}`),
|
|
2847
|
+
]);
|
|
2848
|
+
const collect = (c) => {
|
|
2849
|
+
const out = [];
|
|
2850
|
+
for (const arr of [
|
|
2851
|
+
["executives", "Direktion"],
|
|
2852
|
+
["board_members", "Bestyrelse"],
|
|
2853
|
+
["alternates", "Suppleant"],
|
|
2854
|
+
["liquidators", "Likvidator"],
|
|
2855
|
+
["founders", "Stifter"],
|
|
2856
|
+
["unlimited_liability_partners", "Fuldt ansvarlig"],
|
|
2857
|
+
]) {
|
|
2858
|
+
const items = (c[arr[0]] || []);
|
|
2859
|
+
for (const m of items) {
|
|
2860
|
+
out.push({
|
|
2861
|
+
name: String(m.name || ""),
|
|
2862
|
+
role: arr[1] + (m.function ? ` (${m.function})` : ""),
|
|
2863
|
+
person_id: m.person_id ?? null,
|
|
2864
|
+
});
|
|
2865
|
+
}
|
|
2866
|
+
}
|
|
2867
|
+
return out;
|
|
2868
|
+
};
|
|
2869
|
+
const peopleA = collect(a);
|
|
2870
|
+
const peopleB = collect(b);
|
|
2871
|
+
// Match by person_id if available, fallback to normalized name
|
|
2872
|
+
const norm = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
|
|
2873
|
+
const keyOf = (p) => p.person_id || `name:${norm(p.name)}`;
|
|
2874
|
+
const mapA = new Map();
|
|
2875
|
+
for (const p of peopleA) {
|
|
2876
|
+
const k = keyOf(p);
|
|
2877
|
+
if (!mapA.has(k))
|
|
2878
|
+
mapA.set(k, []);
|
|
2879
|
+
mapA.get(k).push(p);
|
|
2880
|
+
}
|
|
2881
|
+
const overlap = [];
|
|
2882
|
+
for (const p of peopleB) {
|
|
2883
|
+
const k = keyOf(p);
|
|
2884
|
+
const matchA = mapA.get(k);
|
|
2885
|
+
if (matchA) {
|
|
2886
|
+
overlap.push({
|
|
2887
|
+
name: p.name,
|
|
2888
|
+
person_id: p.person_id,
|
|
2889
|
+
role_a: matchA.map((m) => m.role),
|
|
2890
|
+
role_b: peopleB.filter((q) => keyOf(q) === k).map((m) => m.role),
|
|
2891
|
+
});
|
|
2892
|
+
mapA.delete(k); // avoid duplicates
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
if (format === "json") {
|
|
2896
|
+
return jsonText({
|
|
2897
|
+
company_a: { cvr: cvr_a, name: a.name, governance_count: peopleA.length },
|
|
2898
|
+
company_b: { cvr: cvr_b, name: b.name, governance_count: peopleB.length },
|
|
2899
|
+
overlap_count: overlap.length,
|
|
2900
|
+
overlap,
|
|
2901
|
+
});
|
|
2902
|
+
}
|
|
2903
|
+
const lines = [
|
|
2904
|
+
`# Bestyrelses-overlap`,
|
|
2905
|
+
"",
|
|
2906
|
+
`**${a.name}** (CVR ${cvr_a}): ${peopleA.length} ledelses-medlemmer`,
|
|
2907
|
+
`**${b.name}** (CVR ${cvr_b}): ${peopleB.length} ledelses-medlemmer`,
|
|
2908
|
+
"",
|
|
2909
|
+
`**Overlap**: ${overlap.length} ${overlap.length === 1 ? "person" : "personer"}`,
|
|
2910
|
+
"",
|
|
2911
|
+
];
|
|
2912
|
+
if (overlap.length === 0) {
|
|
2913
|
+
lines.push("*Intet overlap fundet.*");
|
|
2914
|
+
}
|
|
2915
|
+
else {
|
|
2916
|
+
for (const o of overlap) {
|
|
2917
|
+
lines.push(`### ${o.name}${o.person_id ? ` [${o.person_id}]` : ""}`);
|
|
2918
|
+
lines.push(`- I **${a.name}**: ${o.role_a.join(", ")}`);
|
|
2919
|
+
lines.push(`- I **${b.name}**: ${o.role_b.join(", ")}`);
|
|
2920
|
+
lines.push("");
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2924
|
+
}
|
|
2925
|
+
catch (error) {
|
|
2926
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2927
|
+
}
|
|
2928
|
+
});
|
|
2929
|
+
// ── Tool 22: Growth trajectory ────────────────────────────────────
|
|
2930
|
+
server.registerTool("firmaapi_growth_trajectory", {
|
|
2931
|
+
title: "Vækstanalyse for en virksomhed (multi-year)",
|
|
2932
|
+
description: `Hent regnskaber over flere år og beregn YoY-vækst i omsætning, resultat, egenkapital og aktiver.
|
|
2933
|
+
|
|
2934
|
+
Viser tilgængelige årsregnskaber og API-beregnede vækstrater uden samlet klassifikation.
|
|
2935
|
+
Periodernes længde og datadækning skal kontrolleres før sammenligning.
|
|
2936
|
+
|
|
2937
|
+
Args:
|
|
2938
|
+
- cvr (string): 8-cifret CVR
|
|
2939
|
+
- format (markdown|json)
|
|
2940
|
+
|
|
2941
|
+
${PLAN.standard} Standard giver adgang til seneste regnskabsår; Professionel giver adgang til op til 5 års historik. Antallet af tilgængelige regnskaber afhænger af kilden og eventuelle individuelle adgangsgrænser.`,
|
|
2942
|
+
inputSchema: {
|
|
2943
|
+
cvr: z.string().regex(/^\d{8}$/),
|
|
2944
|
+
format: FORMAT_SCHEMA,
|
|
2945
|
+
},
|
|
2946
|
+
annotations: {
|
|
2947
|
+
readOnlyHint: true,
|
|
2948
|
+
destructiveHint: false,
|
|
2949
|
+
idempotentHint: true,
|
|
2950
|
+
openWorldHint: true,
|
|
2951
|
+
},
|
|
2952
|
+
}, async ({ cvr, format }) => {
|
|
2953
|
+
try {
|
|
2954
|
+
const data = await apiRequest(`/company/${cvr}`, { include: "finance" });
|
|
2955
|
+
const fin = (data.financials || []);
|
|
2956
|
+
const annualOnly = fin.filter((f) => !f.report_type || f.report_type === "annual");
|
|
2957
|
+
annualOnly.sort((a, b) => (a.year || 0) - (b.year || 0));
|
|
2958
|
+
if (annualOnly.length === 0) {
|
|
2959
|
+
const hint = data.financials_pending ? " Regnskaber er ved at blive hentet; prøv igen senere." : " Det betyder ikke i sig selv, at en opgradering vil give flere oplysninger.";
|
|
2960
|
+
return {
|
|
2961
|
+
content: [{
|
|
2962
|
+
type: "text",
|
|
2963
|
+
text: `Ingen årsregnskaber fundet for CVR ${cvr}.${hint}`,
|
|
2964
|
+
}],
|
|
2965
|
+
};
|
|
2966
|
+
}
|
|
2967
|
+
if (format === "json") {
|
|
2968
|
+
return jsonText({
|
|
2969
|
+
cvr,
|
|
2970
|
+
name: data.name,
|
|
2971
|
+
years_analyzed: annualOnly.length,
|
|
2972
|
+
financials: annualOnly,
|
|
2973
|
+
});
|
|
2974
|
+
}
|
|
2975
|
+
const lines = [
|
|
2976
|
+
`# Vækstanalyse: ${data.name} (CVR ${cvr})`,
|
|
2977
|
+
"",
|
|
2978
|
+
`**Antal år analyseret**: ${annualOnly.length}`,
|
|
2979
|
+
"",
|
|
2980
|
+
"| År | Omsætning | YoY | Resultat | YoY | Egenkapital | YoY |",
|
|
2981
|
+
"| --- | --- | --- | --- | --- | --- | --- |",
|
|
2982
|
+
];
|
|
2983
|
+
for (const f of annualOnly) {
|
|
2984
|
+
const g = f.growth;
|
|
2985
|
+
lines.push(`| ${f.year} | ${dkk(f.revenue)} | ${pct(g?.revenue_yoy)} | ${dkk(f.net_profit)} | ${pct(g?.profit_yoy)} | ${dkk(f.equity)} | ${pct(g?.equity_yoy)} |`);
|
|
2986
|
+
}
|
|
2987
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
2988
|
+
}
|
|
2989
|
+
catch (error) {
|
|
2990
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
2991
|
+
}
|
|
2992
|
+
});
|
|
2993
|
+
// ── Tool 23: Industry landscape ──────────────────────────────────
|
|
2994
|
+
server.registerTool("firmaapi_industry_landscape", {
|
|
2995
|
+
title: "Top N virksomheder i en branche (rangordnet)",
|
|
2996
|
+
description: `Hent top N virksomheder i en specifik branche, by eller region, sorteret
|
|
2997
|
+
efter omsætning, kapital, ansatte eller stiftelsesår.
|
|
2998
|
+
|
|
2999
|
+
Bemærk: 'revenue'-rangering bruger \`latest_revenue\` fra det seneste indberettede
|
|
3000
|
+
årsregnskab (ikke summeret over flere år). 'employees'-rangering bruger
|
|
3001
|
+
employees_max-bandet i CVR's beskæftigelsesinterval — så "ANTAL_50_99" sorteres
|
|
3002
|
+
højere end "ANTAL_10_19" som forventet.
|
|
3003
|
+
|
|
3004
|
+
NULL-værdier (selskaber uden regnskab/employees-data) sorteres altid sidst, så
|
|
3005
|
+
listen ikke domineres af unprofiled rows.
|
|
3006
|
+
|
|
3007
|
+
Use cases:
|
|
3008
|
+
- "Hvem er de 50 største IT-selskaber i Aarhus?"
|
|
3009
|
+
- "Top 20 producenter inden for fødevarer i Region Hovedstaden"
|
|
3010
|
+
- "De ældste aktive selskaber i Danmark" → sort='founded', limit=20
|
|
3011
|
+
|
|
3012
|
+
Args:
|
|
3013
|
+
- industry (string): branchekode (prefix-match, fx '62' = alle IT-selskaber)
|
|
3014
|
+
eller fritekst (fx 'restauranter')
|
|
3015
|
+
- sort (revenue|capital|employees|founded): default 'revenue'
|
|
3016
|
+
- limit (int 1-100): default 25
|
|
3017
|
+
- plus city, region, municipality, status, employees_min
|
|
3018
|
+
|
|
3019
|
+
${PLAN.standard} sort=revenue/capital kræver Standard+ for at give meningsfuld
|
|
3020
|
+
rangering (uden regnskabsdata sorteres alle med NULL).`,
|
|
3021
|
+
inputSchema: {
|
|
3022
|
+
industry: z.string().describe("Branchekode (prefix) eller branchetekst"),
|
|
3023
|
+
sort: z.enum(["revenue", "capital", "employees", "founded"]).optional(),
|
|
3024
|
+
limit: z.number().int().min(1).max(100).optional(),
|
|
3025
|
+
city: z.string().optional(),
|
|
3026
|
+
region: z.string().optional(),
|
|
3027
|
+
municipality: z.string().optional(),
|
|
3028
|
+
status: z.string().optional(),
|
|
3029
|
+
employees_min: z.number().int().nonnegative().optional(),
|
|
3030
|
+
format: FORMAT_SCHEMA,
|
|
3031
|
+
fields: FIELDS_SCHEMA,
|
|
3032
|
+
verbose: VERBOSE_SCHEMA,
|
|
3033
|
+
},
|
|
3034
|
+
annotations: {
|
|
3035
|
+
readOnlyHint: true,
|
|
3036
|
+
destructiveHint: false,
|
|
3037
|
+
idempotentHint: true,
|
|
3038
|
+
openWorldHint: true,
|
|
3039
|
+
},
|
|
3040
|
+
}, async ({ industry, sort, limit, city, region, municipality, status, employees_min, format, fields, verbose }) => {
|
|
3041
|
+
try {
|
|
3042
|
+
const sortField = sort || "revenue";
|
|
3043
|
+
const params = {
|
|
3044
|
+
industry,
|
|
3045
|
+
status: status || "Aktiv",
|
|
3046
|
+
limit: limit || 25,
|
|
3047
|
+
sort: `${sortField}:desc`,
|
|
3048
|
+
};
|
|
3049
|
+
if (city)
|
|
3050
|
+
params.city = city;
|
|
3051
|
+
if (region)
|
|
3052
|
+
params.region = region;
|
|
3053
|
+
if (municipality)
|
|
3054
|
+
params.municipality = municipality;
|
|
3055
|
+
if (employees_min != null)
|
|
3056
|
+
params.employees_min = employees_min;
|
|
3057
|
+
const data = await apiRequest(`/search/advanced`, params);
|
|
3058
|
+
const results = data.results || [];
|
|
3059
|
+
if (format === "json") {
|
|
3060
|
+
return jsonText({ industry, sort: sortField, ...data, results: selectListFields(results, fields, verbose) });
|
|
3061
|
+
}
|
|
3062
|
+
const lines = [
|
|
3063
|
+
`# Branche-landskab: ${industry}`,
|
|
3064
|
+
"",
|
|
3065
|
+
`*Sorteret efter ${sortField} (faldende). ${results.length} virksomheder${data.total != null ? ` af ${data.total.toLocaleString("da-DK")} match` : ""}.*`,
|
|
3066
|
+
"",
|
|
3067
|
+
];
|
|
3068
|
+
let rank = 1;
|
|
3069
|
+
for (const r of results) {
|
|
3070
|
+
const parts = [`#${rank}: **${r.name}** (CVR ${r.cvr})`];
|
|
3071
|
+
if (r.city)
|
|
3072
|
+
parts.push(String(r.city));
|
|
3073
|
+
if (r.employees)
|
|
3074
|
+
parts.push(`${r.employees} ansatte`);
|
|
3075
|
+
const fin = r.financials?.[0];
|
|
3076
|
+
if (fin?.revenue)
|
|
3077
|
+
parts.push(`omsætning ${dkk(fin.revenue)}`);
|
|
3078
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
3079
|
+
rank++;
|
|
3080
|
+
}
|
|
3081
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
3082
|
+
}
|
|
3083
|
+
catch (error) {
|
|
3084
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
3085
|
+
}
|
|
3086
|
+
});
|
|
3087
|
+
// ── Tool 24: Geographical distribution ───────────────────────────
|
|
3088
|
+
server.registerTool("firmaapi_geographical_distribution", {
|
|
3089
|
+
title: "Geografisk fordeling af virksomheder",
|
|
3090
|
+
description: `Aggreger virksomheder pr. kommune eller region for et givet filter-sæt og
|
|
3091
|
+
returnerer en tabel med antal + andel pr. område.
|
|
3092
|
+
|
|
3093
|
+
Bemærk: \`group_by=municipality\` aggregerer på \`municipality_code\` (98 kommuner).
|
|
3094
|
+
\`group_by=region\` aggregerer på regions-niveau (5 regioner). Hvis du vil filtrere
|
|
3095
|
+
til en bestemt kommune før aggregering, brug \`municipality\` filter — men det
|
|
3096
|
+
giver kun 1 række (sig selv), så for fordelinger brug typisk filter på branche/
|
|
3097
|
+
status og group_by på geografi.
|
|
3098
|
+
|
|
3099
|
+
Use cases:
|
|
3100
|
+
- "Hvor mange tømrervirksomheder pr. kommune?" → industry="433200", group_by="municipality"
|
|
3101
|
+
- "Geografisk fordeling af IT-selskaber" → industry="62", group_by="region"
|
|
3102
|
+
- "Hvor er fitness-branchen koncentreret?" → industry="9313", group_by="municipality", top_n=20
|
|
3103
|
+
|
|
3104
|
+
Args:
|
|
3105
|
+
- group_by ('municipality'|'region'): default 'municipality'
|
|
3106
|
+
- top_n (int 5-30): default 15
|
|
3107
|
+
- plus alle advanced_search filtre
|
|
3108
|
+
|
|
3109
|
+
${PLAN.any}`,
|
|
3110
|
+
inputSchema: {
|
|
3111
|
+
...SHARED_SEARCH_FILTERS,
|
|
3112
|
+
group_by: z.enum(["municipality", "region"]).optional().describe("Default 'municipality'"),
|
|
3113
|
+
top_n: z.number().int().min(5).max(30).optional().describe("Default 15"),
|
|
3114
|
+
format: FORMAT_SCHEMA,
|
|
3115
|
+
},
|
|
3116
|
+
annotations: {
|
|
3117
|
+
readOnlyHint: true,
|
|
3118
|
+
destructiveHint: false,
|
|
3119
|
+
idempotentHint: true,
|
|
3120
|
+
openWorldHint: true,
|
|
3121
|
+
},
|
|
3122
|
+
}, async ({ group_by, top_n, format, ...filters }) => {
|
|
3123
|
+
try {
|
|
3124
|
+
const params = {
|
|
3125
|
+
...filters,
|
|
3126
|
+
group_by: group_by || "municipality",
|
|
3127
|
+
top_n: top_n || 15,
|
|
3128
|
+
};
|
|
3129
|
+
const data = await apiRequest(`/search/aggregate`, params);
|
|
3130
|
+
if (format === "json")
|
|
3131
|
+
return jsonText(data);
|
|
3132
|
+
const lines = [
|
|
3133
|
+
`# Geografisk fordeling`,
|
|
3134
|
+
"",
|
|
3135
|
+
`*Grupperet efter: ${data.group_by}*`,
|
|
3136
|
+
`*Total match: ${data.total_matches.toLocaleString("da-DK")} virksomheder fordelt på ${data.total_groups} ${data.group_by === "municipality" ? "kommuner" : "regioner"}*`,
|
|
3137
|
+
"",
|
|
3138
|
+
"| # | Område | Antal | Andel |",
|
|
3139
|
+
"| --- | --- | --- | --- |",
|
|
3140
|
+
];
|
|
3141
|
+
let rank = 1;
|
|
3142
|
+
for (const r of data.results) {
|
|
3143
|
+
const share = data.total_matches ? ((r.count / data.total_matches) * 100).toFixed(1) : "0";
|
|
3144
|
+
lines.push(`| ${rank} | ${r.key || "(ukendt)"} | ${r.count.toLocaleString("da-DK")} | ${share}% |`);
|
|
3145
|
+
rank++;
|
|
3146
|
+
}
|
|
3147
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
3148
|
+
}
|
|
3149
|
+
catch (error) {
|
|
3150
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
3151
|
+
}
|
|
3152
|
+
});
|
|
3153
|
+
// ── Tool 25: Validate CVR (modulus-11) ───────────────────────────
|
|
3154
|
+
/**
|
|
3155
|
+
* CVR modulus-11 check. Standard Danish weights: [2, 7, 6, 5, 4, 3, 2, 1]
|
|
3156
|
+
* for the 8 digits left-to-right. Sum mod 11 must equal 0 for the CVR to
|
|
3157
|
+
* be a valid number (this is independent of whether the CVR exists).
|
|
3158
|
+
*
|
|
3159
|
+
* This check rejects ~91% of randomly typed 8-digit strings, catching
|
|
3160
|
+
* typos before they spend an API call.
|
|
3161
|
+
*/
|
|
3162
|
+
const CVR_MODULUS_WEIGHTS = [2, 7, 6, 5, 4, 3, 2, 1];
|
|
3163
|
+
function checkCvrModulus11(eightDigits) {
|
|
3164
|
+
if (!/^\d{8}$/.test(eightDigits))
|
|
3165
|
+
return false;
|
|
3166
|
+
let sum = 0;
|
|
3167
|
+
for (let i = 0; i < 8; i++) {
|
|
3168
|
+
sum += parseInt(eightDigits[i], 10) * CVR_MODULUS_WEIGHTS[i];
|
|
3169
|
+
}
|
|
3170
|
+
return sum % 11 === 0;
|
|
3171
|
+
}
|
|
3172
|
+
server.registerTool("firmaapi_validate_cvr", {
|
|
3173
|
+
title: "Valider CVR-nummer (modulus-11 check)",
|
|
3174
|
+
description: `Tjek om en CVR-streng er et formelt gyldigt CVR-nummer.
|
|
3175
|
+
|
|
3176
|
+
Validering i 2 trin:
|
|
3177
|
+
1. **Format**: præcis 8 cifre efter normalisering (whitespace + bindestreger fjernes)
|
|
3178
|
+
2. **Modulus-11 check**: standard dansk CVR-checksum med vægte [2,7,6,5,4,3,2,1].
|
|
3179
|
+
Et tilfældigt 8-cifret tal har ~9% sandsynlighed for at bestå dette check —
|
|
3180
|
+
så validate_cvr fanger ~91% af tastefejl uden et API-kald.
|
|
3181
|
+
|
|
3182
|
+
Brug dette FØR firmaapi_lookup_company eller firmaapi_batch_lookup for at
|
|
3183
|
+
spare API-quota og få bedre fejlbeskeder ved bruger-input.
|
|
3184
|
+
|
|
3185
|
+
Args:
|
|
3186
|
+
- cvr (string): CVR til validering. Tolererer "12345678", "12 34 56 78",
|
|
3187
|
+
"12-34-56-78" eller "DK12345678".
|
|
3188
|
+
- check_existence (boolean): hvis true, opslår også om CVR'et findes i
|
|
3189
|
+
vores database (koster 1 API-call). Default false (kun format-check).
|
|
3190
|
+
|
|
3191
|
+
Returnerer: format-validitet, modulus-validitet, normaliseret 8-cifret form,
|
|
3192
|
+
+ optionelt name/status hvis check_existence=true og CVR findes.
|
|
3193
|
+
|
|
3194
|
+
Eksempler:
|
|
3195
|
+
- "Tjek om '12 34 56 78' er gyldigt CVR" → cvr="12 34 56 78"
|
|
3196
|
+
- "Findes CVR 24256790?" → cvr="24256790", check_existence=true
|
|
3197
|
+
|
|
3198
|
+
${PLAN.any} check_existence=true bruger 1 quota-enhed pr. kald.`,
|
|
3199
|
+
inputSchema: {
|
|
3200
|
+
cvr: z.string().describe("CVR-streng (tolererer whitespace, bindestreger og 'DK'-prefix)"),
|
|
3201
|
+
check_existence: z.boolean().optional().describe("Hvis true: opslår også om CVR findes (1 API-call)"),
|
|
3202
|
+
format: FORMAT_SCHEMA,
|
|
3203
|
+
},
|
|
3204
|
+
annotations: {
|
|
3205
|
+
readOnlyHint: true,
|
|
3206
|
+
destructiveHint: false,
|
|
3207
|
+
idempotentHint: true,
|
|
3208
|
+
openWorldHint: false, // pure compute when check_existence=false
|
|
3209
|
+
},
|
|
3210
|
+
}, async ({ cvr, check_existence, format }) => {
|
|
3211
|
+
// Normalize: strip whitespace, dashes, DK-prefix
|
|
3212
|
+
const normalized = cvr
|
|
3213
|
+
.replace(/\s+/g, "")
|
|
3214
|
+
.replace(/-/g, "")
|
|
3215
|
+
.replace(/^DK/i, "")
|
|
3216
|
+
.trim();
|
|
3217
|
+
const validFormat = /^\d{8}$/.test(normalized);
|
|
3218
|
+
const validChecksum = validFormat && checkCvrModulus11(normalized);
|
|
3219
|
+
const result = {
|
|
3220
|
+
input: cvr,
|
|
3221
|
+
normalized: validFormat ? normalized : null,
|
|
3222
|
+
valid_format: validFormat,
|
|
3223
|
+
valid_checksum: validChecksum,
|
|
3224
|
+
valid: validFormat && validChecksum,
|
|
3225
|
+
};
|
|
3226
|
+
if (!validFormat) {
|
|
3227
|
+
result.error = `Forventer 8 cifre efter normalisering (whitespace/bindestreger/DK-prefix fjernes), fik ${normalized.length} tegn: '${normalized}'`;
|
|
3228
|
+
}
|
|
3229
|
+
else if (!validChecksum) {
|
|
3230
|
+
result.error = `Format OK men modulus-11 checksum mislykkes — sandsynligvis en typo. Tjek hver ciffer.`;
|
|
3231
|
+
}
|
|
3232
|
+
// Optional existence check
|
|
3233
|
+
if (check_existence && validFormat && validChecksum) {
|
|
3234
|
+
try {
|
|
3235
|
+
const company = await apiRequest(`/company/${normalized}`);
|
|
3236
|
+
result.exists = true;
|
|
3237
|
+
result.name = String(company.name || "");
|
|
3238
|
+
result.status = String(company.status || "");
|
|
3239
|
+
}
|
|
3240
|
+
catch (err) {
|
|
3241
|
+
const msg = handleApiError(err);
|
|
3242
|
+
if (msg.includes("Ikke fundet")) {
|
|
3243
|
+
result.exists = false;
|
|
3244
|
+
}
|
|
3245
|
+
else {
|
|
3246
|
+
// Other errors (auth, network) — surface but don't fail validation
|
|
3247
|
+
result.error = `Validering OK, men kunne ikke verificere eksistens: ${msg}`;
|
|
3248
|
+
}
|
|
3249
|
+
}
|
|
3250
|
+
}
|
|
3251
|
+
if (format === "json")
|
|
3252
|
+
return jsonText(result);
|
|
3253
|
+
const lines = [`# CVR-validering: '${cvr}'`, ""];
|
|
3254
|
+
lines.push(`- **Input**: \`${cvr}\``);
|
|
3255
|
+
if (result.normalized)
|
|
3256
|
+
lines.push(`- **Normaliseret**: \`${result.normalized}\``);
|
|
3257
|
+
lines.push(`- **Format gyldigt**: ${validFormat ? "✅ Ja (8 cifre)" : "❌ Nej"}`);
|
|
3258
|
+
if (validFormat) {
|
|
3259
|
+
lines.push(`- **Modulus-11 checksum**: ${validChecksum ? "✅ Gyldig" : "❌ Fejler"}`);
|
|
3260
|
+
}
|
|
3261
|
+
lines.push(`- **Samlet vurdering**: ${result.valid ? "✅ Gyldigt CVR-format" : "❌ Ikke gyldigt"}`);
|
|
3262
|
+
if (result.error)
|
|
3263
|
+
lines.push("", `*${result.error}*`);
|
|
3264
|
+
if (check_existence && result.valid) {
|
|
3265
|
+
lines.push("");
|
|
3266
|
+
if (result.exists) {
|
|
3267
|
+
lines.push(`✅ **Findes i registeret**: ${result.name} (${result.status})`);
|
|
3268
|
+
}
|
|
3269
|
+
else if (result.exists === false) {
|
|
3270
|
+
lines.push(`⚠️ **Findes IKKE i registeret** — formelt gyldigt format men ingen virksomhed med dette CVR.`);
|
|
3271
|
+
}
|
|
3272
|
+
}
|
|
3273
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
3274
|
+
});
|
|
3275
|
+
// ── Tool 26: My portfolio (person's role overview) ───────────────
|
|
3276
|
+
server.registerTool("firmaapi_my_portfolio", {
|
|
3277
|
+
title: "Personens portfolio — alle virksomhedsroller på tværs",
|
|
3278
|
+
description: `Vis en samlet portfolio-oversigt for en person: alle aktive og historiske
|
|
3279
|
+
roller, grupperet efter rolletype, branche og virksomheds-status.
|
|
3280
|
+
|
|
3281
|
+
Tool'et er bygget for revisorer/advokater med 50+ klienter, brugere der
|
|
3282
|
+
screener UBO'er, og investorer der vil se en kandidats track record.
|
|
3283
|
+
|
|
3284
|
+
Output (markdown):
|
|
3285
|
+
- Overskrift med navn, total/aktive/historiske rolletæller
|
|
3286
|
+
- **Aktive roller** grupperet pr. rolletype (Direktør, Bestyrelsesmedlem, Stifter, Ejer)
|
|
3287
|
+
- **Branche-fordeling** af aktive selskaber
|
|
3288
|
+
- **Status-fordeling** af alle selskaber (aktiv, ophørt, konkurs, etc.)
|
|
3289
|
+
- **Top 10 seneste aktiviteter** (sorteret efter joined/left date)
|
|
3290
|
+
- Optælling af registrerede tilknytninger under 180 dage uden fortolkning
|
|
3291
|
+
|
|
3292
|
+
Args:
|
|
3293
|
+
- person_id (UUID): personens UUID. Findes via firmaapi_search_persons,
|
|
3294
|
+
eller på \`person_id\` på owners/board_members/auditors i company-respons.
|
|
3295
|
+
- format (markdown|json)
|
|
3296
|
+
|
|
3297
|
+
Edge cases:
|
|
3298
|
+
- Person uden roller → "Ingen tilknytninger"
|
|
3299
|
+
- Person med 100+ roller → top 25 vises pr. sektion + total-tæller
|
|
3300
|
+
|
|
3301
|
+
Eksempler:
|
|
3302
|
+
- "Vis Lars Larsens portfolio" → først firmaapi_search_persons → derefter
|
|
3303
|
+
firmaapi_my_portfolio med UUID
|
|
3304
|
+
- "Hvad sidder denne CFO også med?" → person_id fra company-respons
|
|
3305
|
+
|
|
3306
|
+
${PLAN.pro}`,
|
|
3307
|
+
inputSchema: {
|
|
3308
|
+
person_id: z.string().uuid("Ugyldig UUID — brug firmaapi_search_persons først").describe("Persons UUID"),
|
|
3309
|
+
format: FORMAT_SCHEMA,
|
|
3310
|
+
},
|
|
3311
|
+
annotations: {
|
|
3312
|
+
readOnlyHint: true,
|
|
3313
|
+
destructiveHint: false,
|
|
3314
|
+
idempotentHint: true,
|
|
3315
|
+
openWorldHint: true,
|
|
3316
|
+
},
|
|
3317
|
+
}, async ({ person_id, format }) => {
|
|
3318
|
+
try {
|
|
3319
|
+
const person = await apiRequest(`/person/${person_id}`);
|
|
3320
|
+
const affiliations = (person.affiliations || []);
|
|
3321
|
+
const active = affiliations.filter((a) => a.is_active === true);
|
|
3322
|
+
const historical = affiliations.filter((a) => a.is_active === false);
|
|
3323
|
+
const unknownActivity = affiliations.filter((a) => typeof a.is_active !== "boolean");
|
|
3324
|
+
const shortRoles = affiliations.filter((a) => {
|
|
3325
|
+
const d = a.duration_days;
|
|
3326
|
+
return d != null && d > 0 && d < 180;
|
|
3327
|
+
});
|
|
3328
|
+
const byRole = new Map();
|
|
3329
|
+
for (const a of active) {
|
|
3330
|
+
const role = String(a.role_title || "Ukendt rolle").trim();
|
|
3331
|
+
if (!byRole.has(role))
|
|
3332
|
+
byRole.set(role, []);
|
|
3333
|
+
byRole.get(role).push(a);
|
|
3334
|
+
}
|
|
3335
|
+
// Source-type distribution — affiliations carry source_type ('cvr', 'manual', etc)
|
|
3336
|
+
// but NOT company_status (would require N extra company-opslag). For portfolio
|
|
3337
|
+
// overview, source_type-distribution er det vi har at vise.
|
|
3338
|
+
const sourceCount = new Map();
|
|
3339
|
+
for (const a of affiliations) {
|
|
3340
|
+
const s = String(a.source_type || "ukendt");
|
|
3341
|
+
sourceCount.set(s, (sourceCount.get(s) || 0) + 1);
|
|
3342
|
+
}
|
|
3343
|
+
if (format === "json") {
|
|
3344
|
+
return jsonText({
|
|
3345
|
+
person_id,
|
|
3346
|
+
name: person.canonical_name,
|
|
3347
|
+
summary: {
|
|
3348
|
+
returned_affiliations: affiliations.length,
|
|
3349
|
+
active_affiliations: active.length,
|
|
3350
|
+
inactive_affiliations: historical.length,
|
|
3351
|
+
unknown_activity_affiliations: unknownActivity.length,
|
|
3352
|
+
short_roles_count: shortRoles.length,
|
|
3353
|
+
},
|
|
3354
|
+
roles_by_type: Object.fromEntries([...byRole.entries()].map(([role, list]) => [role, list.length])),
|
|
3355
|
+
source_type_distribution: Object.fromEntries(sourceCount),
|
|
3356
|
+
recent_activity: [...affiliations]
|
|
3357
|
+
.sort((a, b) => String(b.joined_date || "").localeCompare(String(a.joined_date || "")))
|
|
3358
|
+
.slice(0, 10),
|
|
3359
|
+
affiliations,
|
|
3360
|
+
});
|
|
3361
|
+
}
|
|
3362
|
+
const lines = [
|
|
3363
|
+
`# Portfolio: ${person.canonical_name || "(navn mangler)"}`,
|
|
3364
|
+
"",
|
|
3365
|
+
`**Returnerede tilknytninger**: ${affiliations.length} (${active.length} aktive, ${historical.length} historiske, ${unknownActivity.length} med ukendt aktivitet)`,
|
|
3366
|
+
];
|
|
3367
|
+
if (shortRoles.length > 0) {
|
|
3368
|
+
lines.push(`**Registrerede tilknytninger under 180 dage**: ${shortRoles.length}. Varighed alene beskriver ikke rollens formål.`);
|
|
3369
|
+
}
|
|
3370
|
+
lines.push("");
|
|
3371
|
+
if (active.length === 0) {
|
|
3372
|
+
lines.push("*Ingen aktive roller.*", "");
|
|
3373
|
+
}
|
|
3374
|
+
else {
|
|
3375
|
+
lines.push(`### Aktive roller pr. rolletype (${active.length})`, "");
|
|
3376
|
+
const sortedRoles = [...byRole.entries()].sort((a, b) => b[1].length - a[1].length);
|
|
3377
|
+
for (const [role, list] of sortedRoles) {
|
|
3378
|
+
lines.push(`#### ${role} (${list.length})`);
|
|
3379
|
+
const top = list.slice(0, 25);
|
|
3380
|
+
for (const a of top) {
|
|
3381
|
+
const parts = [`**${a.company_name}** (CVR ${a.cvr})`];
|
|
3382
|
+
if (a.joined_date)
|
|
3383
|
+
parts.push(`siden ${a.joined_date}`);
|
|
3384
|
+
if (a.ownership_share != null)
|
|
3385
|
+
parts.push(`${a.ownership_share}% ejerandel`);
|
|
3386
|
+
if (a.voting_share != null)
|
|
3387
|
+
parts.push(`${a.voting_share}% stemmer`);
|
|
3388
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
3389
|
+
}
|
|
3390
|
+
if (list.length > 25)
|
|
3391
|
+
lines.push(`- *... ${list.length - 25} flere ${role.toLowerCase()}-roller*`);
|
|
3392
|
+
lines.push("");
|
|
3393
|
+
}
|
|
3394
|
+
}
|
|
3395
|
+
// Source-type distribution (kun hvis der er meningsfuld variation)
|
|
3396
|
+
if (sourceCount.size > 1) {
|
|
3397
|
+
lines.push("### Datakilde-fordeling", "");
|
|
3398
|
+
const sortedSources = [...sourceCount.entries()].sort((a, b) => b[1] - a[1]);
|
|
3399
|
+
for (const [src, count] of sortedSources) {
|
|
3400
|
+
const pct = ((count / affiliations.length) * 100).toFixed(0);
|
|
3401
|
+
lines.push(`- ${src}: ${count} (${pct}%)`);
|
|
3402
|
+
}
|
|
3403
|
+
lines.push("");
|
|
3404
|
+
}
|
|
3405
|
+
// Recent activity (top 10)
|
|
3406
|
+
const recent = [...affiliations]
|
|
3407
|
+
.sort((a, b) => String(b.joined_date || "").localeCompare(String(a.joined_date || "")))
|
|
3408
|
+
.slice(0, 10);
|
|
3409
|
+
if (recent.length) {
|
|
3410
|
+
lines.push("### Seneste 10 aktiviteter", "");
|
|
3411
|
+
for (const a of recent) {
|
|
3412
|
+
const status = a.left_date ? `↗️ fratrådt ${a.left_date}` : "✅ aktiv";
|
|
3413
|
+
lines.push(`- **${a.company_name}** (${a.role_title}) — tiltrådt ${a.joined_date || "?"} [${status}]`);
|
|
3414
|
+
}
|
|
3415
|
+
}
|
|
3416
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
3417
|
+
}
|
|
3418
|
+
catch (error) {
|
|
3419
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
3420
|
+
}
|
|
3421
|
+
});
|
|
3422
|
+
// ── Tool 27: Industry benchmark ──────────────────────────────────
|
|
3423
|
+
server.registerTool("firmaapi_industry_benchmark", {
|
|
3424
|
+
title: "Branche-benchmark — sammenlign virksomhed mod peers",
|
|
3425
|
+
description: `Sammenlign en virksomheds nøgletal mod peers i samme branche (og evt. region).
|
|
3426
|
+
Beregner percentil-position for revenue, profit margin og employees.
|
|
3427
|
+
|
|
3428
|
+
Hvordan peers vælges:
|
|
3429
|
+
1. Hent target-virksomheden → udled industry_code (4-cifret prefix-match) og kommune
|
|
3430
|
+
2. Hent peer_limit (default 50, max 100) selskaber med has_financials=true i samme
|
|
3431
|
+
branche+region sorteret efter omsætning DESC
|
|
3432
|
+
3. Hent finance-data for hver peer parallelt (omkostning: 1 + N quota-units)
|
|
3433
|
+
4. Beregn percentiler (p25, median, p75, p95) client-side fra dette sample
|
|
3434
|
+
|
|
3435
|
+
Vigtige begrænsninger:
|
|
3436
|
+
- **Sample bias**: peers hentes top-revenue-først, så benchmarket er "mod de største
|
|
3437
|
+
i din branche". For en lille virksomhed vil percentilen være kunstigt lav.
|
|
3438
|
+
- **Quota-omkostning**: 1 + N kald, hvor N = peer_limit. Default = 51 quota-units.
|
|
3439
|
+
- **Mindst 10 peers**: under 10 peers giver ikke meningsfulde percentiler — output
|
|
3440
|
+
vil være sample-data uden statistisk konklusion.
|
|
3441
|
+
- **Kun annual reports**: bruger latest annual financial pr. peer (interim filtreres fra).
|
|
3442
|
+
- **Bruger has_financials=true** filter automatisk — selskaber uden regnskaber
|
|
3443
|
+
bidrager intet til distribution og udelades.
|
|
3444
|
+
|
|
3445
|
+
Output:
|
|
3446
|
+
- Target-tal (revenue, profit margin, ROE, employees)
|
|
3447
|
+
- Peer-statistik: antal, p25, median, p75, p95
|
|
3448
|
+
- Target's percentil-position pr. metric
|
|
3449
|
+
- Visning: andel af observerede værdier under virksomhedens værdi, uden kvalitetsvurdering
|
|
3450
|
+
|
|
3451
|
+
Args:
|
|
3452
|
+
- cvr (string): 8-cifret target-CVR
|
|
3453
|
+
- region (string, optional): override region. Default = target's egen kommune.
|
|
3454
|
+
Sæt til "DK" for landsdækkende benchmark.
|
|
3455
|
+
- peer_limit (int 10-100, default 50): hvor mange peers fetches
|
|
3456
|
+
- format (markdown|json)
|
|
3457
|
+
|
|
3458
|
+
Eksempler:
|
|
3459
|
+
- "Hvor godt klarer CVR 12345678 sig vs branchen?" → cvr="12345678"
|
|
3460
|
+
- "Landsdækkende benchmark" → cvr="...", region="DK"
|
|
3461
|
+
- "Bredt sample" → cvr="...", peer_limit=100
|
|
3462
|
+
|
|
3463
|
+
${PLAN.standard} Henter target + N peers → bruger N+1 quota-enheder.
|
|
3464
|
+
Tools tager typisk 3-10 sekunder pga. parallel fetch af peer-financials.`,
|
|
3465
|
+
inputSchema: {
|
|
3466
|
+
cvr: z.string().regex(/^\d{8}$/, "CVR skal være 8 cifre").describe("Target-CVR"),
|
|
3467
|
+
region: z.string().optional().describe("Override region (kommunenavn/-kode eller 'DK' for landsdækkende)"),
|
|
3468
|
+
peer_limit: z.number().int().min(10).max(100).optional().describe("Antal peers (default 50, max 100 — bruger 1+N quota)"),
|
|
3469
|
+
format: FORMAT_SCHEMA,
|
|
3470
|
+
},
|
|
3471
|
+
annotations: {
|
|
3472
|
+
readOnlyHint: true,
|
|
3473
|
+
destructiveHint: false,
|
|
3474
|
+
idempotentHint: true,
|
|
3475
|
+
openWorldHint: true,
|
|
3476
|
+
},
|
|
3477
|
+
}, async ({ cvr, region, peer_limit, format }) => {
|
|
3478
|
+
try {
|
|
3479
|
+
const target = await apiRequest(`/company/${cvr}`, {
|
|
3480
|
+
include: "finance",
|
|
3481
|
+
});
|
|
3482
|
+
const targetIndustry = target.industry_code;
|
|
3483
|
+
if (!targetIndustry) {
|
|
3484
|
+
return {
|
|
3485
|
+
content: [{
|
|
3486
|
+
type: "text",
|
|
3487
|
+
text: `Kan ikke benchmarke ${target.name || cvr}: ingen branchekode på selskabet.`,
|
|
3488
|
+
}],
|
|
3489
|
+
};
|
|
3490
|
+
}
|
|
3491
|
+
const targetFin = target.financials?.find((f) => !f.report_type || f.report_type === "annual");
|
|
3492
|
+
// Build peer query
|
|
3493
|
+
const effectiveLimit = peer_limit ?? 50;
|
|
3494
|
+
const params = {
|
|
3495
|
+
industry: targetIndustry.slice(0, 4), // 4-digit prefix
|
|
3496
|
+
status: "Aktiv",
|
|
3497
|
+
limit: effectiveLimit,
|
|
3498
|
+
sort: "revenue:desc",
|
|
3499
|
+
has_financials: true, // skip selskaber uden regnskaber — de bidrager intet
|
|
3500
|
+
};
|
|
3501
|
+
// Region: override > target's municipality > skip (countrywide)
|
|
3502
|
+
if (region && region.toUpperCase() !== "DK") {
|
|
3503
|
+
params.municipality = region;
|
|
3504
|
+
}
|
|
3505
|
+
else if (!region && target.municipality_code) {
|
|
3506
|
+
params.municipality = String(target.municipality_code);
|
|
3507
|
+
}
|
|
3508
|
+
const peerData = await apiRequest(`/search/advanced`, params);
|
|
3509
|
+
const peerCvrs = (peerData.results || [])
|
|
3510
|
+
.map((p) => p.cvr)
|
|
3511
|
+
.filter((c) => c && c !== cvr);
|
|
3512
|
+
// advanced_search returnerer IKKE finance-data i row payload — vi skal
|
|
3513
|
+
// hente hver peer separat med include=finance. Promise.allSettled så
|
|
3514
|
+
// enkelte fejl (rate-limit på en bestemt peer) ikke vælter hele kaldet.
|
|
3515
|
+
const peerSettled = await Promise.allSettled(peerCvrs.map((peerCvr) => apiRequest(`/company/${peerCvr}`, { include: "finance" })));
|
|
3516
|
+
const peers = peerSettled
|
|
3517
|
+
.filter((r) => r.status === "fulfilled")
|
|
3518
|
+
.map((r) => r.value);
|
|
3519
|
+
const fetchErrors = peerSettled.filter((r) => r.status === "rejected").length;
|
|
3520
|
+
const sample = { revenue: [], profit_margin: [], employees: [], equity: [] };
|
|
3521
|
+
for (const p of peers) {
|
|
3522
|
+
const fin = p.financials?.find((f) => !f.report_type || f.report_type === "annual");
|
|
3523
|
+
if (fin?.revenue != null)
|
|
3524
|
+
sample.revenue.push(Number(fin.revenue));
|
|
3525
|
+
if (fin?.equity != null)
|
|
3526
|
+
sample.equity.push(Number(fin.equity));
|
|
3527
|
+
const ratios = fin?.ratios;
|
|
3528
|
+
if (ratios?.profit_margin != null)
|
|
3529
|
+
sample.profit_margin.push(ratios.profit_margin);
|
|
3530
|
+
// employees from CVR row, not financial
|
|
3531
|
+
const emp = p.employees;
|
|
3532
|
+
if (typeof emp === "number")
|
|
3533
|
+
sample.employees.push(emp);
|
|
3534
|
+
else if (typeof emp === "string" && /^\d+$/.test(emp))
|
|
3535
|
+
sample.employees.push(parseInt(emp, 10));
|
|
3536
|
+
}
|
|
3537
|
+
function percentile(arr, p) {
|
|
3538
|
+
if (arr.length === 0)
|
|
3539
|
+
return null;
|
|
3540
|
+
const sorted = [...arr].sort((a, b) => a - b);
|
|
3541
|
+
const idx = Math.min(sorted.length - 1, Math.floor(p * sorted.length));
|
|
3542
|
+
return sorted[idx];
|
|
3543
|
+
}
|
|
3544
|
+
function rankOf(value, arr) {
|
|
3545
|
+
if (arr.length === 0)
|
|
3546
|
+
return null;
|
|
3547
|
+
const lower = arr.filter((v) => v < value).length;
|
|
3548
|
+
return Math.round((lower / arr.length) * 100);
|
|
3549
|
+
}
|
|
3550
|
+
const stats = {
|
|
3551
|
+
peer_count: peers.length,
|
|
3552
|
+
revenue: {
|
|
3553
|
+
target: targetFin?.revenue ?? null,
|
|
3554
|
+
p25: percentile(sample.revenue, 0.25),
|
|
3555
|
+
median: percentile(sample.revenue, 0.5),
|
|
3556
|
+
p75: percentile(sample.revenue, 0.75),
|
|
3557
|
+
p95: percentile(sample.revenue, 0.95),
|
|
3558
|
+
target_rank_pct: targetFin?.revenue != null ? rankOf(Number(targetFin.revenue), sample.revenue) : null,
|
|
3559
|
+
},
|
|
3560
|
+
profit_margin: {
|
|
3561
|
+
target: targetFin?.ratios?.profit_margin ?? null,
|
|
3562
|
+
p25: percentile(sample.profit_margin, 0.25),
|
|
3563
|
+
median: percentile(sample.profit_margin, 0.5),
|
|
3564
|
+
p75: percentile(sample.profit_margin, 0.75),
|
|
3565
|
+
p95: percentile(sample.profit_margin, 0.95),
|
|
3566
|
+
target_rank_pct: targetFin?.ratios?.profit_margin != null
|
|
3567
|
+
? rankOf(targetFin.ratios.profit_margin, sample.profit_margin)
|
|
3568
|
+
: null,
|
|
3569
|
+
},
|
|
3570
|
+
equity: {
|
|
3571
|
+
target: targetFin?.equity ?? null,
|
|
3572
|
+
p25: percentile(sample.equity, 0.25),
|
|
3573
|
+
median: percentile(sample.equity, 0.5),
|
|
3574
|
+
p75: percentile(sample.equity, 0.75),
|
|
3575
|
+
},
|
|
3576
|
+
};
|
|
3577
|
+
if (format === "json") {
|
|
3578
|
+
return jsonText({
|
|
3579
|
+
target: { cvr, name: target.name, industry_code: targetIndustry, municipality_name: target.municipality_name },
|
|
3580
|
+
peer_query: params,
|
|
3581
|
+
stats,
|
|
3582
|
+
});
|
|
3583
|
+
}
|
|
3584
|
+
const lines = [
|
|
3585
|
+
`# Branche-benchmark: ${target.name} (CVR ${cvr})`,
|
|
3586
|
+
"",
|
|
3587
|
+
`**Branche**: ${target.industry_text} (${targetIndustry})`,
|
|
3588
|
+
`**Region**: ${region === "DK" ? "Landsdækkende" : target.municipality_name || "?"}`,
|
|
3589
|
+
`**Peer sample**: ${peers.length} virksomheder${peers.length < 10 ? " ⚠️ (for få for meningsfulde percentiler)" : ""}${fetchErrors > 0 ? ` (${fetchErrors} peer-opslag fejlede)` : ""}`,
|
|
3590
|
+
"",
|
|
3591
|
+
];
|
|
3592
|
+
const fmtVal = (v, isPct) => v === null ? "—" : isPct ? `${(v * 100).toFixed(1)}%` : dkk(v);
|
|
3593
|
+
const fmtRank = (r) => r === null ? "—" : `${r}% af samplets værdier er lavere`;
|
|
3594
|
+
lines.push("| Metric | Target | p25 | Median | p75 | p95 | Position |");
|
|
3595
|
+
lines.push("| --- | --- | --- | --- | --- | --- | --- |");
|
|
3596
|
+
lines.push(`| Omsætning | ${fmtVal(stats.revenue.target, false)} | ${fmtVal(stats.revenue.p25, false)} | ${fmtVal(stats.revenue.median, false)} | ${fmtVal(stats.revenue.p75, false)} | ${fmtVal(stats.revenue.p95, false)} | ${fmtRank(stats.revenue.target_rank_pct)} |`);
|
|
3597
|
+
lines.push(`| Profit margin | ${fmtVal(stats.profit_margin.target, true)} | ${fmtVal(stats.profit_margin.p25, true)} | ${fmtVal(stats.profit_margin.median, true)} | ${fmtVal(stats.profit_margin.p75, true)} | ${fmtVal(stats.profit_margin.p95, true)} | ${fmtRank(stats.profit_margin.target_rank_pct)} |`);
|
|
3598
|
+
lines.push(`| Egenkapital | ${fmtVal(stats.equity.target, false)} | ${fmtVal(stats.equity.p25, false)} | ${fmtVal(stats.equity.median, false)} | ${fmtVal(stats.equity.p75, false)} | — | — |`);
|
|
3599
|
+
lines.push("");
|
|
3600
|
+
if (peers.length < 10) {
|
|
3601
|
+
lines.push("⚠️ **Peer-sample er for lille** for statistisk meningsfulde percentiler. Prøv at fjerne region-filteret (`region=\"DK\"`) eller hæve `peer_limit`.");
|
|
3602
|
+
}
|
|
3603
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
3604
|
+
}
|
|
3605
|
+
catch (error) {
|
|
3606
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
3607
|
+
}
|
|
3608
|
+
});
|
|
3609
|
+
// ── Tool 29: Dependency analysis ─────────────────────────────────
|
|
3610
|
+
server.registerTool("firmaapi_dependency_analysis", {
|
|
3611
|
+
title: "Registrerede selskabsforbindelser",
|
|
3612
|
+
description: `Vis direkte koncernrelationer og fælles registrerede personer. Henter højst fem personprofiler. Forbindelser dokumenterer ikke økonomisk afhængighed, hæftelse eller konsekvenser ved konkurs. Manglende svar er ikke bevis på manglende relationer.
|
|
3613
|
+
${PLAN.pro}`,
|
|
3614
|
+
inputSchema: {
|
|
3615
|
+
cvr: z.string().regex(/^\d{8}$/, "CVR skal være 8 cifre"),
|
|
3616
|
+
format: FORMAT_SCHEMA,
|
|
3617
|
+
},
|
|
3618
|
+
annotations: {
|
|
3619
|
+
readOnlyHint: true,
|
|
3620
|
+
destructiveHint: false,
|
|
3621
|
+
idempotentHint: true,
|
|
3622
|
+
openWorldHint: true,
|
|
3623
|
+
},
|
|
3624
|
+
}, async ({ cvr, format }) => {
|
|
3625
|
+
try {
|
|
3626
|
+
const target = await apiRequest(`/company/${cvr}`, {
|
|
3627
|
+
include: "relations,history",
|
|
3628
|
+
});
|
|
3629
|
+
const relations = (target.relations || {});
|
|
3630
|
+
const parents = relations.parents || [];
|
|
3631
|
+
const subsidiaries = relations.subsidiaries || [];
|
|
3632
|
+
// Collect key personnel with person_id
|
|
3633
|
+
const keyPeople = [];
|
|
3634
|
+
const addKeyPerson = (name, personId, role) => {
|
|
3635
|
+
const pid = typeof personId === "string" ? personId : null;
|
|
3636
|
+
if (!pid)
|
|
3637
|
+
return;
|
|
3638
|
+
const existing = keyPeople.find((k) => k.person_id === pid);
|
|
3639
|
+
if (existing) {
|
|
3640
|
+
if (!existing.roles.includes(role))
|
|
3641
|
+
existing.roles.push(role);
|
|
3642
|
+
return;
|
|
3643
|
+
}
|
|
3644
|
+
keyPeople.push({ name: String(name || ""), person_id: pid, roles: [role] });
|
|
3645
|
+
};
|
|
3646
|
+
for (const arr of [
|
|
3647
|
+
["executives", "Direktør"],
|
|
3648
|
+
["board_members", "Bestyrelse"],
|
|
3649
|
+
["liquidators", "Likvidator"],
|
|
3650
|
+
["unlimited_liability_partners", "Fuldt ansvarlig deltager"],
|
|
3651
|
+
]) {
|
|
3652
|
+
const items = (target[arr[0]] || []);
|
|
3653
|
+
for (const m of items) {
|
|
3654
|
+
const role = arr[1] + (m.function ? ` (${m.function})` : "");
|
|
3655
|
+
addKeyPerson(m.name, m.person_id, role);
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
const history = (target.history || {});
|
|
3659
|
+
const registerEntries = (history.register_entries || []);
|
|
3660
|
+
for (const entry of registerEntries) {
|
|
3661
|
+
if (entry.valid_to)
|
|
3662
|
+
continue;
|
|
3663
|
+
addKeyPerson(entry.name, entry.person_id, "Legal ejer");
|
|
3664
|
+
}
|
|
3665
|
+
// Limit to top 5 to control quota usage
|
|
3666
|
+
const topPeople = keyPeople.slice(0, 5);
|
|
3667
|
+
// Fetch each person's other affiliations
|
|
3668
|
+
const personSettled = await Promise.allSettled(topPeople.map((p) => apiRequest(`/person/${p.person_id}`)));
|
|
3669
|
+
// Map: other CVR → who connects there
|
|
3670
|
+
const sharedCompanies = new Map();
|
|
3671
|
+
for (let i = 0; i < topPeople.length; i++) {
|
|
3672
|
+
const result = personSettled[i];
|
|
3673
|
+
if (result.status !== "fulfilled")
|
|
3674
|
+
continue;
|
|
3675
|
+
const affiliations = (result.value.affiliations || []);
|
|
3676
|
+
for (const aff of affiliations) {
|
|
3677
|
+
const otherCvr = String(aff.cvr);
|
|
3678
|
+
if (otherCvr === cvr || aff.is_active !== true)
|
|
3679
|
+
continue; // skip target itself + historical roles
|
|
3680
|
+
const entry = sharedCompanies.get(otherCvr) || {
|
|
3681
|
+
name: String(aff.company_name || "(ukendt)"),
|
|
3682
|
+
via: [],
|
|
3683
|
+
};
|
|
3684
|
+
entry.via.push({
|
|
3685
|
+
person: topPeople[i].name,
|
|
3686
|
+
role: String(aff.role_title || "?"),
|
|
3687
|
+
});
|
|
3688
|
+
sharedCompanies.set(otherCvr, entry);
|
|
3689
|
+
}
|
|
3690
|
+
}
|
|
3691
|
+
const totalConnections = parents.length + subsidiaries.length + sharedCompanies.size;
|
|
3692
|
+
if (format === "json") {
|
|
3693
|
+
return jsonText({
|
|
3694
|
+
target: { cvr, name: target.name, status: target.status },
|
|
3695
|
+
parents,
|
|
3696
|
+
subsidiaries,
|
|
3697
|
+
shared_companies: [...sharedCompanies.entries()].map(([c, v]) => ({ cvr: c, ...v })),
|
|
3698
|
+
key_people_analyzed: topPeople.length,
|
|
3699
|
+
total_returned_connections: totalConnections,
|
|
3700
|
+
});
|
|
3701
|
+
}
|
|
3702
|
+
const lines = [
|
|
3703
|
+
`# Afhængighedsanalyse: ${target.name} (CVR ${cvr})`,
|
|
3704
|
+
"",
|
|
3705
|
+
`**Status**: ${target.status}`,
|
|
3706
|
+
`**Antal returnerede forbindelser (kan overlappe)**: ${totalConnections} (${parents.length} moderselskaber, ${subsidiaries.length} datterselskaber, ${sharedCompanies.size} via personoverlap)`,
|
|
3707
|
+
"",
|
|
3708
|
+
];
|
|
3709
|
+
lines.push("## Koncern-relationer", "");
|
|
3710
|
+
if (parents.length === 0 && subsidiaries.length === 0) {
|
|
3711
|
+
lines.push("*Ingen direkte koncernrelationer registreret.*", "");
|
|
3712
|
+
}
|
|
3713
|
+
else {
|
|
3714
|
+
if (parents.length > 0) {
|
|
3715
|
+
lines.push(`### Moderselskaber (${parents.length})`);
|
|
3716
|
+
for (const p of parents) {
|
|
3717
|
+
const parts = [`**${p.name || "(ukendt)"}** (CVR ${p.cvr})`];
|
|
3718
|
+
if (p.ownership_share != null)
|
|
3719
|
+
parts.push(`${p.ownership_share}% ejerandel`);
|
|
3720
|
+
if (p.status)
|
|
3721
|
+
parts.push(`status: ${p.status}`);
|
|
3722
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
3723
|
+
}
|
|
3724
|
+
lines.push("");
|
|
3725
|
+
}
|
|
3726
|
+
if (subsidiaries.length > 0) {
|
|
3727
|
+
lines.push(`### Datterselskaber (${subsidiaries.length})`);
|
|
3728
|
+
for (const s of subsidiaries) {
|
|
3729
|
+
const parts = [`**${s.name || "(ukendt)"}** (CVR ${s.cvr})`];
|
|
3730
|
+
if (s.ownership_share != null)
|
|
3731
|
+
parts.push(`${s.ownership_share}% ejer`);
|
|
3732
|
+
if (s.status)
|
|
3733
|
+
parts.push(`status: ${s.status}`);
|
|
3734
|
+
lines.push(`- ${parts.join(" — ")}`);
|
|
3735
|
+
}
|
|
3736
|
+
lines.push("");
|
|
3737
|
+
}
|
|
3738
|
+
}
|
|
3739
|
+
lines.push("## Personoverlap (delte nøglepersoner)", "");
|
|
3740
|
+
if (topPeople.length === 0) {
|
|
3741
|
+
lines.push("*Ingen nøglepersoner med person_id registreret (kræver Pro+).*", "");
|
|
3742
|
+
}
|
|
3743
|
+
else if (sharedCompanies.size === 0) {
|
|
3744
|
+
lines.push(`*Ingen andre tilknytninger fundet i de tilgængelige svar. Det er ikke dokumentation for fravær af andre relationer.*`, "");
|
|
3745
|
+
}
|
|
3746
|
+
else {
|
|
3747
|
+
lines.push(`*Analyserede ${topPeople.length} nøglepersoner (max 5 for at spare quota). Fundet ${sharedCompanies.size} delte selskaber:*`, "");
|
|
3748
|
+
// Sort by number of connections (most overlapping first)
|
|
3749
|
+
const sorted = [...sharedCompanies.entries()].sort((a, b) => b[1].via.length - a[1].via.length);
|
|
3750
|
+
for (const [otherCvr, info] of sorted.slice(0, 25)) {
|
|
3751
|
+
lines.push(`- **${info.name}** (CVR ${otherCvr}) — ${info.via.length} fælles person${info.via.length > 1 ? "er" : ""}`);
|
|
3752
|
+
for (const v of info.via.slice(0, 3)) {
|
|
3753
|
+
lines.push(` - ${v.person} (${v.role})`);
|
|
3754
|
+
}
|
|
3755
|
+
if (info.via.length > 3)
|
|
3756
|
+
lines.push(` - *... ${info.via.length - 3} flere*`);
|
|
3757
|
+
}
|
|
3758
|
+
if (sorted.length > 25)
|
|
3759
|
+
lines.push(`- *... ${sorted.length - 25} flere selskaber med personoverlap*`);
|
|
3760
|
+
}
|
|
3761
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
3762
|
+
}
|
|
3763
|
+
catch (error) {
|
|
3764
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
3765
|
+
}
|
|
3766
|
+
});
|
|
3767
|
+
// ── Tool 31: Dividend history ────────────────────────────────────
|
|
3768
|
+
server.registerTool("firmaapi_dividend_history", {
|
|
3769
|
+
title: "Udbytte-historik for en virksomhed",
|
|
3770
|
+
description: `Multi-year analyse af et selskabs udbyttebetalinger. Brug ved investor-research,
|
|
3771
|
+
ejer-cashflow-analyse eller "hvor meget er der trukket ud af selskabet over årene".
|
|
3772
|
+
|
|
3773
|
+
Bruger to felter pr. årsregnskab:
|
|
3774
|
+
- **dividends_paid**: Faktisk udbetalt udbytte i året
|
|
3775
|
+
- **proposed_dividend**: Foreslået udbytte (typisk udbetalt året efter på generalforsamling)
|
|
3776
|
+
|
|
3777
|
+
Output:
|
|
3778
|
+
- Sum af alle udbetalte udbytter over alle årsregnskaber
|
|
3779
|
+
- Gennemsnit pr. år (kun år med non-null værdi)
|
|
3780
|
+
- Største enkelt-udbytte i et år
|
|
3781
|
+
- Antal år med udbytte vs uden
|
|
3782
|
+
- Detaljeret tabel pr. år med både paid og proposed
|
|
3783
|
+
- "Pay-out ratio": foreslået udbytte / nettoresultat samme år (DK-konvention:
|
|
3784
|
+
udbytte foreslås på basis af årets resultat, udbetales året efter)
|
|
3785
|
+
|
|
3786
|
+
Edge cases:
|
|
3787
|
+
- Ingen regnskaber → returnerer "Intet at vise"
|
|
3788
|
+
- Alle udbytte-felter null → "Selskabet har ingen registrerede udbytter"
|
|
3789
|
+
- Quarterly/interim reports filtreres fra (kun annual)
|
|
3790
|
+
- Negative dividends_paid (rare, fx tilbageført udbytte) vises som er
|
|
3791
|
+
|
|
3792
|
+
Args:
|
|
3793
|
+
- cvr (string): 8-cifret CVR
|
|
3794
|
+
- format (markdown|json)
|
|
3795
|
+
|
|
3796
|
+
Eksempler:
|
|
3797
|
+
- "Hvor meget udbytte har CVR 12345678 udbetalt?" → cvr="12345678"
|
|
3798
|
+
- "Vis udbytte-historik for Novo Nordisk" → cvr="24256790"
|
|
3799
|
+
|
|
3800
|
+
${PLAN.standard} Standard giver adgang til seneste regnskabsår; Professionel giver adgang til op til 5 års historik. Antallet af tilgængelige regnskaber afhænger af kilden og eventuelle individuelle adgangsgrænser.`,
|
|
3801
|
+
inputSchema: {
|
|
3802
|
+
cvr: z.string().regex(/^\d{8}$/, "CVR skal være 8 cifre"),
|
|
3803
|
+
format: FORMAT_SCHEMA,
|
|
3804
|
+
},
|
|
3805
|
+
annotations: {
|
|
3806
|
+
readOnlyHint: true,
|
|
3807
|
+
destructiveHint: false,
|
|
3808
|
+
idempotentHint: true,
|
|
3809
|
+
openWorldHint: true,
|
|
3810
|
+
},
|
|
3811
|
+
}, async ({ cvr, format }) => {
|
|
3812
|
+
try {
|
|
3813
|
+
const data = await apiRequest(`/company/${cvr}`, { include: "finance" });
|
|
3814
|
+
const fin = (data.financials || []).filter((f) => !f.report_type || f.report_type === "annual");
|
|
3815
|
+
if (fin.length === 0) {
|
|
3816
|
+
const hint = data.financials_pending ? " Regnskaber er ved at blive hentet; prøv igen senere." : " Det betyder ikke i sig selv, at en opgradering vil give flere oplysninger.";
|
|
3817
|
+
return {
|
|
3818
|
+
content: [{
|
|
3819
|
+
type: "text",
|
|
3820
|
+
text: `Ingen årsregnskaber for ${data.name || cvr}.${hint}`,
|
|
3821
|
+
}],
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
// Sort ascending by year for readability
|
|
3825
|
+
fin.sort((a, b) => (a.year || 0) - (b.year || 0));
|
|
3826
|
+
const years = fin.map((f) => {
|
|
3827
|
+
const paid = f.dividends_paid;
|
|
3828
|
+
const proposed = f.proposed_dividend;
|
|
3829
|
+
const profit = f.net_profit;
|
|
3830
|
+
const payoutRatio = proposed != null && profit != null && profit > 0
|
|
3831
|
+
? proposed / profit
|
|
3832
|
+
: null;
|
|
3833
|
+
return {
|
|
3834
|
+
year: Number(f.year),
|
|
3835
|
+
period_end: String(f.period_end || ""),
|
|
3836
|
+
dividends_paid: paid ?? null,
|
|
3837
|
+
proposed_dividend: proposed ?? null,
|
|
3838
|
+
net_profit: profit ?? null,
|
|
3839
|
+
payout_ratio: payoutRatio,
|
|
3840
|
+
};
|
|
3841
|
+
});
|
|
3842
|
+
const yearsWithPaid = years.filter((y) => y.dividends_paid != null);
|
|
3843
|
+
const totalPaid = yearsWithPaid.reduce((sum, y) => sum + y.dividends_paid, 0);
|
|
3844
|
+
const avgPaid = yearsWithPaid.length ? totalPaid / yearsWithPaid.length : null;
|
|
3845
|
+
const maxPaidYear = yearsWithPaid.reduce((max, y) => max == null || y.dividends_paid > max.dividends_paid ? y : max, null);
|
|
3846
|
+
const totalYears = years.length;
|
|
3847
|
+
const yearsWithoutPaid = totalYears - yearsWithPaid.length;
|
|
3848
|
+
// Has proposed-but-no-paid mismatch detection (proposed in year N, no paid in N+1?)
|
|
3849
|
+
const upcomingProposed = years[years.length - 1];
|
|
3850
|
+
const hasUpcomingProposed = upcomingProposed?.proposed_dividend != null && upcomingProposed.proposed_dividend > 0;
|
|
3851
|
+
if (format === "json") {
|
|
3852
|
+
return jsonText({
|
|
3853
|
+
cvr,
|
|
3854
|
+
name: data.name,
|
|
3855
|
+
summary: {
|
|
3856
|
+
years_analyzed: totalYears,
|
|
3857
|
+
years_with_dividend: yearsWithPaid.length,
|
|
3858
|
+
years_without_dividend: yearsWithoutPaid,
|
|
3859
|
+
total_paid: totalPaid,
|
|
3860
|
+
average_paid_per_payout_year: avgPaid,
|
|
3861
|
+
max_single_year: maxPaidYear ? { year: maxPaidYear.year, amount: maxPaidYear.dividends_paid } : null,
|
|
3862
|
+
upcoming_proposed: hasUpcomingProposed ? { year: upcomingProposed.year, amount: upcomingProposed.proposed_dividend } : null,
|
|
3863
|
+
},
|
|
3864
|
+
years,
|
|
3865
|
+
});
|
|
3866
|
+
}
|
|
3867
|
+
const lines = [`# Udbytte-historik: ${data.name} (CVR ${cvr})`, ""];
|
|
3868
|
+
if (yearsWithPaid.length === 0) {
|
|
3869
|
+
lines.push(`Selskabet har ingen registrerede udbyttebetalinger over ${totalYears} år${totalYears !== 1 ? "" : ""}.`);
|
|
3870
|
+
if (hasUpcomingProposed) {
|
|
3871
|
+
lines.push("");
|
|
3872
|
+
lines.push(`📋 **Forventet**: ${dkk(upcomingProposed.proposed_dividend)} foreslået for regnskabsåret ${upcomingProposed.year} (typisk udbetalt næste år).`);
|
|
3873
|
+
}
|
|
3874
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
3875
|
+
}
|
|
3876
|
+
lines.push("## Sammenfatning", "");
|
|
3877
|
+
lines.push(`- **Total udbetalt** over ${totalYears} år: ${dkk(totalPaid)}`);
|
|
3878
|
+
lines.push(`- **År med udbytte**: ${yearsWithPaid.length}/${totalYears}`);
|
|
3879
|
+
if (avgPaid != null)
|
|
3880
|
+
lines.push(`- **Gennemsnit pr. udbetalingsår**: ${dkk(avgPaid)}`);
|
|
3881
|
+
if (maxPaidYear)
|
|
3882
|
+
lines.push(`- **Største enkelt-udbytte**: ${dkk(maxPaidYear.dividends_paid)} (${maxPaidYear.year})`);
|
|
3883
|
+
if (hasUpcomingProposed) {
|
|
3884
|
+
lines.push(`- 📋 **Foreslået for ${upcomingProposed.year}** (typisk udbetalt næste år): ${dkk(upcomingProposed.proposed_dividend)}`);
|
|
3885
|
+
}
|
|
3886
|
+
lines.push("");
|
|
3887
|
+
lines.push("## År-for-år");
|
|
3888
|
+
lines.push("");
|
|
3889
|
+
lines.push("| År | Udbetalt | Foreslået | Nettoresultat | Pay-out ratio |");
|
|
3890
|
+
lines.push("| --- | ---: | ---: | ---: | ---: |");
|
|
3891
|
+
for (const y of years) {
|
|
3892
|
+
const paidStr = y.dividends_paid != null ? dkk(y.dividends_paid) : "—";
|
|
3893
|
+
const proposedStr = y.proposed_dividend != null ? dkk(y.proposed_dividend) : "—";
|
|
3894
|
+
const profitStr = y.net_profit != null ? dkk(y.net_profit) : "—";
|
|
3895
|
+
const ratioStr = y.payout_ratio != null ? pct(y.payout_ratio) : "—";
|
|
3896
|
+
lines.push(`| ${y.year} | ${paidStr} | ${proposedStr} | ${profitStr} | ${ratioStr} |`);
|
|
3897
|
+
}
|
|
3898
|
+
return { content: [{ type: "text", text: truncate(lines.join("\n")) }] };
|
|
3899
|
+
}
|
|
3900
|
+
catch (error) {
|
|
3901
|
+
return { content: [{ type: "text", text: handleApiError(error) }], isError: true };
|
|
3902
|
+
}
|
|
3903
|
+
});
|
|
3904
|
+
const EXPLAIN_CATALOG = new Map();
|
|
3905
|
+
function addEntry(keys, entry) {
|
|
3906
|
+
for (const key of keys) {
|
|
3907
|
+
const upper = key.toUpperCase();
|
|
3908
|
+
EXPLAIN_CATALOG.set(upper, entry);
|
|
3909
|
+
// Også registrér underscore-normaliseret variant så "UNDER KONKURS" og
|
|
3910
|
+
// "UNDER_KONKURS" begge matcher direkte (uden at falde tilbage på fuzzy
|
|
3911
|
+
// suggestions). Strip også trailing period for konsistens.
|
|
3912
|
+
const normalized = upper.replace(/[-\s]+/g, "_").replace(/\.$/, "");
|
|
3913
|
+
if (normalized !== upper)
|
|
3914
|
+
EXPLAIN_CATALOG.set(normalized, entry);
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
// Selskabsformer (company_type)
|
|
3918
|
+
addEntry(["APS", "ANPARTSSELSKAB"], {
|
|
3919
|
+
category: "Selskabsform",
|
|
3920
|
+
description: "Anpartsselskab — den mest almindelige selskabsform i Danmark for SMV. Mindste anpartskapital er 40.000 DKK. Begrænset hæftelse.",
|
|
3921
|
+
related: ["A/S", "IVS", "P/S"],
|
|
3922
|
+
});
|
|
3923
|
+
addEntry(["A/S", "AKTIESELSKAB"], {
|
|
3924
|
+
category: "Selskabsform",
|
|
3925
|
+
description: "Aktieselskab — typisk for større virksomheder. Mindste selskabskapital er 400.000 DKK. Begrænset hæftelse. Kan børsnoteres.",
|
|
3926
|
+
related: ["ApS", "P/S"],
|
|
3927
|
+
});
|
|
3928
|
+
addEntry(["IVS", "IVÆRKSÆTTERSELSKAB"], {
|
|
3929
|
+
category: "Selskabsform",
|
|
3930
|
+
description: "Iværksætterselskab — historisk lavkapital-selskabsform (1 DKK), afskaffet i 2019. Eksisterende IVS skulle omdannes til ApS senest 2021.",
|
|
3931
|
+
related: ["ApS"],
|
|
3932
|
+
});
|
|
3933
|
+
addEntry(["P/S", "PARTNERSELSKAB"], {
|
|
3934
|
+
category: "Selskabsform",
|
|
3935
|
+
description: "Partnerselskab (Kommanditaktieselskab) — kombinerer aktieselskabs-struktur med personlig hæftelse for komplementaren.",
|
|
3936
|
+
});
|
|
3937
|
+
addEntry(["K/S", "KOMMANDITSELSKAB"], {
|
|
3938
|
+
category: "Selskabsform",
|
|
3939
|
+
description: "Kommanditselskab — interessentskab med både fuldt ansvarlige (komplementarer) og begrænsede (kommanditister) deltagere.",
|
|
3940
|
+
related: ["I/S"],
|
|
3941
|
+
});
|
|
3942
|
+
addEntry(["I/S", "INTERESSENTSKAB"], {
|
|
3943
|
+
category: "Selskabsform",
|
|
3944
|
+
description: "Interessentskab — selskab med 2+ fuldt ansvarlige personlige interessenter. Hæfter personligt og solidarisk.",
|
|
3945
|
+
});
|
|
3946
|
+
addEntry(["ENK", "ENKELTMANDSVIRKSOMHED"], {
|
|
3947
|
+
category: "Selskabsform",
|
|
3948
|
+
description: "Enkeltmandsvirksomhed — én ejer der hæfter personligt. Ingen selskabskapital. Ejeren beskattes som personlig indkomst.",
|
|
3949
|
+
});
|
|
3950
|
+
addEntry(["FOND"], {
|
|
3951
|
+
category: "Selskabsform",
|
|
3952
|
+
description: "Erhvervsdrivende fond — selvejende juridisk enhed uden ejere. Kan eje aktier i selskaber (typisk holding-strukturer).",
|
|
3953
|
+
});
|
|
3954
|
+
// Status-værdier
|
|
3955
|
+
addEntry(["AKTIV", "NORMAL"], {
|
|
3956
|
+
category: "Status",
|
|
3957
|
+
description: "Virksomheden er aktivt registreret i CVR. Driver erhverv eller er klar til det. Standard-status for langt de fleste selskaber.",
|
|
3958
|
+
});
|
|
3959
|
+
addEntry(["UNDER_KONKURS", "UNDER KONKURS"], {
|
|
3960
|
+
category: "Status",
|
|
3961
|
+
description: "Konkursbehandling er indledt. Boet administreres af kurator. Virksomheden kan stadig findes i CVR men driften er typisk standset.",
|
|
3962
|
+
related: ["OPLØST_EFTER_KONKURS", "TVANGSOPLØST"],
|
|
3963
|
+
});
|
|
3964
|
+
addEntry(["OPLØST_EFTER_KONKURS", "OPLØST EFTER KONKURS"], {
|
|
3965
|
+
category: "Status",
|
|
3966
|
+
description: "Konkursbehandlingen er afsluttet og selskabet slettet fra registeret. Hæftelse for fordringer er typisk afskåret efter kreditor-behandling.",
|
|
3967
|
+
related: ["UNDER_KONKURS"],
|
|
3968
|
+
});
|
|
3969
|
+
addEntry(["TVANGSOPLØST"], {
|
|
3970
|
+
category: "Status",
|
|
3971
|
+
description: "Virksomheden er tvangsopløst (typisk fordi den ikke har indberettet regnskab eller mangler ledelse). Adskiller sig fra konkurs ved at der ikke nødvendigvis er insolvens.",
|
|
3972
|
+
related: ["UNDER_TVANGSOPLØSNING"],
|
|
3973
|
+
});
|
|
3974
|
+
addEntry(["UNDER_TVANGSOPLØSNING", "UNDER TVANGSOPLØSNING"], {
|
|
3975
|
+
category: "Status",
|
|
3976
|
+
description: "Erhvervsstyrelsen har anmodet skifteretten om tvangsopløsning. Selskabet får frist til at undgå opløsning ved at indberette regnskab eller udnævne ny ledelse.",
|
|
3977
|
+
});
|
|
3978
|
+
addEntry(["UNDER_FRIVILLIG_LIKVIDATION", "UNDER FRIVILLIG LIKVIDATION"], {
|
|
3979
|
+
category: "Status",
|
|
3980
|
+
description: "Generalforsamlingen har besluttet at opløse selskabet ordentligt. Aktiver realiseres, kreditorer betales, og restformue udloddes til ejerne.",
|
|
3981
|
+
related: ["LIKVIDATOR"],
|
|
3982
|
+
});
|
|
3983
|
+
addEntry(["UNDER_REKONSTRUKTION", "UNDER REKONSTRUKTION"], {
|
|
3984
|
+
category: "Status",
|
|
3985
|
+
description: "Virksomheden har søgt om rekonstruktionsbehandling for at undgå konkurs. Kreditorer kan tvinges til afdrags- eller akkordordninger.",
|
|
3986
|
+
});
|
|
3987
|
+
addEntry(["OPHØRT"], {
|
|
3988
|
+
category: "Status",
|
|
3989
|
+
description: "Virksomheden er ophørt — typisk efter ordentlig opløsning eller virksomhedsoverdragelse. Adskiller sig fra konkurs ved at være planlagt.",
|
|
3990
|
+
});
|
|
3991
|
+
// Regnskabsklasse
|
|
3992
|
+
addEntry(["A", "REGNSKABSKLASSE_A", "ACCOUNTING_CLASS_A"], {
|
|
3993
|
+
category: "Regnskabsklasse",
|
|
3994
|
+
description: "Klasse A — personligt ejede virksomheder (typisk enkeltmandsvirksomheder). Ingen lovpligtigt regnskab i CVR.",
|
|
3995
|
+
});
|
|
3996
|
+
addEntry(["B", "REGNSKABSKLASSE_B", "ACCOUNTING_CLASS_B"], {
|
|
3997
|
+
category: "Regnskabsklasse",
|
|
3998
|
+
description: "Klasse B — små virksomheder. Forenklet regnskabsindberetning. Grænser (2024): omsætning < 89M DKK, balance < 44M DKK, ansatte < 50.",
|
|
3999
|
+
related: ["C", "D"],
|
|
4000
|
+
});
|
|
4001
|
+
addEntry(["C", "REGNSKABSKLASSE_C", "ACCOUNTING_CLASS_C"], {
|
|
4002
|
+
category: "Regnskabsklasse",
|
|
4003
|
+
description: "Klasse C — mellemstore virksomheder. Fuld regnskabsindberetning. Grænser (2024): omsætning 89M-313M, balance 44M-156M, ansatte 50-250.",
|
|
4004
|
+
related: ["B", "D"],
|
|
4005
|
+
});
|
|
4006
|
+
addEntry(["D", "REGNSKABSKLASSE_D", "ACCOUNTING_CLASS_D"], {
|
|
4007
|
+
category: "Regnskabsklasse",
|
|
4008
|
+
description: "Klasse D — store virksomheder + alle børsnoterede selskaber. Mest detaljeret indberetning. Grænser overskredet eller børsnotering.",
|
|
4009
|
+
related: ["B", "C"],
|
|
4010
|
+
});
|
|
4011
|
+
// Beskæftigelses-bracketkoder
|
|
4012
|
+
addEntry(["ANTAL_0", "INTERVAL_KODE_0"], {
|
|
4013
|
+
category: "Ansatte-interval",
|
|
4014
|
+
description: "0 ansatte — typisk personligt ejede virksomheder eller dormante selskaber.",
|
|
4015
|
+
});
|
|
4016
|
+
addEntry(["ANTAL_1", "INTERVAL_KODE_1"], {
|
|
4017
|
+
category: "Ansatte-interval",
|
|
4018
|
+
description: "1 ansat — typisk solo-iværksætter på løn eller selskab med 1 medarbejder.",
|
|
4019
|
+
});
|
|
4020
|
+
addEntry(["ANTAL_2_4", "INTERVAL_KODE_2_4"], {
|
|
4021
|
+
category: "Ansatte-interval",
|
|
4022
|
+
description: "2-4 ansatte — meget små virksomheder.",
|
|
4023
|
+
});
|
|
4024
|
+
addEntry(["ANTAL_5_9", "INTERVAL_KODE_5_9"], {
|
|
4025
|
+
category: "Ansatte-interval",
|
|
4026
|
+
description: "5-9 ansatte.",
|
|
4027
|
+
});
|
|
4028
|
+
addEntry(["ANTAL_10_19", "INTERVAL_KODE_10_19"], {
|
|
4029
|
+
category: "Ansatte-interval",
|
|
4030
|
+
description: "10-19 ansatte — mikrovirksomheder.",
|
|
4031
|
+
});
|
|
4032
|
+
addEntry(["ANTAL_20_49", "INTERVAL_KODE_20_49"], {
|
|
4033
|
+
category: "Ansatte-interval",
|
|
4034
|
+
description: "20-49 ansatte — små virksomheder.",
|
|
4035
|
+
});
|
|
4036
|
+
addEntry(["ANTAL_50_99", "INTERVAL_KODE_50_99"], {
|
|
4037
|
+
category: "Ansatte-interval",
|
|
4038
|
+
description: "50-99 ansatte — på grænsen mellem små og mellemstore.",
|
|
4039
|
+
});
|
|
4040
|
+
addEntry(["ANTAL_100_199", "INTERVAL_KODE_100_199"], {
|
|
4041
|
+
category: "Ansatte-interval",
|
|
4042
|
+
description: "100-199 ansatte — mellemstore virksomheder.",
|
|
4043
|
+
});
|
|
4044
|
+
addEntry(["ANTAL_200_499", "INTERVAL_KODE_200_499"], {
|
|
4045
|
+
category: "Ansatte-interval",
|
|
4046
|
+
description: "200-499 ansatte — store virksomheder.",
|
|
4047
|
+
});
|
|
4048
|
+
addEntry(["ANTAL_500_999", "INTERVAL_KODE_500_999"], {
|
|
4049
|
+
category: "Ansatte-interval",
|
|
4050
|
+
description: "500-999 ansatte — meget store virksomheder.",
|
|
4051
|
+
});
|
|
4052
|
+
addEntry(["ANTAL_1000_PLUS", "INTERVAL_KODE_1000_PLUS"], {
|
|
4053
|
+
category: "Ansatte-interval",
|
|
4054
|
+
description: "1000+ ansatte — koncerner og store nationale arbejdsgivere.",
|
|
4055
|
+
});
|
|
4056
|
+
// FUNKTION-værdier
|
|
4057
|
+
addEntry(["DIREKTØR"], {
|
|
4058
|
+
category: "FUNKTION",
|
|
4059
|
+
description: "Person tegningsberettiget på direktør-niveau. Repræsenterer selskabet juridisk og driver den daglige ledelse.",
|
|
4060
|
+
related: ["ADM_DIR", "DIREKTION"],
|
|
4061
|
+
});
|
|
4062
|
+
addEntry(["ADM_DIR", "ADM. DIR.", "ADMINISTRERENDE DIREKTØR"], {
|
|
4063
|
+
category: "FUNKTION",
|
|
4064
|
+
description: "Administrerende direktør (CEO) — øverste daglige ledelse, typisk indstillet af bestyrelsen. Findes i selskaber med både direktion og bestyrelse.",
|
|
4065
|
+
});
|
|
4066
|
+
addEntry(["BESTYRELSESMEDLEM", "BESTYRELSE"], {
|
|
4067
|
+
category: "FUNKTION",
|
|
4068
|
+
description: "Medlem af bestyrelsen. Ansvarlig for strategisk overordnet ledelse + tilsyn med direktionen. Vælges typisk af generalforsamlingen.",
|
|
4069
|
+
related: ["FORMAND", "NÆSTFORMAND", "SUPPLEANT"],
|
|
4070
|
+
});
|
|
4071
|
+
addEntry(["FORMAND", "BESTYRELSESFORMAND"], {
|
|
4072
|
+
category: "FUNKTION",
|
|
4073
|
+
description: "Bestyrelsesformand — leder bestyrelsens arbejde, indkalder til møder, har typisk udslagsgivende stemme.",
|
|
4074
|
+
});
|
|
4075
|
+
addEntry(["NÆSTFORMAND"], {
|
|
4076
|
+
category: "FUNKTION",
|
|
4077
|
+
description: "Næstformand — træder i formandens sted ved fravær.",
|
|
4078
|
+
});
|
|
4079
|
+
addEntry(["SUPPLEANT"], {
|
|
4080
|
+
category: "FUNKTION",
|
|
4081
|
+
description: "Suppleant — træder ind i bestyrelse/direktion ved en primær persons fratræden. SUPPLEANT_FOR_DELTAGER_NR-attributten peger på den primære persons enhedsnummer.",
|
|
4082
|
+
});
|
|
4083
|
+
addEntry(["LIKVIDATOR"], {
|
|
4084
|
+
category: "FUNKTION",
|
|
4085
|
+
description: "Likvidator — udnævnt til at afvikle selskabet under frivillig likvidation. Realiserer aktiver, betaler kreditorer, udlodder restformue.",
|
|
4086
|
+
related: ["UNDER_FRIVILLIG_LIKVIDATION"],
|
|
4087
|
+
});
|
|
4088
|
+
addEntry(["STIFTER", "STIFTERE"], {
|
|
4089
|
+
category: "FUNKTION",
|
|
4090
|
+
description: "Person eller selskab der har stiftet virksomheden. Historisk rolle — efter stiftelse er stifteren ikke nødvendigvis aktiv i selskabet.",
|
|
4091
|
+
});
|
|
4092
|
+
addEntry(["INTERESSENTER"], {
|
|
4093
|
+
category: "FUNKTION",
|
|
4094
|
+
description: "Fuldt ansvarlig deltager i interessentskab (I/S) eller enkeltmandsvirksomhed. Hæfter personligt for selskabets gæld.",
|
|
4095
|
+
});
|
|
4096
|
+
addEntry(["BÆREDYGTIGHEDSREVISION"], {
|
|
4097
|
+
category: "FUNKTION",
|
|
4098
|
+
description: "Bæredygtighedsrevisor — revisor specifikt valgt til at revidere bæredygtigheds-/ESG-rapportering. Krav for store virksomheder under CSRD.",
|
|
4099
|
+
});
|
|
4100
|
+
// hovedtype-værdier
|
|
4101
|
+
addEntry(["LEDELSESORGAN"], {
|
|
4102
|
+
category: "Hovedtype",
|
|
4103
|
+
description: "Den samlede juridiske ledelse — direktion + bestyrelse + suppleanter + likvidatorer. Splittes i FirmaAPI ud i executives, board_members, alternates, liquidators baseret på FUNKTION.",
|
|
4104
|
+
});
|
|
4105
|
+
addEntry(["REVISION"], {
|
|
4106
|
+
category: "Hovedtype",
|
|
4107
|
+
description: "Statsautoriseret eller registreret revisor. Påtegner årsregnskabet (eller mangel på det hvis revision er fravalgt).",
|
|
4108
|
+
related: ["REVISION_FRAVALGT", "BÆREDYGTIGHEDSREVISION"],
|
|
4109
|
+
});
|
|
4110
|
+
addEntry(["REGISTER", "EJERREGISTER"], {
|
|
4111
|
+
category: "Hovedtype",
|
|
4112
|
+
description: "Officielt ejerregister — registrering af legale ejere/ejerandele over tærskler (typisk 5%/10%/25%/50% kapital eller stemmeret). Eksponeret som register_entries i FirmaAPI.",
|
|
4113
|
+
});
|
|
4114
|
+
addEntry(["FULDT_ANSVARLIG_DELTAGERE"], {
|
|
4115
|
+
category: "Hovedtype",
|
|
4116
|
+
description: "Fuldt ansvarlige deltagere — interessenter i I/S, komplementarer i K/S, eller ejer af enkeltmandsvirksomhed. Hæfter personligt og solidarisk.",
|
|
4117
|
+
});
|
|
4118
|
+
// ERST-attributter
|
|
4119
|
+
addEntry(["BØRSNOTERET"], {
|
|
4120
|
+
category: "ERST-attribut",
|
|
4121
|
+
description: "Boolean — angiver om selskabets aktier handles på en regulated market (typisk Nasdaq Copenhagen). Påvirker rapporteringskrav.",
|
|
4122
|
+
});
|
|
4123
|
+
addEntry(["KAPITAL"], {
|
|
4124
|
+
category: "ERST-attribut",
|
|
4125
|
+
description: "Selskabskapital i hovedvalutaen (typisk DKK). For ApS minimum 40.000, A/S minimum 400.000.",
|
|
4126
|
+
});
|
|
4127
|
+
addEntry(["KAPITALKLASSER"], {
|
|
4128
|
+
category: "ERST-attribut",
|
|
4129
|
+
description: "Boolean — angiver om selskabet har flere aktieklasser (fx A og B-aktier med forskellige stemmerettigheder).",
|
|
4130
|
+
});
|
|
4131
|
+
addEntry(["TEGNINGSREGEL"], {
|
|
4132
|
+
category: "ERST-attribut",
|
|
4133
|
+
description: "Tekstuel beskrivelse af hvem der kan tegne selskabet juridisk (fx 'tegnes af direktøren alene' eller 'tegnes af bestyrelsesformand sammen med en direktør').",
|
|
4134
|
+
});
|
|
4135
|
+
addEntry(["VEDTÆGT_SENESTE"], {
|
|
4136
|
+
category: "ERST-attribut",
|
|
4137
|
+
description: "ISO-dato for seneste vedtægtsændring registreret i CVR.",
|
|
4138
|
+
});
|
|
4139
|
+
addEntry(["REVISION_FRAVALGT"], {
|
|
4140
|
+
category: "ERST-attribut",
|
|
4141
|
+
description: "Boolean — angiver om selskabet har fravalgt revision (kun muligt for klasse B-selskaber under visse størrelseskrav). Lavere data-pålidelighed på regnskabet.",
|
|
4142
|
+
});
|
|
4143
|
+
addEntry(["OPLØSNINGSTRUSSEL_SENESTE"], {
|
|
4144
|
+
category: "ERST-attribut",
|
|
4145
|
+
description: "ISO-dato for seneste registrerede opløsningstrussel — hvor Erhvervsstyrelsen har varslet tvangsopløsning. Registreret oplysning, ikke en vurdering.",
|
|
4146
|
+
});
|
|
4147
|
+
addEntry(["OMFATTET_AF_LOV_OM_HVIDVASK_OG_TERRORFINANSIERING", "AML"], {
|
|
4148
|
+
category: "ERST-attribut",
|
|
4149
|
+
description: "Tekstuel ('OMFATTET'/'IKKE_OMFATTET') — angiver om selskabet er omfattet af hvidvaskloven (typisk finans, ejendom, advokater, revisorer m.fl.).",
|
|
4150
|
+
});
|
|
4151
|
+
addEntry(["FORMÅL", "FORMAAL"], {
|
|
4152
|
+
category: "ERST-attribut",
|
|
4153
|
+
description: "Selskabets vedtægts-formål — fritekst der beskriver hvad selskabet må beskæftige sig med (fx 'at drive virksomhed med IT-konsulentydelser').",
|
|
4154
|
+
});
|
|
4155
|
+
addEntry(["PSEUDOCVRNR", "HAS_PSEUDO_CVR"], {
|
|
4156
|
+
category: "ERST-attribut",
|
|
4157
|
+
description: "Boolean — angiver om virksomheden har et pseudo-CVR (intern reference til en anden virksomhed eller historisk identitet).",
|
|
4158
|
+
});
|
|
4159
|
+
addEntry(["NAVN_IDENTITET"], {
|
|
4160
|
+
category: "ERST-attribut",
|
|
4161
|
+
description: "Tekstuel — virksomhedens 'identitetsnavn' brugt internt i ERST. Sjælden attribut.",
|
|
4162
|
+
});
|
|
4163
|
+
addEntry(["ARKIV_REGISTRERINGSNUMMER"], {
|
|
4164
|
+
category: "ERST-attribut",
|
|
4165
|
+
description: "Historisk registreringsnummer fra før CVR-systemet (fx 'A/S16201'). Bruges af de ældste selskaber til arkiv-opslag.",
|
|
4166
|
+
});
|
|
4167
|
+
// VAERDITYPE-koder
|
|
4168
|
+
addEntry(["BOOLEAN"], {
|
|
4169
|
+
category: "Vaerditype",
|
|
4170
|
+
description: "Boolean attributværdi — typisk strenge 'true' eller 'false' (kategorisk OMFATTET/IKKE_OMFATTET for hvidvask).",
|
|
4171
|
+
});
|
|
4172
|
+
addEntry(["DECIMAL"], {
|
|
4173
|
+
category: "Vaerditype",
|
|
4174
|
+
description: "Decimaltal som streng (fx '446500000.00' for kapital). Parses som number.",
|
|
4175
|
+
});
|
|
4176
|
+
addEntry(["DATE"], {
|
|
4177
|
+
category: "Vaerditype",
|
|
4178
|
+
description: "ISO-dato YYYY-MM-DD som streng.",
|
|
4179
|
+
});
|
|
4180
|
+
addEntry(["STRING"], {
|
|
4181
|
+
category: "Vaerditype",
|
|
4182
|
+
description: "Fritekst.",
|
|
4183
|
+
});
|
|
4184
|
+
// Andre
|
|
4185
|
+
addEntry(["VALGFORM"], {
|
|
4186
|
+
category: "ERST-attribut",
|
|
4187
|
+
description: "Hvordan et bestyrelsesmedlem er valgt: 'GENERALFORSAMLING' (af aktionærerne), 'MEDARBEJDERE_I_SELSKABET' (medarbejderrepræsentant), 'KONCERN_MEDARBEJDERE' (koncernmedarbejderrepræsentant) m.fl.",
|
|
4188
|
+
});
|
|
4189
|
+
addEntry(["EJERANDEL_PROCENT"], {
|
|
4190
|
+
category: "Ejerregister",
|
|
4191
|
+
description: "Procent af kapitalen ejet af denne deltager (0-100). Brugt til CSR/AML/skatteberegning.",
|
|
4192
|
+
});
|
|
4193
|
+
addEntry(["EJERANDEL_STEMMERET_PROCENT"], {
|
|
4194
|
+
category: "Ejerregister",
|
|
4195
|
+
description: "Procent af stemmerne kontrolleret af denne deltager. Kan afvige fra ejerandel ved A/B-aktier med forskellige stemmerettigheder.",
|
|
4196
|
+
});
|
|
4197
|
+
addEntry(["EJERANDEL_KAPITALKLASSE"], {
|
|
4198
|
+
category: "Ejerregister",
|
|
4199
|
+
description: "Hvilken aktieklasse denne ejerandel tilhører (fx 'A' eller 'B' for selskaber med flere kapitalklasser).",
|
|
4200
|
+
});
|
|
4201
|
+
addEntry(["EJERANDEL_MEDDELELSE_DATO"], {
|
|
4202
|
+
category: "Ejerregister",
|
|
4203
|
+
description: "Dato hvor ejerskabet blev anmeldt til ejerregisteret.",
|
|
4204
|
+
});
|
|
4205
|
+
addEntry(["AD_PROTECTED", "REKLAMEBESKYTTET"], {
|
|
4206
|
+
category: "CompanyData-felt",
|
|
4207
|
+
description: "Boolean — virksomheden har valgt at være beskyttet mod uopfordret markedsføring. På Free-plan returneres ingen kontaktoplysninger; på Standard+ returneres alt, men brugeren har ansvar for ikke at sende reklame.",
|
|
4208
|
+
});
|
|
4209
|
+
addEntry(["DB07", "BRANCHEKODE"], {
|
|
4210
|
+
category: "Klassifikation",
|
|
4211
|
+
description: "Dansk Branchekode 2007 — 6-cifret hierarkisk kode der kategoriserer virksomheder efter aktivitet. Eksempel: 62.01.00 = 'Computerprogrammering'. Prefix-match støttes (fx '62' = alle IT-brancher).",
|
|
4212
|
+
});
|
|
4213
|
+
server.registerTool("firmaapi_explain_field", {
|
|
4214
|
+
title: "Forklar et CVR/ERST-felt eller værdi",
|
|
4215
|
+
description: `Slå op i et statisk feltkatalog over CVR-, ERST- og FirmaAPI-specifikke
|
|
4216
|
+
termer, koder og enums. Returnerer beskrivelse, kategori og relaterede termer.
|
|
4217
|
+
|
|
4218
|
+
Kataloget dækker:
|
|
4219
|
+
- **Selskabsformer**: ApS, A/S, IVS, P/S, K/S, I/S, Enk, Fond
|
|
4220
|
+
- **Status-værdier**: Aktiv, Under konkurs, Tvangsopløst, Under rekonstruktion m.fl.
|
|
4221
|
+
- **Regnskabsklasser**: A/B/C/D med tærskler
|
|
4222
|
+
- **Ansatte-intervaller**: ANTAL_0 → ANTAL_1000_PLUS
|
|
4223
|
+
- **FUNKTION-roller**: Direktør, Bestyrelsesmedlem, Suppleant, Likvidator m.fl.
|
|
4224
|
+
- **Hovedtyper**: LEDELSESORGAN, REVISION, REGISTER, FULDT_ANSVARLIG_DELTAGERE
|
|
4225
|
+
- **ERST-attributter**: BØRSNOTERET, KAPITAL, TEGNINGSREGEL, OMFATTET_AF_LOV_OM_HVIDVASK m.fl.
|
|
4226
|
+
- **Ejerregister-felter**: EJERANDEL_PROCENT, _STEMMERET, _KAPITALKLASSE
|
|
4227
|
+
- **CompanyData-felter**: ad_protected, has_pseudo_cvr m.fl.
|
|
4228
|
+
- **Tekniske termer**: vaerditype, branchekode (DB07)
|
|
4229
|
+
|
|
4230
|
+
Brug ved tvivl om hvad en værdi betyder, eller hvis LLM møder ukendte
|
|
4231
|
+
ERST-koder under analyse af raw data.
|
|
4232
|
+
|
|
4233
|
+
Lookup er case-insensitiv og tolerant for whitespace + bindestreger
|
|
4234
|
+
(fx "Under konkurs", "UNDER_KONKURS", "under-konkurs" alle matcher).
|
|
4235
|
+
|
|
4236
|
+
Args:
|
|
4237
|
+
- field (string): feltnavn, kode-værdi eller selskabsforkortelse at slå op
|
|
4238
|
+
- format (markdown|json)
|
|
4239
|
+
|
|
4240
|
+
Eksempler:
|
|
4241
|
+
- "Hvad betyder UNDER KONKURS?" → field="UNDER KONKURS"
|
|
4242
|
+
- "Forklar regnskabsklasse C" → field="C"
|
|
4243
|
+
- "Hvad er ANTAL_50_99?" → field="ANTAL_50_99"
|
|
4244
|
+
- "Forklar BÆREDYGTIGHEDSREVISION" → field="BÆREDYGTIGHEDSREVISION"
|
|
4245
|
+
|
|
4246
|
+
${PLAN.any} Pure compute — ingen API-kald, ingen quota-omkostning.`,
|
|
4247
|
+
inputSchema: {
|
|
4248
|
+
field: z.string().min(1, "Field-navn må ikke være tom").describe("Feltnavn, kode eller selskabsforkortelse"),
|
|
4249
|
+
format: FORMAT_SCHEMA,
|
|
4250
|
+
},
|
|
4251
|
+
annotations: {
|
|
4252
|
+
readOnlyHint: true,
|
|
4253
|
+
destructiveHint: false,
|
|
4254
|
+
idempotentHint: true,
|
|
4255
|
+
openWorldHint: false, // pure compute, no external interaction
|
|
4256
|
+
},
|
|
4257
|
+
}, async ({ field, format }) => {
|
|
4258
|
+
// Normalize input: trim, uppercase, replace dashes/spaces with underscores
|
|
4259
|
+
const normalized = field
|
|
4260
|
+
.trim()
|
|
4261
|
+
.toUpperCase()
|
|
4262
|
+
.replace(/[-\s]+/g, "_")
|
|
4263
|
+
.replace(/\.$/, ""); // strip trailing period
|
|
4264
|
+
// Try direct lookup
|
|
4265
|
+
let entry = EXPLAIN_CATALOG.get(normalized);
|
|
4266
|
+
let matchedKey = normalized;
|
|
4267
|
+
// Try with original spacing (some keys have spaces, e.g. "UNDER KONKURS")
|
|
4268
|
+
if (!entry) {
|
|
4269
|
+
const withSpaces = field.trim().toUpperCase();
|
|
4270
|
+
entry = EXPLAIN_CATALOG.get(withSpaces);
|
|
4271
|
+
if (entry)
|
|
4272
|
+
matchedKey = withSpaces;
|
|
4273
|
+
}
|
|
4274
|
+
// Fuzzy: find catalog entries that contain the normalized term
|
|
4275
|
+
let suggestions = [];
|
|
4276
|
+
if (!entry) {
|
|
4277
|
+
for (const key of EXPLAIN_CATALOG.keys()) {
|
|
4278
|
+
if (key.includes(normalized) || normalized.includes(key)) {
|
|
4279
|
+
suggestions.push(key);
|
|
4280
|
+
}
|
|
4281
|
+
}
|
|
4282
|
+
// Cap suggestions
|
|
4283
|
+
suggestions = suggestions.slice(0, 10);
|
|
4284
|
+
}
|
|
4285
|
+
if (format === "json") {
|
|
4286
|
+
return jsonText({
|
|
4287
|
+
query: field,
|
|
4288
|
+
normalized,
|
|
4289
|
+
found: entry !== undefined,
|
|
4290
|
+
matched_key: entry ? matchedKey : null,
|
|
4291
|
+
entry: entry ?? null,
|
|
4292
|
+
suggestions: entry ? [] : suggestions,
|
|
4293
|
+
});
|
|
4294
|
+
}
|
|
4295
|
+
if (entry) {
|
|
4296
|
+
const lines = [
|
|
4297
|
+
`# ${matchedKey}`,
|
|
4298
|
+
"",
|
|
4299
|
+
`**Kategori**: ${entry.category}`,
|
|
4300
|
+
"",
|
|
4301
|
+
entry.description,
|
|
4302
|
+
];
|
|
4303
|
+
if (entry.examples?.length) {
|
|
4304
|
+
lines.push("", "**Eksempler**:");
|
|
4305
|
+
for (const ex of entry.examples)
|
|
4306
|
+
lines.push(`- ${ex}`);
|
|
4307
|
+
}
|
|
4308
|
+
if (entry.related?.length) {
|
|
4309
|
+
lines.push("", `**Relaterede termer**: ${entry.related.join(", ")}`);
|
|
4310
|
+
}
|
|
4311
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
4312
|
+
}
|
|
4313
|
+
const lines = [`# Ingen direkte match for '${field}'`, ""];
|
|
4314
|
+
if (suggestions.length) {
|
|
4315
|
+
lines.push("Måske mente du:");
|
|
4316
|
+
for (const s of suggestions)
|
|
4317
|
+
lines.push(`- \`${s}\``);
|
|
4318
|
+
lines.push("", "Kald firmaapi_explain_field igen med en af ovenstående.");
|
|
4319
|
+
}
|
|
4320
|
+
else {
|
|
4321
|
+
lines.push("Termen findes ikke i feltkataloget. Kataloget dækker selskabsformer,", "statusværdier, regnskabsklasser, ansatte-intervaller, FUNKTION-roller,", "hovedtyper, ERST-attributter og ejerregister-felter. Hvis termen er ny", "eller specifik for en bestemt branche, prøv at slå den op direkte i", "ERST/Erhvervsstyrelsen's dokumentation.");
|
|
4322
|
+
}
|
|
4323
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
4324
|
+
});
|
|
4325
|
+
return server;
|
|
4326
|
+
}
|
|
4327
|
+
//# sourceMappingURL=server.js.map
|