@talonic/mcp 0.1.88 → 0.1.90

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/dist/index.js CHANGED
@@ -3672,7 +3672,7 @@ var templateIdArg = z.string().uuid().describe("Template id (from talonic_doc_ge
3672
3672
  var productIdArg = z.string().uuid().describe("Data product id (from talonic_doc_gen_products).");
3673
3673
  var jobIdArg = z.string().uuid().describe("Batch id (from talonic_doc_gen_jobs or _generate).");
3674
3674
  var valuesArg = z.record(z.string(), z.string()).describe(
3675
- "Values by field key (or case key). A field whose source type is `case` (entered per document) takes the value as entered; a value for any other field is an edit over the fill, recorded in the document history."
3675
+ 'Values by field key (or case key). A field whose source type is `case` (entered per document) takes the value as entered; a passage decided per document (condition `ask`) takes "yes" or "no" (include or leave out; it stays missing until decided); a value for any other field is an edit over the fill, recorded in the document history.'
3676
3676
  );
3677
3677
  var ENTERED_RULE = "Fields whose source type is `case` are entered per document: the data does not hold them (e.g. the new owner), so pass them in `values` by field key (or case key). A value for any other field overrides the fill and is recorded as an edit in the document history.";
3678
3678
  function waitSeconds(requested, max) {
@@ -3747,10 +3747,11 @@ var UPDATE_TEMPLATE_DESCRIPTION = [
3747
3747
  "Change a template's metadata (name, group, kind, companion template, version) and its fields by key: a field's label, source, confirmed flag or reason. Fields not named stay as they are; an unknown key is refused. Run with dry_run first to see the sheet as it would be.",
3748
3748
  "USE WHEN: fixing a field the proposal got wrong (e.g. pointing it at another column or making it entered per document with source { type: 'case', caseKey }), or pairing a letter with its agreement.",
3749
3749
  "Setting `confirmed: true` is a person's decision: only do it when the user asked (see talonic_doc_gen_confirm_fields).",
3750
+ "Red passages (fields with `spot.original`, red text in the Word file): set a `variant` for grammar that depends on the party, a `condition` for text printed only sometimes, any value source, or `fixed` to keep the words (in black). `rescan: true` first adds the red passages of a template whose sheet predates them.",
3750
3751
  "NOT FOR: confirming many fields at once (talonic_doc_gen_confirm_fields).",
3751
3752
  "",
3752
- "ARGS: `template_id`; optional `name`, `group`, `kind` letter|agreement, `pair_template_id`, `version` (null clears group/kind/pair/version); `fields[] { key, label?, source?, confirmed?, reason? }`; `dry_run`.",
3753
- "RETURNS: { dry_run, template } with the field sheet."
3753
+ "ARGS: `template_id`; optional `name`, `group`, `kind` letter|agreement, `pair_template_id`, `version` (null clears group/kind/pair/version); `fields[] { key, label?, source?, confirmed?, reason? }`; `rescan` (add the fields the file has and the sheet lacks; alone or before the changes); `dry_run`.",
3754
+ "RETURNS: { dry_run, template } with the field sheet; with `rescan` alone { template, added[] } (keys added)."
3754
3755
  ].join("\n");
3755
3756
  var updateTemplateInputSchema = {
3756
3757
  template_id: templateIdArg,
@@ -3764,29 +3765,39 @@ var updateTemplateInputSchema = {
3764
3765
  key: z.string().min(1).max(200).describe("Field key from the field sheet."),
3765
3766
  label: z.string().max(120).optional(),
3766
3767
  source: z.record(z.string(), z.unknown()).optional().describe(
3767
- "Field source as the sheet stores it, e.g. { type: 'product', field }, { type: 'reference', column }, { type: 'case', caseKey }, { type: 'user', profile }, { type: 'rule', rule }, { type: 'today' }."
3768
+ "Field source as the sheet stores it, e.g. { type: 'product', field }, { type: 'reference', column }, { type: 'case', caseKey }, { type: 'user', profile }, { type: 'rule', rule }, { type: 'today' }, { type: 'party', role: addressee|owner_addressee|effective_partner|partner|manager|tenant|previous_owner|new_owner, attribute: name|salutation|greeting|street|postcode_town|address|address_block|email|kind|channel }, { type: 'variant', by: <party role>, map: { herr, frau, eheleute, person, company, association }, fallback } (grammar such as 'der/von'), { type: 'condition', when: { kind: 'party', role, present } | { kind: 'document', pattern, present } | { kind: 'field', field, present?, equals? } | { kind: 'ask' }, text? } (printed only when the condition holds; `ask`: the person generating decides per document, e.g. case variants), { type: 'fixed', text }."
3768
3769
  ),
3769
3770
  confirmed: z.boolean().optional().describe("Only when the user asked to confirm."),
3770
3771
  reason: z.string().max(400).nullable().optional()
3771
3772
  })
3772
3773
  ).max(500).optional().describe("Field changes by key."),
3774
+ rescan: z.boolean().optional().describe(
3775
+ "Read the Word file again and add the fields the sheet lacks (red passages); existing fields stay."
3776
+ ),
3773
3777
  dry_run: z.boolean().optional().describe("Return the sheet as it would be; nothing is saved.")
3774
3778
  };
3775
3779
  function handleUpdateTemplate(getToken, baseUrl, args) {
3776
- const { template_id, dry_run, ...changes } = args;
3780
+ const { template_id, dry_run, rescan, ...changes } = args;
3777
3781
  const body = Object.fromEntries(Object.entries(changes).filter(([, v]) => v !== void 0));
3778
- if (Object.keys(body).length === 0) {
3782
+ if (Object.keys(body).length === 0 && !rescan) {
3779
3783
  return Promise.resolve(
3780
3784
  validationError(
3781
- "name nothing to change: pass name, group, kind, pair_template_id, version or fields."
3785
+ "name nothing to change: pass name, group, kind, pair_template_id, version, fields or rescan."
3782
3786
  )
3783
3787
  );
3784
3788
  }
3785
- return runTool(
3786
- () => apiJson(getToken, baseUrl, "PATCH", `/v1/doc-gen/templates/${template_id}`, {
3789
+ if (rescan && dry_run) {
3790
+ return Promise.resolve(
3791
+ validationError("rescan saves the added fields; it cannot run as a dry run.")
3792
+ );
3793
+ }
3794
+ return runTool(async () => {
3795
+ const scanned = rescan ? await apiJson(getToken, baseUrl, "POST", `/v1/doc-gen/templates/${template_id}/rescan`) : null;
3796
+ if (Object.keys(body).length === 0) return scanned;
3797
+ return apiJson(getToken, baseUrl, "PATCH", `/v1/doc-gen/templates/${template_id}`, {
3787
3798
  body: { ...body, dry_run: dry_run ?? false }
3788
- })
3789
- );
3799
+ });
3800
+ });
3790
3801
  }
3791
3802
  var CONFIRM_DESCRIPTION = [
3792
3803
  "Confirm fields of a template's field sheet: the named keys, or every unconfirmed field (with include_entered false, leaving the fields entered per document unconfirmed). Confirming says a person checked the field's source; it is the user's decision, so only call this when the user asked to confirm. Run with dry_run first to list what would be confirmed.",
@@ -4336,6 +4347,961 @@ function registerDocGenTools(server, getToken, baseUrl, opts = {}) {
4336
4347
  );
4337
4348
  }
4338
4349
  }
4350
+ var readOnly4 = {
4351
+ readOnlyHint: true,
4352
+ destructiveHint: false,
4353
+ idempotentHint: true,
4354
+ openWorldHint: false
4355
+ };
4356
+ var write4 = (idempotent, destructive = false) => ({
4357
+ readOnlyHint: false,
4358
+ destructiveHint: destructive,
4359
+ idempotentHint: idempotent,
4360
+ openWorldHint: false
4361
+ });
4362
+ var PARTIES_POLL_INTERVAL_MS = 5e3;
4363
+ var READ_MAX_WAIT_S = 600;
4364
+ var ROLES2 = [
4365
+ "partner",
4366
+ "manager",
4367
+ "tenant",
4368
+ "previous_owner",
4369
+ "new_owner",
4370
+ "contact",
4371
+ "invoice_recipient"
4372
+ ];
4373
+ var KINDS = ["person", "company", "owners_association", "unknown"];
4374
+ var SALUTATIONS = ["herr", "frau", "eheleute", "firma", "weg"];
4375
+ var ROLE_STATES = ["suggested", "confirmed", "rejected"];
4376
+ var ISSUE_CODES = [
4377
+ "no_partner",
4378
+ "several_partners",
4379
+ "reference_disagrees",
4380
+ "kind_unknown",
4381
+ "address_missing",
4382
+ "manager_without_party",
4383
+ "tenant_without_period",
4384
+ "owner_change_open",
4385
+ "cost_unit_disagrees",
4386
+ "cost_unit_missing",
4387
+ "not_read",
4388
+ "read_failed",
4389
+ "possible_duplicate"
4390
+ ];
4391
+ var ROLES_EXPLAINED = "Roles: partner (the contract partner), manager (Verwalter: acts for a company or an owners' association and is written to on its behalf; represents_id names the role it acts for), tenant (with enters_contract: true the tenant is the temporary partner for the lease period valid_from..valid_to), previous_owner / new_owner (an owner change: the new owner holds from the transfer date valid_from), contact, invoice_recipient.";
4392
+ var COMPUTED_RULE = "The effective partner (the tenant entering the contract during its lease, else the partner) and the addressee (the effective partner's Verwalter when it has one, else the effective partner) are computed by the platform from the roles in force on the day; never set them yourself, fix the roles.";
4393
+ var DECISION_RULE = "A read only makes suggestions and never overwrites a person's decision (a confirmed role stays, a rejected one never comes back). Confirming, rejecting and merging are a person's decisions: only do them when the user asked.";
4394
+ var dateArg = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "a date YYYY-MM-DD").describe("ISO date YYYY-MM-DD.");
4395
+ var contractIdArg2 = z.string().uuid().describe("Contract id (from talonic_parties_contracts or talonic_parties_issues).");
4396
+ var partyIdArg = z.string().uuid().describe("Party id (from talonic_parties_search, _contract or _issues).");
4397
+ function waitSeconds2(requested, max) {
4398
+ const n = Number.isFinite(requested) ? requested : 0;
4399
+ return Math.max(0, Math.min(max, Math.floor(n)));
4400
+ }
4401
+ function defined(obj) {
4402
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
4403
+ }
4404
+ var STATUS_DESCRIPTION3 = [
4405
+ "Contract Party Management at a glance: how many contracts, how many have confirmed parties, only suggestions, or no partner; active parties; open suggestions; and the parties-read queue.",
4406
+ "USE WHEN: starting any parties work, or to report where things stand. The loop: talonic_parties_status \u2192 talonic_parties_read (dry_run first, then with wait_seconds) \u2192 talonic_parties_issues \u2192 talonic_parties_contract per flagged contract \u2192 talonic_parties_set_role / talonic_parties_confirm \u2192 talonic_parties_merge duplicates \u2192 talonic_parties_issues again.",
4407
+ "NOT FOR: what to fix (talonic_parties_issues); one contract (talonic_parties_contract).",
4408
+ "",
4409
+ "ARGS: none.",
4410
+ "RETURNS: { contracts, contracts_confirmed, contracts_suggested, contracts_without_partner, parties, suggestions, reads { counts { pending, running, done, failed }, unread, failed } }."
4411
+ ].join("\n");
4412
+ function handleStatus2(getToken, baseUrl) {
4413
+ return runTool(() => apiJson(getToken, baseUrl, "GET", "/v1/parties/status"));
4414
+ }
4415
+ var ISSUES_DESCRIPTION4 = [
4416
+ "The parties worklist: per contract what looks wrong today (no partner, several partners, the reference table names another partner, person-or-company unknown, no postal address, a Verwalter for a party no longer on the contract, a tenant entering the contract without a lease period, an owner change without a transfer date, cost unit disagreeing or missing, not read, read failed), plus parties that look like duplicates (same name, and postcode when both have one).",
4417
+ "USE WHEN: after talonic_parties_read, deciding what to fix; open each flagged contract with talonic_parties_contract. Duplicates are merge candidates: never merged on their own (talonic_parties_merge, only when the user asked).",
4418
+ "NOT FOR: the headline counts (talonic_parties_status); all contracts (talonic_parties_contracts).",
4419
+ "",
4420
+ `ARGS: \`code\` (only this issue; one of ${ISSUE_CODES.join(", ")}).`,
4421
+ "RETURNS: { contracts[] { contract_id, contract_key, title, issues[] { code, detail, role_ids[], party_ids[] } }, duplicates[] { name_key, party_ids[], names[] } }."
4422
+ ].join("\n");
4423
+ var issuesInputSchema2 = {
4424
+ code: z.enum(ISSUE_CODES).optional().describe("Only this issue code.")
4425
+ };
4426
+ function handleIssues4(getToken, baseUrl, args) {
4427
+ return runTool(
4428
+ () => apiJson(getToken, baseUrl, "GET", "/v1/parties/issues", { params: { code: args.code } })
4429
+ );
4430
+ }
4431
+ var CONTRACTS_DESCRIPTION = [
4432
+ "List the workspace's contracts with their parties today: effective partner, addressee and Verwalter by name, the parties' state (confirmed: every role counted is confirmed; suggested: any is a suggestion; none: no partner), open suggestions and the read state.",
4433
+ "USE WHEN: getting an overview, finding a contract by key, title or party name, or listing contracts still on suggestions (state: suggested) or without a partner (state: none).",
4434
+ "NOT FOR: one contract's roles and evidence (talonic_parties_contract); what needs fixing (talonic_parties_issues).",
4435
+ "",
4436
+ "ARGS: `query` (contract key, title, counterparty, partner or Verwalter contains), `state` confirmed|suggested|none, `limit` (1-5000, default 500).",
4437
+ "RETURNS: { total, data[] { id, contract_key, title, counterparty, status, partner, addressee, manager, state, suggestions, read } }."
4438
+ ].join("\n");
4439
+ var contractsInputSchema = {
4440
+ query: z.string().optional().describe("Key, title, counterparty, partner or Verwalter contains."),
4441
+ state: z.enum(["confirmed", "suggested", "none"]).optional().describe("Only contracts whose parties are in this state."),
4442
+ limit: z.number().int().min(1).max(5e3).optional().describe("At most this many (default 500).")
4443
+ };
4444
+ function handleContracts(getToken, baseUrl, args) {
4445
+ return runTool(
4446
+ () => apiJson(getToken, baseUrl, "GET", "/v1/parties/contracts", {
4447
+ params: { q: args.query, state: args.state, limit: args.limit }
4448
+ })
4449
+ );
4450
+ }
4451
+ var CONTRACT_DESCRIPTION2 = [
4452
+ "One contract's parties on a day: the computed view (partner, manager, tenant, previous and new owner, effective partner, addressee with its postal address lines, contacts, state), every role row with its party, state (suggested|confirmed|rejected), confidence and evidence (document quotes, reference table rows, a person's word), the issues, the cost unit (documents vs. contract register) and the read state.",
4453
+ "USE WHEN: checking or fixing a flagged contract; you need role ids (roles[].id) for talonic_parties_set_role, or to answer who the partner is and where a letter goes.",
4454
+ ROLES_EXPLAINED,
4455
+ COMPUTED_RULE,
4456
+ "NOT FOR: the list of contracts (talonic_parties_contracts); one party across contracts (talonic_parties_party).",
4457
+ "",
4458
+ "ARGS: `contract_id`, `on` (YYYY-MM-DD; default today: the roles in force on that day).",
4459
+ "RETURNS: { contract { id, contract_key, title, counterparty, status }, on, view { partner, manager, tenant, previous_owner, new_owner, effective_partner, addressee { ...party, role_id, role, state, valid_from, valid_to, address_lines[] }, contacts[], state }, roles[] { id, party_id, role, represents_id, valid_from, valid_to, enters_contract, state, confidence, evidence[], origin, decided_by, decided_at, note, party }, issues[], cost_unit { documents, quote, register[] }, reference_names[], read { status, read_at, error, notes, read_with } | null }."
4460
+ ].join("\n");
4461
+ var contractInputSchema2 = {
4462
+ contract_id: contractIdArg2,
4463
+ on: dateArg.optional().describe("The day to read the parties for (YYYY-MM-DD; default today).")
4464
+ };
4465
+ function handleContract2(getToken, baseUrl, args) {
4466
+ return runTool(
4467
+ () => apiJson(getToken, baseUrl, "GET", `/v1/parties/contracts/${args.contract_id}`, {
4468
+ params: { on: args.on }
4469
+ })
4470
+ );
4471
+ }
4472
+ var SEARCH_DESCRIPTION = [
4473
+ "Search the party register (people, companies, owners' associations): name, street, postcode, town, email or an external reference contains the query; each with how many contracts it holds a role on.",
4474
+ "USE WHEN: finding a party to add to a contract (its id for talonic_parties_set_role), checking whether a party already exists before creating one, or finding duplicates by name.",
4475
+ "NOT FOR: one party with its roles (talonic_parties_party); a contract's parties (talonic_parties_contract).",
4476
+ "",
4477
+ "ARGS: `query`, `kind` person|company|owners_association|unknown, `limit` (1-1000, default 200).",
4478
+ "RETURNS: { total, data[] { id, kind, display_name, salutation, title, first_name, last_name, company_name, legal_form, street, postcode, town, country, email, phone, preferred_channel, external_refs, status, contracts } }."
4479
+ ].join("\n");
4480
+ var searchInputSchema = {
4481
+ query: z.string().optional().describe("Name, address, email or external reference contains."),
4482
+ kind: z.enum(KINDS).optional().describe("Only parties of this kind."),
4483
+ limit: z.number().int().min(1).max(1e3).optional().describe("At most this many (default 200).")
4484
+ };
4485
+ function handleSearch2(getToken, baseUrl, args) {
4486
+ return runTool(
4487
+ () => apiJson(getToken, baseUrl, "GET", "/v1/parties", {
4488
+ params: { q: args.query, kind: args.kind, limit: args.limit }
4489
+ })
4490
+ );
4491
+ }
4492
+ var PARTY_FIELD_KEYS = [
4493
+ "kind",
4494
+ "display_name",
4495
+ "salutation",
4496
+ "title",
4497
+ "first_name",
4498
+ "last_name",
4499
+ "company_name",
4500
+ "legal_form",
4501
+ "street",
4502
+ "postcode",
4503
+ "town",
4504
+ "country",
4505
+ "email",
4506
+ "phone",
4507
+ "preferred_channel",
4508
+ "external_refs"
4509
+ ];
4510
+ var PARTY_DESCRIPTION = [
4511
+ "Read, change or create one party. With `party_id` alone: the party with its roles on every contract, its contacts (members), the companies it is a contact of and the documents it appears in (with quotes). With `party_id` and fields: changes those fields (the rest stay). Without `party_id`: creates a party; `display_name` is required (kind and salutation are inferred from it when not given).",
4512
+ "USE WHEN: checking a party; fixing its name, kind (person or company decides a letter's wording), salutation or postal address (issues kind_unknown, address_missing); creating a party the documents miss before adding it to a contract with talonic_parties_set_role. Search first (talonic_parties_search) so you do not create a duplicate.",
4513
+ "NOT FOR: its role on a contract (talonic_parties_set_role); combining duplicates (talonic_parties_merge).",
4514
+ "",
4515
+ "ARGS: `party_id` (omit to create); fields `kind` person|company|owners_association|unknown, `display_name`, `salutation` herr|frau|eheleute|firma|weg, `title`, `first_name`, `last_name`, `company_name`, `legal_form`, `street`, `postcode`, `town`, `country`, `email`, `phone`, `preferred_channel` post|email, `external_refs` { name: value } (null clears a text field).",
4516
+ "RETURNS: read { party, merged_into, roles[] { ...role, contract }, members[] { id, function, party }, member_of[], documents[] { document_id, filename, quotes[] } }; change or create: the party."
4517
+ ].join("\n");
4518
+ var nullableText = (max) => z.string().max(max).nullable().optional();
4519
+ var partyInputSchema = {
4520
+ party_id: partyIdArg.optional().describe("The party to read or change; omit to create one."),
4521
+ kind: z.enum(KINDS).optional().describe("Person, company, owners' association or unknown."),
4522
+ display_name: z.string().min(1).max(300).optional().describe("Name as printed; required to create."),
4523
+ salutation: z.enum(SALUTATIONS).nullable().optional().describe("Salutation; null clears it."),
4524
+ title: nullableText(60).describe("Academic title, e.g. 'Dr.'."),
4525
+ first_name: nullableText(120),
4526
+ last_name: nullableText(120),
4527
+ company_name: nullableText(300),
4528
+ legal_form: nullableText(60).describe("e.g. GmbH, AG, KG."),
4529
+ street: nullableText(200).describe("Street and house number."),
4530
+ postcode: nullableText(12),
4531
+ town: nullableText(120),
4532
+ country: nullableText(60),
4533
+ email: z.string().email().nullable().optional(),
4534
+ phone: nullableText(60),
4535
+ preferred_channel: z.enum(["post", "email"]).nullable().optional(),
4536
+ external_refs: z.record(z.string(), z.string()).optional().describe("References in other systems by name, e.g. { debitor: '10042' }.")
4537
+ };
4538
+ function handleParty(getToken, baseUrl, args) {
4539
+ const fields = defined(Object.fromEntries(PARTY_FIELD_KEYS.map((k) => [k, args[k]])));
4540
+ const changing = Object.keys(fields).length > 0;
4541
+ if (args.party_id) {
4542
+ const path = `/v1/parties/${args.party_id}`;
4543
+ return runTool(
4544
+ () => changing ? apiJson(getToken, baseUrl, "PATCH", path, { body: fields }) : apiJson(getToken, baseUrl, "GET", path)
4545
+ );
4546
+ }
4547
+ if (typeof args.display_name !== "string" || !args.display_name.trim()) {
4548
+ return Promise.resolve(
4549
+ validationError("pass party_id to read or change a party, or display_name to create one.")
4550
+ );
4551
+ }
4552
+ return runTool(() => apiJson(getToken, baseUrl, "POST", "/v1/parties", { body: fields }));
4553
+ }
4554
+ var SET_ROLE_DESCRIPTION = [
4555
+ "Add a role to a contract, or change one role row. With `contract_id`, `party_id` and `role`: adds the party in that role (confirmed unless `state` says suggested; a party already holding that role on the contract has that row updated). With `role_id`: changes that row: confirm or reject it (`state`), move it to another role or party, set the period, the Verwalter link or enters_contract. Any change by a person is a decision: an edited suggestion becomes confirmed unless `state` says otherwise.",
4556
+ "USE WHEN: fixing a contract's parties after reading talonic_parties_contract: a partner missing (no_partner), two partners at once (reject the wrong one, or give the old one valid_to), a Verwalter for the right party (represents_id), a tenant entering the contract (enters_contract with valid_from / valid_to), an owner change (previous_owner, new_owner with valid_from = transfer date).",
4557
+ ROLES_EXPLAINED,
4558
+ COMPUTED_RULE,
4559
+ DECISION_RULE,
4560
+ "NOT FOR: confirming many suggestions at once (talonic_parties_confirm); the party's own details (talonic_parties_party).",
4561
+ "",
4562
+ "ARGS: add: `contract_id`, `party_id`, `role`; change: `role_id` (roles[].id from talonic_parties_contract) and optional `party_id`, `role`. Both: `state` suggested|confirmed|rejected, `represents_id` (another role id on the same contract; null clears), `valid_from`, `valid_to` (YYYY-MM-DD; null clears), `enters_contract` (tenant only), `note` (say where the decision comes from).",
4563
+ "RETURNS: the role row { id, contract_id, party_id, role, represents_id, valid_from, valid_to, enters_contract, state, confidence, evidence[], origin, decided_by, decided_at, note }."
4564
+ ].join("\n");
4565
+ var setRoleInputSchema = {
4566
+ contract_id: contractIdArg2.optional().describe("Add: the contract to add the role to."),
4567
+ role_id: z.string().uuid().optional().describe("Change: the role row (roles[].id from talonic_parties_contract)."),
4568
+ party_id: partyIdArg.optional().describe("Add: the party; change: move the row to this party."),
4569
+ role: z.enum(ROLES2).optional().describe("The role."),
4570
+ state: z.enum(ROLE_STATES).optional().describe("confirmed or rejected (a person's decision); suggested keeps it open."),
4571
+ represents_id: z.string().uuid().nullable().optional().describe("Manager / contact: the role id it acts for on the same contract; null clears."),
4572
+ valid_from: dateArg.nullable().optional().describe("From this day (YYYY-MM-DD); null clears."),
4573
+ valid_to: dateArg.nullable().optional().describe("Until this day (YYYY-MM-DD); null clears."),
4574
+ enters_contract: z.boolean().optional().describe("Tenant: enters the contract (temporary partner for the lease period)."),
4575
+ note: z.string().max(1e3).nullable().optional().describe("Why; where the decision comes from.")
4576
+ };
4577
+ function handleSetRole(getToken, baseUrl, args) {
4578
+ const { contract_id, role_id, ...rest } = args;
4579
+ const body = defined(rest);
4580
+ if (!!contract_id === !!role_id) {
4581
+ return Promise.resolve(
4582
+ validationError("pass contract_id (with party_id and role) to add, or role_id to change.")
4583
+ );
4584
+ }
4585
+ if (contract_id) {
4586
+ if (!args.party_id || !args.role) {
4587
+ return Promise.resolve(validationError("adding a role needs party_id and role."));
4588
+ }
4589
+ return runTool(
4590
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/contracts/${contract_id}/roles`, { body })
4591
+ );
4592
+ }
4593
+ if (Object.keys(body).length === 0) {
4594
+ return Promise.resolve(
4595
+ validationError(
4596
+ "name something to change: state, role, party_id, represents_id, valid_from, valid_to, enters_contract or note."
4597
+ )
4598
+ );
4599
+ }
4600
+ return runTool(
4601
+ () => apiJson(getToken, baseUrl, "PATCH", `/v1/parties/roles/${role_id}`, { body })
4602
+ );
4603
+ }
4604
+ var CONFIRM_DESCRIPTION2 = [
4605
+ "Confirm suggested roles in bulk: by default only high-confidence suggestions (a verified quote the contract register agrees with), optionally only of named contracts or roles. Confirming says a person checked them; it is the user's decision, so only call this when the user asked. Run with dry_run first and say how many it would confirm.",
4606
+ "USE WHEN: the user asks to accept the suggestions (all, or of some contracts / roles).",
4607
+ DECISION_RULE,
4608
+ "NOT FOR: rejecting or fixing one role (talonic_parties_set_role).",
4609
+ "",
4610
+ "ARGS: `contract_ids[]` (omit for all), `roles[]` (e.g. ['partner']), `min_confidence` high|medium|low (default high), `limit` (1-5000, default 500), `dry_run`.",
4611
+ "RETURNS: { dry_run, confirmed, rows[] { id, contract_id, party_id, role, confidence } } (rows: the first 100)."
4612
+ ].join("\n");
4613
+ var confirmInputSchema2 = {
4614
+ contract_ids: z.array(z.string().uuid()).max(1e3).optional().describe("Only these contracts."),
4615
+ roles: z.array(z.enum(ROLES2)).max(ROLES2.length).optional().describe("Only these roles."),
4616
+ min_confidence: z.enum(["high", "medium", "low"]).optional().describe("Lowest confidence confirmed (default high)."),
4617
+ limit: z.number().int().min(1).max(5e3).optional().describe("At most this many (default 500)."),
4618
+ dry_run: z.boolean().optional().describe("Count only; nothing is confirmed.")
4619
+ };
4620
+ function handleConfirm2(getToken, baseUrl, args) {
4621
+ return runTool(
4622
+ () => apiJson(getToken, baseUrl, "POST", "/v1/parties/roles/confirm", {
4623
+ body: {
4624
+ ...args.contract_ids ? { contract_ids: args.contract_ids } : {},
4625
+ ...args.roles ? { roles: args.roles } : {},
4626
+ min_confidence: args.min_confidence ?? "high",
4627
+ ...args.limit ? { limit: args.limit } : {},
4628
+ dry_run: args.dry_run ?? false
4629
+ }
4630
+ })
4631
+ );
4632
+ }
4633
+ var MERGE_DESCRIPTION2 = [
4634
+ "Merge one party into another: every role and contact link moves to the survivor (`into`); a role the survivor already holds on the same contract keeps the survivor's row and takes the merged one's evidence. The merged party stays only as a pointer to the survivor. Cannot be undone; a person's decision, so only when the user asked. Run with dry_run first.",
4635
+ "USE WHEN: talonic_parties_issues lists duplicates (same name and postcode) and the user confirms they are the same party.",
4636
+ "NOT FOR: two different parties with similar names; moving one role to another party (talonic_parties_set_role with role_id and party_id).",
4637
+ "",
4638
+ "ARGS: `party_id` (the one that goes), `into` (the survivor), `dry_run`.",
4639
+ "RETURNS: { dry_run, moves, combined, party } (party: the survivor, after a real merge)."
4640
+ ].join("\n");
4641
+ var mergeInputSchema2 = {
4642
+ party_id: partyIdArg.describe("The party merged away."),
4643
+ into: z.string().uuid().describe("The party that survives."),
4644
+ dry_run: z.boolean().optional().describe("Count the moves; nothing changes.")
4645
+ };
4646
+ function handleMerge2(getToken, baseUrl, args) {
4647
+ if (args.party_id === args.into) {
4648
+ return Promise.resolve(validationError("a party cannot be merged into itself."));
4649
+ }
4650
+ return runTool(
4651
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/merge`, {
4652
+ body: { into: args.into, dry_run: args.dry_run ?? false }
4653
+ })
4654
+ );
4655
+ }
4656
+ var READ_DESCRIPTION = [
4657
+ "Read the parties from contract documents: queues contracts for the platform to read in the background (one model call per contract) and store every party and role it finds as a suggestion, with quotes. By default every contract not read yet (only_unread); `contract_ids` reads exactly those again. With `status: true` only reports the queue. Pass `wait_seconds` to wait until the queue is empty (polls the queue every 5 s).",
4658
+ "USE WHEN: filling the app or after new contract documents arrived: run with dry_run first and say how many contracts it will read, then without dry_run and with wait_seconds; then talonic_parties_issues.",
4659
+ DECISION_RULE,
4660
+ "NOT FOR: one contract's parties (talonic_parties_contract).",
4661
+ "",
4662
+ "ARGS: `status` (only the queue); or `contract_ids[]` (omit for all), `only_unread` (default true), `force` (read again although read), `limit` (1-5000, default 500), `dry_run`; `wait_seconds` (0-600, default 0; not with dry_run).",
4663
+ "RETURNS: dry_run { dry_run, would_queue, skipped, contracts[] (first 50) }; queued { dry_run, queued, skipped }; status { contracts, counts { pending, running, done, failed }, unread, failed[] { contract_id, contract_key, error, attempts } }. After a wait also { status, waited_ms, still_running }."
4664
+ ].join("\n");
4665
+ var readInputSchema = {
4666
+ status: z.boolean().optional().describe("Only report the read queue; nothing is queued."),
4667
+ contract_ids: z.array(z.string().uuid()).max(5e3).optional().describe("Only these contracts (read again when already read)."),
4668
+ only_unread: z.boolean().optional().describe("All contracts: only those not read yet (default true)."),
4669
+ force: z.boolean().optional().describe("Read again although already read."),
4670
+ limit: z.number().int().min(1).max(5e3).optional().describe("Queue at most this many."),
4671
+ dry_run: z.boolean().optional().describe("Count and list what would be read; nothing is queued."),
4672
+ wait_seconds: z.number().min(0).max(READ_MAX_WAIT_S).optional().describe(`Seconds to wait for the queue to empty (0-${READ_MAX_WAIT_S}).`)
4673
+ };
4674
+ var busy = (s) => (s.counts?.["pending"] ?? 0) + (s.counts?.["running"] ?? 0) > 0;
4675
+ function handleRead(getToken, baseUrl, args, deps = {}) {
4676
+ const waitS = waitSeconds2(args.wait_seconds, READ_MAX_WAIT_S);
4677
+ const readStatus = () => apiJson(getToken, baseUrl, "GET", "/v1/parties/read/status");
4678
+ return runTool(async () => {
4679
+ let started = null;
4680
+ if (!args.status) {
4681
+ started = await apiJson(
4682
+ getToken,
4683
+ baseUrl,
4684
+ "POST",
4685
+ "/v1/parties/read",
4686
+ {
4687
+ body: {
4688
+ ...args.contract_ids ? { contract_ids: args.contract_ids } : {},
4689
+ ...args.only_unread !== void 0 ? { only_unread: args.only_unread } : {},
4690
+ ...args.force !== void 0 ? { force: args.force } : {},
4691
+ ...args.limit ? { limit: args.limit } : {},
4692
+ dry_run: args.dry_run ?? false
4693
+ }
4694
+ }
4695
+ );
4696
+ if (waitS === 0 || args.dry_run) return started;
4697
+ }
4698
+ const first = await readStatus();
4699
+ if (waitS === 0) return first;
4700
+ const sleep2 = deps.sleep ?? sleep;
4701
+ const now = deps.now ?? Date.now;
4702
+ const start = now();
4703
+ const deadline = start + waitS * 1e3;
4704
+ let status3 = first;
4705
+ let pollError;
4706
+ while (busy(status3) && now() < deadline) {
4707
+ await sleep2(Math.min(PARTIES_POLL_INTERVAL_MS, deadline - now()));
4708
+ try {
4709
+ status3 = await readStatus();
4710
+ } catch (err) {
4711
+ pollError = err instanceof Error ? err.message : String(err);
4712
+ break;
4713
+ }
4714
+ }
4715
+ const stillRunning = pollError !== void 0 || busy(status3);
4716
+ return {
4717
+ ...started ?? {},
4718
+ status: status3,
4719
+ waited_ms: now() - start,
4720
+ still_running: stillRunning,
4721
+ ...pollError ? { poll_error: pollError } : {},
4722
+ next: stillRunning ? "Still reading: call talonic_parties_read with status: true (and wait_seconds) later." : "Read done: open the worklist with talonic_parties_issues."
4723
+ };
4724
+ });
4725
+ }
4726
+ var MEMBERS_DESCRIPTION = [
4727
+ "Add a contact person to a company or an owners' association (with their function), or remove a contact link. A contact is always a person; the company is a company or an owners' association. Adding the same person again updates the function.",
4728
+ "USE WHEN: the user names the person to write to at a company (e.g. the WEG's Verwalter contact), or a contact left.",
4729
+ "NOT FOR: a contact role on one contract (talonic_parties_set_role with role contact).",
4730
+ "",
4731
+ "ARGS: add: `party_id` (the company), `person_id`, `function` (e.g. 'Gesch\xE4ftsf\xFChrer'); remove: `member_id` (members[].id from talonic_parties_party) alone.",
4732
+ "RETURNS: add: the link { id, company_party_id, person_party_id, function }; remove: { ok: true }."
4733
+ ].join("\n");
4734
+ var membersInputSchema = {
4735
+ party_id: partyIdArg.optional().describe("Add: the company or owners' association."),
4736
+ person_id: z.string().uuid().optional().describe("Add: the person (a party of kind person)."),
4737
+ function: z.string().max(200).nullable().optional().describe("Add: their function."),
4738
+ member_id: z.string().uuid().optional().describe("Remove: the link (members[].id from talonic_parties_party).")
4739
+ };
4740
+ function handleMembers(getToken, baseUrl, args) {
4741
+ if (args.member_id) {
4742
+ if (args.party_id || args.person_id || args.function !== void 0) {
4743
+ return Promise.resolve(validationError("member_id (remove) goes alone."));
4744
+ }
4745
+ return runTool(
4746
+ () => apiJson(getToken, baseUrl, "DELETE", `/v1/parties/members/${args.member_id}`)
4747
+ );
4748
+ }
4749
+ if (!args.party_id || !args.person_id) {
4750
+ return Promise.resolve(
4751
+ validationError("pass party_id and person_id to add a contact, or member_id to remove one.")
4752
+ );
4753
+ }
4754
+ return runTool(
4755
+ () => apiJson(getToken, baseUrl, "POST", `/v1/parties/${args.party_id}/members`, {
4756
+ body: {
4757
+ person_id: args.person_id,
4758
+ ...args.function !== void 0 ? { function: args.function } : {}
4759
+ }
4760
+ })
4761
+ );
4762
+ }
4763
+ var GROUP_COMPANIES_DESCRIPTION = [
4764
+ "Read the workspace's own companies (the group: lead company, subsidiaries, sisters), or replace them all with `companies`. The read uses them to tell our side from the contract partner. Replacing deletes every company not in the new list: read first, change, send the whole list, and only when the user asked.",
4765
+ "USE WHEN: a read takes one of our own companies for the partner, or setting up the workspace.",
4766
+ "NOT FOR: contract partners (talonic_parties_party).",
4767
+ "",
4768
+ "ARGS: none to read; `companies[] { name, parent? (another name in the list), relation? subsidiary|sister|parent }` to replace.",
4769
+ "RETURNS: { data[] { id, name, parent_id, relation } } (after a replace: the stored list)."
4770
+ ].join("\n");
4771
+ var groupCompaniesInputSchema = {
4772
+ companies: z.array(
4773
+ z.object({
4774
+ name: z.string().min(1).max(300),
4775
+ parent: z.string().max(300).nullable().optional().describe("Another name in the list."),
4776
+ relation: z.enum(["subsidiary", "sister", "parent"]).nullable().optional()
4777
+ })
4778
+ ).max(1e3).optional().describe("The complete new list; omit to read.")
4779
+ };
4780
+ function handleGroupCompanies(getToken, baseUrl, args) {
4781
+ return runTool(
4782
+ () => args.companies ? apiJson(getToken, baseUrl, "PUT", "/v1/parties/group-companies", {
4783
+ body: { companies: args.companies }
4784
+ }) : apiJson(getToken, baseUrl, "GET", "/v1/parties/group-companies")
4785
+ );
4786
+ }
4787
+ function registerPartiesTools(server, getToken, baseUrl) {
4788
+ const tools = [
4789
+ [
4790
+ "talonic_parties_status",
4791
+ "Contract parties status",
4792
+ STATUS_DESCRIPTION3,
4793
+ {},
4794
+ readOnly4,
4795
+ () => handleStatus2(getToken, baseUrl)
4796
+ ],
4797
+ [
4798
+ "talonic_parties_issues",
4799
+ "Contract parties worklist",
4800
+ ISSUES_DESCRIPTION4,
4801
+ issuesInputSchema2,
4802
+ readOnly4,
4803
+ (a) => handleIssues4(getToken, baseUrl, a)
4804
+ ],
4805
+ [
4806
+ "talonic_parties_contracts",
4807
+ "Contracts with their parties",
4808
+ CONTRACTS_DESCRIPTION,
4809
+ contractsInputSchema,
4810
+ readOnly4,
4811
+ (a) => handleContracts(getToken, baseUrl, a)
4812
+ ],
4813
+ [
4814
+ "talonic_parties_contract",
4815
+ "One contract's parties",
4816
+ CONTRACT_DESCRIPTION2,
4817
+ contractInputSchema2,
4818
+ readOnly4,
4819
+ (a) => handleContract2(getToken, baseUrl, a)
4820
+ ],
4821
+ [
4822
+ "talonic_parties_search",
4823
+ "Search parties",
4824
+ SEARCH_DESCRIPTION,
4825
+ searchInputSchema,
4826
+ readOnly4,
4827
+ (a) => handleSearch2(getToken, baseUrl, a)
4828
+ ],
4829
+ [
4830
+ "talonic_parties_party",
4831
+ "Read, change or create a party",
4832
+ PARTY_DESCRIPTION,
4833
+ partyInputSchema,
4834
+ // With fields it overwrites the party's details: destructive per OpenAI's annotation rules.
4835
+ write4(false, true),
4836
+ (a) => handleParty(getToken, baseUrl, a)
4837
+ ],
4838
+ [
4839
+ "talonic_parties_set_role",
4840
+ "Add or change a contract role",
4841
+ SET_ROLE_DESCRIPTION,
4842
+ setRoleInputSchema,
4843
+ // Overwrites or rejects a role row: destructive.
4844
+ write4(true, true),
4845
+ (a) => handleSetRole(getToken, baseUrl, a)
4846
+ ],
4847
+ [
4848
+ "talonic_parties_confirm",
4849
+ "Confirm suggested roles",
4850
+ CONFIRM_DESCRIPTION2,
4851
+ confirmInputSchema2,
4852
+ write4(true),
4853
+ (a) => handleConfirm2(getToken, baseUrl, a)
4854
+ ],
4855
+ [
4856
+ "talonic_parties_merge",
4857
+ "Merge duplicate parties",
4858
+ MERGE_DESCRIPTION2,
4859
+ mergeInputSchema2,
4860
+ write4(true, true),
4861
+ (a) => handleMerge2(getToken, baseUrl, a)
4862
+ ],
4863
+ [
4864
+ "talonic_parties_read",
4865
+ "Read parties from contracts",
4866
+ READ_DESCRIPTION,
4867
+ readInputSchema,
4868
+ write4(true),
4869
+ (a) => handleRead(getToken, baseUrl, a)
4870
+ ],
4871
+ [
4872
+ "talonic_parties_members",
4873
+ "Company contacts",
4874
+ MEMBERS_DESCRIPTION,
4875
+ membersInputSchema,
4876
+ // Removing a contact link deletes it: destructive.
4877
+ write4(true, true),
4878
+ (a) => handleMembers(getToken, baseUrl, a)
4879
+ ],
4880
+ [
4881
+ "talonic_parties_group_companies",
4882
+ "Our group companies",
4883
+ GROUP_COMPANIES_DESCRIPTION,
4884
+ groupCompaniesInputSchema,
4885
+ // With `companies` it replaces the whole list: destructive.
4886
+ write4(true, true),
4887
+ (a) => handleGroupCompanies(getToken, baseUrl, a)
4888
+ ]
4889
+ ];
4890
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
4891
+ server.registerTool(
4892
+ name,
4893
+ { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
4894
+ async (args) => handler(args)
4895
+ );
4896
+ }
4897
+ }
4898
+ var readOnly5 = {
4899
+ readOnlyHint: true,
4900
+ destructiveHint: false,
4901
+ idempotentHint: true,
4902
+ openWorldHint: false
4903
+ };
4904
+ var write5 = (idempotent, destructive = false) => ({
4905
+ readOnlyHint: false,
4906
+ destructiveHint: destructive,
4907
+ idempotentHint: idempotent,
4908
+ openWorldHint: false
4909
+ });
4910
+ var domainSchema = z.enum(["vendors", "customers", "materials"]).describe("Master data domain: vendors, customers or materials.");
4911
+ var domainPath = (domain, rest = "") => `/v1/master-records/${encodeURIComponent(domain)}${rest}`;
4912
+ var CONFIG_DESCRIPTION2 = [
4913
+ "Read the Master Records configuration: per domain (vendors, customers, materials) the source systems (label, SQL connection, the read-only SELECT aliasing columns to the canonical fields; order is survivorship priority), the match thresholds, and the optional change logs, open items and evidence Spec.",
4914
+ "USE WHEN: before changing the configuration, or to explain which systems feed a domain.",
4915
+ "NOT FOR: the golden records (talonic_master_records_overview).",
4916
+ "",
4917
+ "ARGS: none.",
4918
+ "RETURNS: { domains { vendors|customers|materials { sources[], auto_threshold?, review_threshold?, changes[]?, open_items[]?, evidence? } } }."
4919
+ ].join("\n");
4920
+ function handleConfig2(getToken, baseUrl) {
4921
+ return runTool(() => apiJson(getToken, baseUrl, "GET", "/v1/master-records/config"));
4922
+ }
4923
+ var SAVE_CONFIG_DESCRIPTION2 = [
4924
+ "Replace the Master Records configuration with a complete new one (validated by the platform: every SQL is checked read-only against its connection). Run with dry_run first. Saving needs an owner.",
4925
+ "USE WHEN: setting up Master Records for a workspace, or adding a source system or change log.",
4926
+ "NOT FOR: partial edits; read talonic_master_records_config, change it, and send the whole object.",
4927
+ "",
4928
+ "ARGS: `config` (the whole configuration object), `dry_run` (validate only).",
4929
+ "RETURNS: { config, saved }. A broken config returns the list of problems."
4930
+ ].join("\n");
4931
+ var saveConfigInputSchema2 = {
4932
+ config: z.record(z.string(), z.unknown()).describe("The whole Master Records configuration object (see talonic_master_records_config)."),
4933
+ dry_run: z.boolean().optional().describe("Validate only; nothing is saved.")
4934
+ };
4935
+ function handleSaveConfig2(getToken, baseUrl, args) {
4936
+ return runTool(
4937
+ () => apiJson(getToken, baseUrl, "PUT", "/v1/master-records/config", {
4938
+ body: { config: args.config, dry_run: args.dry_run ?? false }
4939
+ })
4940
+ );
4941
+ }
4942
+ var RUN_DESCRIPTION = [
4943
+ "Resolve a domain now: read every configured source, match rows across systems, and replace the domain's golden records. Earlier accept / split decisions are kept. Deterministic; running it again on the same data gives the same records.",
4944
+ "USE WHEN: the sources changed, or the domain has never been resolved.",
4945
+ "NOT FOR: reading the result (talonic_master_records_overview).",
4946
+ "",
4947
+ "ARGS: `domain` vendors|customers|materials.",
4948
+ "RETURNS: { run_id, stats { source_rows, records, multi_source, auto_merged, to_review, conflicts, bad_conflicts, per_source, pairs_compared, resolve_ms } }."
4949
+ ].join("\n");
4950
+ var runInputSchema = { domain: domainSchema };
4951
+ function handleRun(getToken, baseUrl, args) {
4952
+ return runTool(() => apiJson(getToken, baseUrl, "POST", domainPath(args.domain, "/run")));
4953
+ }
4954
+ var OVERVIEW_DESCRIPTION2 = [
4955
+ "A domain's latest run (stats per source, records, merged, to review, conflicts) and its golden records that join two or more source rows, review and bank / tax id conflicts first, each with status, match score, member sources and conflicting fields.",
4956
+ 'USE WHEN: the headline ("how many duplicates across the ERPs, how many need review") or finding a record by name or source id.',
4957
+ "NOT FOR: one record's fields and reasons (talonic_master_records_get_record); single-source rows (talonic_master_records_crosswalk).",
4958
+ "",
4959
+ "ARGS: `domain`, `status` review|auto|accepted|split|conflict|all (default all), `query` (name or source id contains), `limit` (default 100), `offset`.",
4960
+ "RETURNS: { domain, run { id, status, stats, started_at, finished_at }, total, records[] { key, name, member_count, status, score, conflict_level, sources[] { source, id }, conflict_fields[] } }."
4961
+ ].join("\n");
4962
+ var overviewInputSchema = {
4963
+ domain: domainSchema,
4964
+ status: z.enum(["review", "auto", "accepted", "split", "conflict", "all"]).optional().describe("Only records with this status; conflict = any field disagreement."),
4965
+ query: z.string().max(200).optional().describe("Name or source id contains."),
4966
+ limit: z.number().int().min(1).max(5e3).optional().describe("Maximum records returned."),
4967
+ offset: z.number().int().min(0).optional().describe("Records to skip, for paging.")
4968
+ };
4969
+ function handleOverview2(getToken, baseUrl, args) {
4970
+ return runTool(
4971
+ () => apiJson(getToken, baseUrl, "GET", domainPath(args.domain, "/overview"), {
4972
+ params: { status: args.status, q: args.query, limit: args.limit, offset: args.offset }
4973
+ })
4974
+ );
4975
+ }
4976
+ var RECORD_DESCRIPTION = [
4977
+ "One golden record: each member row with its source and values, the golden value per field with the sources it came from, the fields where sources disagree (bank account and tax id are `bad`), the field-by-field reasons the rows were linked, status, score and any decision.",
4978
+ "USE WHEN: explaining why rows were merged, which system a value came from, or before accepting or splitting a record.",
4979
+ "NOT FOR: listing records (talonic_master_records_overview).",
4980
+ "",
4981
+ "ARGS: `domain`, `key` (from talonic_master_records_overview or talonic_master_records_crosswalk).",
4982
+ "RETURNS: { key, domain, name, members[] { source, id, values }, golden { <field> { value, from[] } }, conflicts[] { field, severity, values[] }, reasons[] { field, outcome, weight }, score, status, run_id, decision }."
4983
+ ].join("\n");
4984
+ var recordInputSchema = {
4985
+ domain: domainSchema,
4986
+ key: z.string().min(1).describe("Golden record key.")
4987
+ };
4988
+ function handleGetRecord(getToken, baseUrl, args) {
4989
+ return runTool(
4990
+ () => apiJson(
4991
+ getToken,
4992
+ baseUrl,
4993
+ "GET",
4994
+ domainPath(args.domain, `/records/${encodeURIComponent(args.key)}`)
4995
+ )
4996
+ );
4997
+ }
4998
+ var DECIDE_DESCRIPTION2 = [
4999
+ "Decide a golden record: `accept` keeps the merge, `split` breaks it into one record per source row, `reopen` removes an earlier decision. The domain is re-resolved at once and the decision survives every later run.",
5000
+ "USE WHEN: the user has reviewed a record and asks to accept or split it.",
5001
+ "NOT FOR: looking at the record (talonic_master_records_get_record).",
5002
+ "",
5003
+ "ARGS: `domain`, `key`, `decision` accept|split|reopen.",
5004
+ "RETURNS: { key, decision, stats } (stats of the re-run)."
5005
+ ].join("\n");
5006
+ var decideInputSchema2 = {
5007
+ domain: domainSchema,
5008
+ key: z.string().min(1).describe("Golden record key."),
5009
+ decision: z.enum(["accept", "split", "reopen"]).describe("accept, split or reopen.")
5010
+ };
5011
+ function handleDecide2(getToken, baseUrl, args) {
5012
+ return runTool(
5013
+ () => apiJson(
5014
+ getToken,
5015
+ baseUrl,
5016
+ "POST",
5017
+ domainPath(args.domain, `/records/${encodeURIComponent(args.key)}/decision`),
5018
+ { body: { decision: args.decision } }
5019
+ )
5020
+ );
5021
+ }
5022
+ var CHANGES_DESCRIPTION = [
5023
+ "Master data changes from the source systems' change logs, each checked against the evidence documents: a bank account change `matches` when a document for the party names the new account, `contradicts` when documents name another, `no_document` otherwise; flagged bank changes carry the party's open payables across every source as `exposure`. Read live; nothing is stored.",
5024
+ 'USE WHEN: "which bank detail changes have no document behind them", vendor bank fraud checks, terms changes.',
5025
+ "NOT FOR: the golden records (talonic_master_records_overview).",
5026
+ "",
5027
+ "ARGS: `domain`, `flagged` (only the changes that need attention).",
5028
+ "RETURNS: { domain, stats { changes, bank_changes, bank_matched, bank_contradicted, bank_no_document, terms_no_document, flagged, exposure, evidence_documents }, evidence_run, changes[] { source, id, field, old_value, new_value, changed_at, changed_by, golden_key, golden_name, verdict, flagged, evidence[], exposure, elsewhere[], explanation } }."
5029
+ ].join("\n");
5030
+ var changesInputSchema = {
5031
+ domain: domainSchema,
5032
+ flagged: z.boolean().optional().describe("Only flagged changes.")
5033
+ };
5034
+ function handleChanges(getToken, baseUrl, args) {
5035
+ return runTool(
5036
+ () => apiJson(getToken, baseUrl, "GET", domainPath(args.domain, "/changes"), {
5037
+ params: { flagged: args.flagged ? "true" : void 0 }
5038
+ })
5039
+ );
5040
+ }
5041
+ var CROSSWALK_DESCRIPTION = [
5042
+ "The crosswalk: every source row (source, source id) mapped to its golden record key and name and the record's status, single-source rows included.",
5043
+ "USE WHEN: looking up which golden record a system's id belongs to, or handing the mapping to another system.",
5044
+ "NOT FOR: the merge reasons (talonic_master_records_get_record).",
5045
+ "",
5046
+ "ARGS: `domain`.",
5047
+ "RETURNS: { domain, rows[] { golden_key, golden_name, source, source_id, status } }."
5048
+ ].join("\n");
5049
+ var crosswalkInputSchema = { domain: domainSchema };
5050
+ function handleCrosswalk(getToken, baseUrl, args) {
5051
+ return runTool(() => apiJson(getToken, baseUrl, "GET", domainPath(args.domain, "/crosswalk")));
5052
+ }
5053
+ function registerMasterRecordsTools(server, getToken, baseUrl) {
5054
+ const tools = [
5055
+ [
5056
+ "talonic_master_records_config",
5057
+ "Read the Master Records configuration",
5058
+ CONFIG_DESCRIPTION2,
5059
+ {},
5060
+ readOnly5,
5061
+ () => handleConfig2(getToken, baseUrl)
5062
+ ],
5063
+ [
5064
+ "talonic_master_records_save_config",
5065
+ "Save the Master Records configuration",
5066
+ SAVE_CONFIG_DESCRIPTION2,
5067
+ saveConfigInputSchema2,
5068
+ write5(true, true),
5069
+ (a) => handleSaveConfig2(getToken, baseUrl, a)
5070
+ ],
5071
+ [
5072
+ "talonic_master_records_run",
5073
+ "Resolve master records",
5074
+ RUN_DESCRIPTION,
5075
+ runInputSchema,
5076
+ write5(true),
5077
+ (a) => handleRun(getToken, baseUrl, a)
5078
+ ],
5079
+ [
5080
+ "talonic_master_records_overview",
5081
+ "Master records overview",
5082
+ OVERVIEW_DESCRIPTION2,
5083
+ overviewInputSchema,
5084
+ readOnly5,
5085
+ (a) => handleOverview2(getToken, baseUrl, a)
5086
+ ],
5087
+ [
5088
+ "talonic_master_records_get_record",
5089
+ "One golden record",
5090
+ RECORD_DESCRIPTION,
5091
+ recordInputSchema,
5092
+ readOnly5,
5093
+ (a) => handleGetRecord(getToken, baseUrl, a)
5094
+ ],
5095
+ [
5096
+ "talonic_master_records_decide",
5097
+ "Accept or split a golden record",
5098
+ DECIDE_DESCRIPTION2,
5099
+ decideInputSchema2,
5100
+ write5(true),
5101
+ (a) => handleDecide2(getToken, baseUrl, a)
5102
+ ],
5103
+ [
5104
+ "talonic_master_records_changes",
5105
+ "Master data changes checked against documents",
5106
+ CHANGES_DESCRIPTION,
5107
+ changesInputSchema,
5108
+ readOnly5,
5109
+ (a) => handleChanges(getToken, baseUrl, a)
5110
+ ],
5111
+ [
5112
+ "talonic_master_records_crosswalk",
5113
+ "Source id to golden record crosswalk",
5114
+ CROSSWALK_DESCRIPTION,
5115
+ crosswalkInputSchema,
5116
+ readOnly5,
5117
+ (a) => handleCrosswalk(getToken, baseUrl, a)
5118
+ ]
5119
+ ];
5120
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
5121
+ server.registerTool(
5122
+ name,
5123
+ { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
5124
+ async (args) => handler(args)
5125
+ );
5126
+ }
5127
+ }
5128
+ var readOnly6 = {
5129
+ readOnlyHint: true,
5130
+ destructiveHint: false,
5131
+ idempotentHint: true,
5132
+ openWorldHint: false
5133
+ };
5134
+ var write6 = (idempotent, destructive = false) => ({
5135
+ readOnlyHint: false,
5136
+ destructiveHint: destructive,
5137
+ idempotentHint: idempotent,
5138
+ openWorldHint: false
5139
+ });
5140
+ var specId = z.string().uuid().describe("Target structure id (talonic_submissions_specs). Omit to use none.");
5141
+ var SPECS_DESCRIPTION = [
5142
+ "List the workspace's target structures: the client formats submissions are mapped into, with field count and how many label mappings still await review.",
5143
+ "USE WHEN: before any other submissions tool, to pick the spec_id.",
5144
+ "NOT FOR: the submissions themselves (talonic_submissions_list).",
5145
+ "",
5146
+ "ARGS: none.",
5147
+ "RETURNS: [{ id, name, updated_at, field_count, labels_to_review }]."
5148
+ ].join("\n");
5149
+ function handleSpecs(getToken, baseUrl) {
5150
+ return runTool(() => apiJson(getToken, baseUrl, "GET", "/v1/submissions/specs"));
5151
+ }
5152
+ var LIST_DESCRIPTION = [
5153
+ "The inbox: every submission workbook of the workspace with its cedent, status (not_captured, captured, mapped, failed), captured values, facts and metrics under a target structure, and failed / warned checks.",
5154
+ 'USE WHEN: the headline ("which submissions are in, which are mapped, which have problems") or finding a submission by file name.',
5155
+ "NOT FOR: what to fix (talonic_submissions_issues); the facts (talonic_submissions_export).",
5156
+ "",
5157
+ "ARGS: `spec_id` (optional), `q` (file name contains), `limit` (default 100, max 500), `offset`.",
5158
+ "RETURNS: { total, submissions[] { document_id, filename, cedent, status, tables, values, facts, metrics, checks_failed, checks_warned, embedded_files, captured_at } }."
5159
+ ].join("\n");
5160
+ var listInputSchema = {
5161
+ spec_id: specId.optional(),
5162
+ q: z.string().optional().describe("File name contains."),
5163
+ limit: z.number().int().min(1).max(500).optional(),
5164
+ offset: z.number().int().min(0).optional()
5165
+ };
5166
+ function handleList(getToken, baseUrl, args) {
5167
+ return runTool(() => apiJson(getToken, baseUrl, "GET", "/v1/submissions", { params: args }));
5168
+ }
5169
+ var ISSUES_DESCRIPTION5 = [
5170
+ "The worklist: what needs a person, naming the submissions concerned. Kinds: not_captured, capture_failed, not_mapped, check_failed (with count), labels_to_review (with count), missing_metric (format metrics with no facts in a submission).",
5171
+ "USE WHEN: deciding what to do next; after talonic_submissions_process to see what is left.",
5172
+ "NOT FOR: the full list (talonic_submissions_list).",
5173
+ "",
5174
+ "ARGS: `spec_id` (optional; mapping-related kinds need it).",
5175
+ "RETURNS: [{ kind, document_id, filename, detail }]."
5176
+ ].join("\n");
5177
+ var issuesInputSchema3 = { spec_id: specId.optional() };
5178
+ function handleIssues5(getToken, baseUrl, args) {
5179
+ return runTool(
5180
+ () => apiJson(getToken, baseUrl, "GET", "/v1/submissions/issues", { params: args })
5181
+ );
5182
+ }
5183
+ var PROCESS_DESCRIPTION = [
5184
+ "Capture new workbooks and map submissions into a target structure, in bulk. Capturing is deterministic (no model); mapping classifies only labels the workspace has not seen, and reuses every earlier and every human decision. Run with dry_run first.",
5185
+ "USE WHEN: new submissions arrived (only: not_captured), or a target structure changed and submissions need re-mapping (only: not_mapped or all).",
5186
+ "NOT FOR: reading results (talonic_submissions_list, talonic_submissions_issues).",
5187
+ "",
5188
+ "ARGS: `spec_id` (map into this structure), `document_ids` (restrict), `only` not_captured|not_mapped|all (default all), `recapture` (capture again even when captured; replaces earlier facts), `limit` (default 50, max 200), `dry_run`.",
5189
+ "RETURNS: dry_run \u2192 { plan[] { document_id, filename, capture, map } }; otherwise { results[] { document_id, ok, facts?, checks_failed?, error? } }."
5190
+ ].join("\n");
5191
+ var processInputSchema = {
5192
+ spec_id: specId.optional(),
5193
+ document_ids: z.array(z.string().uuid()).max(200).optional(),
5194
+ only: z.enum(["not_captured", "not_mapped", "all"]).optional(),
5195
+ recapture: z.boolean().optional().describe("Capture again even when already captured; earlier facts are replaced."),
5196
+ limit: z.number().int().min(1).max(200).optional(),
5197
+ dry_run: z.boolean().optional().describe("List what would run; nothing runs.")
5198
+ };
5199
+ function handleProcess(getToken, baseUrl, args) {
5200
+ return runTool(
5201
+ () => apiJson(getToken, baseUrl, "POST", "/v1/submissions/process", { body: args })
5202
+ );
5203
+ }
5204
+ var COMPLETENESS_DESCRIPTION = [
5205
+ "One submission against a target structure: for every metric the client's format knows, how many facts the submission has and which fields they fill, plus metrics found that are not in the format.",
5206
+ "USE WHEN: judging whether a submission carries what a quote needs, or explaining what is missing.",
5207
+ "NOT FOR: the facts themselves (talonic_submissions_export).",
5208
+ "",
5209
+ "ARGS: `document_id`, `spec_id`.",
5210
+ "RETURNS: { metrics[] { metric, in_format, facts, fields[] } }."
5211
+ ].join("\n");
5212
+ var completenessInputSchema = {
5213
+ document_id: z.string().uuid().describe("Submission (workbook document) id."),
5214
+ spec_id: specId
5215
+ };
5216
+ function handleCompleteness(getToken, baseUrl, args) {
5217
+ return runTool(
5218
+ () => apiJson(
5219
+ getToken,
5220
+ baseUrl,
5221
+ "GET",
5222
+ `/v1/submissions/${encodeURIComponent(args.document_id)}/completeness`,
5223
+ {
5224
+ params: { spec_id: args.spec_id }
5225
+ }
5226
+ )
5227
+ );
5228
+ }
5229
+ var EXPORT_DESCRIPTION = [
5230
+ "Facts in the client's long format: a header (the structure's fields, then Metric, Figure, Document, Source) and one row per figure; Source is the cell the figure came from. Large: prefer one document.",
5231
+ "USE WHEN: handing facts to the client or another system, or answering a question about figures.",
5232
+ "NOT FOR: the inbox (talonic_submissions_list).",
5233
+ "",
5234
+ "ARGS: `spec_id`, `document_id` (optional; all submissions when omitted).",
5235
+ "RETURNS: { header[], rows[][] }."
5236
+ ].join("\n");
5237
+ var exportInputSchema = {
5238
+ spec_id: specId,
5239
+ document_id: z.string().uuid().optional().describe("Only this submission.")
5240
+ };
5241
+ function handleExport(getToken, baseUrl, args) {
5242
+ return runTool(
5243
+ () => apiJson(getToken, baseUrl, "GET", "/v1/submissions/export", { params: args })
5244
+ );
5245
+ }
5246
+ function registerSubmissionsTools(server, getToken, baseUrl) {
5247
+ const tools = [
5248
+ [
5249
+ "talonic_submissions_specs",
5250
+ "Submission target structures",
5251
+ SPECS_DESCRIPTION,
5252
+ {},
5253
+ readOnly6,
5254
+ () => handleSpecs(getToken, baseUrl)
5255
+ ],
5256
+ [
5257
+ "talonic_submissions_list",
5258
+ "Submissions inbox",
5259
+ LIST_DESCRIPTION,
5260
+ listInputSchema,
5261
+ readOnly6,
5262
+ (a) => handleList(getToken, baseUrl, a)
5263
+ ],
5264
+ [
5265
+ "talonic_submissions_issues",
5266
+ "Submissions worklist",
5267
+ ISSUES_DESCRIPTION5,
5268
+ issuesInputSchema3,
5269
+ readOnly6,
5270
+ (a) => handleIssues5(getToken, baseUrl, a)
5271
+ ],
5272
+ [
5273
+ "talonic_submissions_process",
5274
+ "Capture and map submissions",
5275
+ PROCESS_DESCRIPTION,
5276
+ processInputSchema,
5277
+ write6(true),
5278
+ (a) => handleProcess(getToken, baseUrl, a)
5279
+ ],
5280
+ [
5281
+ "talonic_submissions_completeness",
5282
+ "Submission completeness",
5283
+ COMPLETENESS_DESCRIPTION,
5284
+ completenessInputSchema,
5285
+ readOnly6,
5286
+ (a) => handleCompleteness(getToken, baseUrl, a)
5287
+ ],
5288
+ [
5289
+ "talonic_submissions_export",
5290
+ "Export submission facts",
5291
+ EXPORT_DESCRIPTION,
5292
+ exportInputSchema,
5293
+ readOnly6,
5294
+ (a) => handleExport(getToken, baseUrl, a)
5295
+ ]
5296
+ ];
5297
+ for (const [name, title, description, inputSchema11, annotations, handler] of tools) {
5298
+ server.registerTool(
5299
+ name,
5300
+ { title, description, inputSchema: inputSchema11, annotations: { title, ...annotations } },
5301
+ async (args) => handler(args)
5302
+ );
5303
+ }
5304
+ }
4339
5305
  var DEFAULT_BASE3 = "https://api.talonic.com";
4340
5306
  var TASK_STATUSES = ["available", "claimed", "submitted", "timed_out", "cancelled"];
4341
5307
  var taskId = z.string().uuid().describe("Agent task UUID.");
@@ -5061,7 +6027,7 @@ async function resolveFieldId(getToken, baseUrl, args) {
5061
6027
  resolution: { matched_by: resolved.matched_by, redirected_from: resolved.redirected_from }
5062
6028
  };
5063
6029
  }
5064
- var LIST_DESCRIPTION = [
6030
+ var LIST_DESCRIPTION2 = [
5065
6031
  "List the workspace's Field Registry \u2014 the canonical concepts Talonic has discovered across every ingested document, each with a stable id, maturity level, data type, synonyms and occurrence count.",
5066
6032
  "",
5067
6033
  "USE WHEN: you need to know WHAT data exists before querying it, want to pick the right concept for a question, or need the exact field id for talonic_get_field / talonic_field_values.",
@@ -5175,7 +6141,7 @@ function registerFieldTools(server, getToken, baseUrl) {
5175
6141
  "talonic_list_fields",
5176
6142
  {
5177
6143
  title: "List Registry Fields",
5178
- description: LIST_DESCRIPTION,
6144
+ description: LIST_DESCRIPTION2,
5179
6145
  inputSchema: listFieldsInputSchema,
5180
6146
  annotations: {
5181
6147
  title: "List Registry Fields",
@@ -5397,7 +6363,7 @@ function registerAgentRegistryTools(server, getToken, baseUrl, opts = {}) {
5397
6363
  async (args) => handleInvokeAgentTool(getToken, baseUrl, args)
5398
6364
  );
5399
6365
  }
5400
- var LIST_DESCRIPTION2 = [
6366
+ var LIST_DESCRIPTION3 = [
5401
6367
  "List the workspace's Specs \u2014 the configured pipelines (rail + fields) that talonic_run_spec executes. Each row: id, name, description, schema_id (the schema a run materializes onto \u2014 a DIFFERENT id from the Spec's), version / materialized_version (null = never published), field_count, node_count, timestamps.",
5402
6368
  "",
5403
6369
  "USE WHEN: the user wants to run 'their pipeline' / 'the invoice Spec', or you need a spec_id for talonic_run_spec / talonic_get_spec.",
@@ -5457,7 +6423,7 @@ function registerSpecTools(server, getToken, baseUrl) {
5457
6423
  "talonic_list_specs",
5458
6424
  {
5459
6425
  title: "List Specs",
5460
- description: LIST_DESCRIPTION2,
6426
+ description: LIST_DESCRIPTION3,
5461
6427
  inputSchema: listSpecsInputSchema,
5462
6428
  annotations: { title: "List Specs", ...READ_ONLY4 },
5463
6429
  _meta: widgetToolMeta("listSpecs")
@@ -5482,7 +6448,7 @@ function mapRunStatus(raw) {
5482
6448
  return "failed";
5483
6449
  return "processing";
5484
6450
  }
5485
- var RUN_DESCRIPTION = [
6451
+ var RUN_DESCRIPTION2 = [
5486
6452
  "Run a Spec \u2014 the customer's configured pipeline \u2014 over documents, in one call. Two inputs: `document_ids` (documents already in the workspace; for a new file, first talonic_request_upload \u2192 poll talonic_get_document until completed) OR `file_urls` (public https files, max 20; Talonic ingests them first). Consumes credits.",
5487
6453
  "",
5488
6454
  "USE WHEN: the user wants to 'run the invoice pipeline on these documents', process files through their Spec, or produce the Spec's structured rows.",
@@ -5697,7 +6663,7 @@ function registerRunTools(server, getToken, baseUrl) {
5697
6663
  "talonic_run_spec",
5698
6664
  {
5699
6665
  title: "Run a Spec pipeline",
5700
- description: RUN_DESCRIPTION,
6666
+ description: RUN_DESCRIPTION2,
5701
6667
  inputSchema: runSpecInputSchema,
5702
6668
  annotations: {
5703
6669
  title: "Run a Spec pipeline",
@@ -5871,7 +6837,7 @@ function registerAskTools(server, getToken, baseUrl) {
5871
6837
 
5872
6838
  // package.json
5873
6839
  var package_default = {
5874
- version: "0.1.88"};
6840
+ version: "0.1.90"};
5875
6841
 
5876
6842
  // src/version.ts
5877
6843
  var VERSION = package_default.version;
@@ -5924,7 +6890,7 @@ function buildServerInstructions(opts) {
5924
6890
  "apps:decide consent and a senior_member role or above; if a decision tool is marked",
5925
6891
  "not invocable in this session, or a call returns 403, tell the user which consent or",
5926
6892
  "role is missing instead of retrying.",
5927
- "Tools that change workspace data (saving schemas, contract and AP updates, decisions)",
6893
+ "Tools that change workspace data (saving schemas, contract, AP and master record updates, decisions)",
5928
6894
  "should only be called when the user asked for that change."
5929
6895
  ].join(" ");
5930
6896
  }
@@ -6031,6 +6997,15 @@ function createServer(options) {
6031
6997
  if (options.includeDocGenTools) {
6032
6998
  registerDocGenTools(server, rawToken, baseUrl, { localFiles: !options.tokenProvider });
6033
6999
  }
7000
+ if (options.includePartiesTools) {
7001
+ registerPartiesTools(server, rawToken, baseUrl);
7002
+ }
7003
+ if (options.includeMasterRecordsTools) {
7004
+ registerMasterRecordsTools(server, rawToken, baseUrl);
7005
+ }
7006
+ if (options.includeSubmissionsTools) {
7007
+ registerSubmissionsTools(server, rawToken, baseUrl);
7008
+ }
6034
7009
  registerSchemasResource(server, getTalonic);
6035
7010
  registerWebhooksResource(server, rawToken, baseUrl);
6036
7011
  registerWidgets(server);