iit-mcp-autotask 0.61.1 → 0.62.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/.env.example CHANGED
@@ -88,6 +88,9 @@ AUTOTASK_PROFILE=readonly
88
88
  AUTOTASK_CACHE=on
89
89
 
90
90
  # --- Vendor budget (the server boots the SDK in the conservative `agent` profile; overrides here) ---
91
+ # These are per-client allowances. The SDK also caps each object/tracking identifier at
92
+ # 3 active requests and shares a conservative origin-wide 10,000-attempt hourly ceiling
93
+ # in this JavaScript runtime. Other processes and integrations need separate coordination.
91
94
  # AUTOTASK_RATE_LIMIT_PER_HOUR=8000
92
95
  # AUTOTASK_MAX_CONCURRENT=3
93
96
  # AUTOTASK_TIMEOUT_MS=20000
package/README.md CHANGED
@@ -29,7 +29,16 @@ examples; `full: true` serves the complete record, `summary: true` about 2 KB),
29
29
  `"serial"` or `"email"`, in one `resource` or swept across the five workflow resources;
30
30
  the default `match: "auto"` tries exact, then contains on a miss for companies, tickets (title) or a
31
31
  sweep (one hit: `ok` with `matched: "contains"`; several: `ambiguous`), `match: "exact"` has no
32
- fallback, `match: "contains"` searches only. `resource: "resources"` finds staff by
32
+ fallback, `match: "contains"` searches only. Explicit `resource: "companies"` also falls back
33
+ to fuzzy after a contains miss; `match: "fuzzy"` goes directly to company candidates (by
34
+ `id_or_name` only, at most 10, lower with `limit`). Every fuzzy hit is `ambiguous` /
35
+ `choose_candidate`, even one at distance zero. Candidates carry `ref`, `record`, `distance`,
36
+ `matchedTerms`, `coverage`, `source`; `data` carries `tier`, `truncated`, `pieces`, `index.state`
37
+ and optional `index.builtAt`. Empty fuzzy results are `needs_input`, never proof of absence:
38
+ cold/building indexes suggest retry; warm/off searches suggest narrowing or a known id.
39
+ `include_family` also applies to fuzzy. `include_inactive: true` applies only to fuzzy candidates
40
+ with companies + fuzzy/auto (default false: active-only fuzzy candidates); exact and contains
41
+ keep their existing activity behavior. Sweeps and other resources never use fuzzy. `resource: "resources"` finds staff by
33
42
  email, user name or name (active only; API users, which carry their owner's email, are excluded unless
34
43
  `include_api_users: true`; `by: "email"` narrows to the email field; a numeric identifier is looked up
35
44
  as a Resource id); compact rows carry `apiUser` and the licence label when the tenant's labels tell it, never an email. Every match carries `ref`, its human reference, as safe text: control and markup characters (`< > { } [ ] \` " | \\`) dropped, whitespace collapsed, at most 80 characters (a cut ends with `…`), never wrapped; still vendor-authored data (#230). A sweep returns compact matches (`resource`, `ref`, `id`, the human fields) unless `expand: true` (the record under `record`, without its `[REDACTED]`, null and empty fields; `expand: "full"` keeps them); `limit` caps the TOTAL matches across resources (resource order, then the SDK's order) and a contains sweep reports `truncated` and per-resource `counts {returned, found}`.
@@ -153,6 +162,14 @@ preview's `approval`, or `PLAN_MISMATCH`), after checking that nothing it depend
153
162
  are numeric ids, never names (resolve a name with `autotask_resolve` first). Applying the same plan
154
163
  again replays the recorded outcome instead of writing twice.
155
164
 
165
+ Independent snapshot reads overlap within the SDK's concurrency limits. Apply still re-reads the
166
+ vendor references and duplicate state before sending; no reference results are reused from preview.
167
+ For `time_entries.create`, apply accepts optional `readBack: "time_entry_verification_v1"` to return
168
+ the [verification projection](#complete-time-entry-note-verification) in `data.record` through its existing fresh
169
+ read-back. Omit it or use `readBack: "record"` for the normal record. This can save a separate client
170
+ verification read. A failed read-back leaves the write successful with `data.record: null`; a replay
171
+ returns the recorded outcome without another send or read-back.
172
+
156
173
  An operator deployment needs:
157
174
 
158
175
  | Variable | Meaning |
@@ -494,10 +511,10 @@ non-zero on an invalid config (fail-fast) instead of failing at the first tool c
494
511
  | `AUTOTASK_BASE_URL` | stdio: yes · http: no (default origin) | — | the zone origin, e.g. `https://webservices6.autotask.net` (zone lives in the host; base path `/atservicesrest` is fixed — never configurable) |
495
512
  | `AUTOTASK_ALLOWED_BASE_HOSTS` | http: unless `AUTOTASK_ALLOW_ANY_BASE_HOST=true` | — | comma-separated exact hostnames or `*.suffix` subdomain suffixes a caller may name in `X-Autotask-Base-Url` (no scheme/port/path). Unset + default origin set → only that origin accepted. Unset + no default → boot refused unless the lab-only flag. **Recommended production value: `*.autotask.net`**. Literal private-IP origins are always refused. |
496
513
  | `AUTOTASK_ALLOW_ANY_BASE_HOST` | no | `false` | lab-only opt-in to boot with neither allow-list nor default origin; `warn`-logged at boot (decision D-4); refused with the operator profile. Not set in production. |
497
- | `AUTOTASK_CACHE` | no | `on` | the single off switch for the SDK's per-tenant in-process caches (see [Per-tenant pool & cache](#per-tenant-pool--cache)): `on` (default) sends no cache block — the SDK's default-on caches apply to each pooled tenant client (read ~5 min + the reference tables at 1 h, field metadata ~5 min); `off` sends `cache: false` (every read re-dials the vendor) |
514
+ | `AUTOTASK_CACHE` | no | `on` | the single off switch for the SDK's per-tenant in-process caches (see [Per-tenant pool & cache](#per-tenant-pool--cache)): `on` (default) sends no cache block — the SDK's default-on caches apply to each pooled tenant client (read ~5 min + the reference tables at 1 h, field metadata ~5 min, plus the fuzzy company-name index below); `off` sends `cache: false` (every read re-dials the vendor) |
498
515
  | `AUTOTASK_OUTPUT_DIR` | no | unset | the ONE directory the `output_path` option may write into (the bounded query tools and the invoice export; stdio transport only). Unset = defaults to `output/` under `AUTOTASK_STATE_DIR` (the feature refuses when neither is set); must be absolute, must already EXIST (the server never creates the root) and must not be the filesystem root. A caller path is relative to this root, and the root and target are canonically resolved (`realpath`) so a traversal or symlink escape is refused — with nothing created outside the root. See [Query results](#query-results-tsv-output_path-and-the-saved-file-shape) |
499
- | `AUTOTASK_RATE_LIMIT_PER_HOUR` | no | 8000 (agent profile) | override the SDK's local hourly budget (never above the vendor cap; `null`/off is rejected at boot — it would void the budget guard) |
500
- | `AUTOTASK_MAX_CONCURRENT` | no | 3 (agent profile) | override the SDK's local concurrency bound |
516
+ | `AUTOTASK_RATE_LIMIT_PER_HOUR` | no | 8000 (agent profile) | override the SDK's local hourly allowance (at most 10,000; `null`/off is rejected at boot); the shared SDK origin ceiling remains enforced |
517
+ | `AUTOTASK_MAX_CONCURRENT` | no | 3 (agent profile) | override local aggregate concurrency across objects (1–10); the SDK still caps each object/tracking identifier at three active requests |
501
518
  | `AUTOTASK_TIMEOUT_MS` | no | 20000 (agent profile) | whole-call budget |
502
519
  | `AUTOTASK_MAX_RETRIES` | no | 1 (agent profile) | bounded retries with backoff (idempotent methods, 429/5xx only) |
503
520
  | `MCP_HOST` | no | `127.0.0.1` | http bind address (`--host` overrides it). Off loopback, `AUTOTASK_HTTP_ALLOWED_HOSTS` and `AUTOTASK_HTTP_AUTH` are required |
@@ -687,6 +704,11 @@ guards (rate limiter, 429 cooldown) — a worse security posture, not a safer on
687
704
  tables ~1 h, field metadata ~5 min). Repeated reads of the same record are served from that
688
705
  tenant's cache until TTL expiry; composites de-duplicate their 3–8 fan-out reads through it.
689
706
  `off` sends `cache: false` (every read re-dials the vendor).
707
+ Fuzzy company search always performs an uncached live fragment query (at most 500 rows).
708
+ Separately, the SDK lazily builds a slim company-name index in the background, refreshes it
709
+ every 30 minutes and clears it after company writes (rebuild debounced for one second).
710
+ `AUTOTASK_CACHE=off` disables that index; results remain live-only with `index.state: "off"`.
711
+ Cold/building indexes and capped live searches can miss companies: inspect the returned metadata.
690
712
  - **Boundaries — never relaxed:** in-process only (never on disk), **per-tenant** (one tenant's
691
713
  cached records or limiter state can never answer another tenant's request), TTL-bounded, cleared
692
714
  on eviction and on `401`. The same boundary covers the limiter/cooldown state.
@@ -817,9 +839,15 @@ With `AUTOTASK_HTTP_AUTH=gateway` the gateway is the control plane. It owns: cli
817
839
  per-tenant tool filtering/exposure, **credential injection** into the `X-Autotask-*` headers, the per-request identity headers `x-autotask-client-id` and `x-autotask-principal` (see [docs/write-gate.md](docs/write-gate.md#gateway-identity); the gateway must strip client-supplied copies) and rate
818
840
  limiting (`/metadata` states the delegation). The server still validates `Host`/`Origin` and caps
819
841
  bodies at 1 MiB. With `AUTOTASK_HTTP_AUTH=tokens` this process authenticates callers and
820
- rate-limits per principal itself. Either way the vendor-side budget (10,000 req/hour, ≤10 concurrent
821
- per integration) is guarded by the SDK agent profile (8,000/hr local budget, 3 concurrent) and exposed
822
- live through `autotask_tenant_status`.
842
+ rate-limits per principal itself. The vendor allows three simultaneous requests per object endpoint
843
+ and tracking identifier, and 10,000 requests per trailing hour across the database's integrations.
844
+ The SDK enforces shared object admission and a conservative origin-wide hourly ceiling across its
845
+ clients in this JavaScript runtime; its agent profile adds a lower per-client allowance (8,000/hr,
846
+ three concurrent across objects). Tenants on the same zone origin share that hourly ceiling, so
847
+ one tenant's traffic can reduce another tenant's available allowance; tenants sharing an integration
848
+ code also share object slots. `autotask_tenant_status` exposes vendor thresholds and the local
849
+ client budget; that local snapshot is not the shared hourly counter. Other processes, workers and
850
+ external integrations require separate coordination.
823
851
 
824
852
  See [docs/architecture.md](docs/architecture.md) section 5 for intentional omissions and blocked capabilities.
825
853
 
package/capabilities.json CHANGED
@@ -74,7 +74,7 @@
74
74
  },
75
75
  {
76
76
  "id": "autotask.platform.catalog",
77
- "description": "Find the exact operation key for anything without a dedicated tool: ranked search (q) over the 1,247 registry operations, with effect and whether this deployment serves it. No vendor call.",
77
+ "description": "Find the exact operation key for anything without a dedicated tool: ranked search (q) over the 1,248 registry operations, with effect and whether this deployment serves it. No vendor call.",
78
78
  "mcpPrimitive": "tool",
79
79
  "toolName": "autotask_catalog",
80
80
  "type": "read",
@@ -122,13 +122,13 @@
122
122
  },
123
123
  {
124
124
  "id": "autotask.discovery.resolve",
125
- "description": "Find the record for an identifier: id or name, ticket number, CI serial, contact email (by), staff by email, user name or name (resource resources, include_api_users); one resource or a sweep. Exact, then contains on a miss.",
125
+ "description": "Find the record for an identifier: id or name, ticket number, CI serial, contact email (by), staff by email, user name or name (resource resources, include_api_users); one resource or a sweep. Exact, then contains; companies add fuzzy candidates.",
126
126
  "mcpPrimitive": "tool",
127
127
  "toolName": "autotask_resolve",
128
128
  "type": "read",
129
129
  "toolset": "core",
130
130
  "profile": "readonly",
131
- "backingOperation": "operations.resolveAny | operations.resolveStaff | operations.searchAcrossResources | companies.resolve | companies.search | configuration_items.resolve | contacts.resolve | projects.resolve | tickets.resolve | tickets.findByTicketNumber | configuration_items.findBySerial | contacts.findByEmail | tickets.search | resources.query | resources.get | operations.fieldCatalog",
131
+ "backingOperation": "operations.resolveAny | operations.resolveStaff | operations.searchAcrossResources | companies.resolve | companies.search | companies.searchFuzzy | configuration_items.resolve | contacts.resolve | projects.resolve | tickets.resolve | tickets.findByTicketNumber | configuration_items.findBySerial | contacts.findByEmail | tickets.search | resources.query | resources.get | operations.fieldCatalog",
132
132
  "annotations": {
133
133
  "readOnly": true,
134
134
  "idempotent": true,
@@ -480,7 +480,7 @@
480
480
  "autotask_describe",
481
481
  "autotask_read"
482
482
  ],
483
- "backingRegistryOperations": 1247,
483
+ "backingRegistryOperations": 1248,
484
484
  "note": "autotask_catalog finds the exact operation key (ranked search), autotask_describe serves its contract, autotask_read runs any effect=read key. Writes go through the operator profile (autotask_write then autotask_apply); authenticate.* is never served."
485
485
  },
486
486
  "schemas": {}
@@ -16,7 +16,7 @@ export type Profile = (typeof PROFILES)[number];
16
16
  /** The optional toolsets `AUTOTASK_TOOLSETS` selects; `core` is always registered. */
17
17
  export declare const TOOLSETS: readonly ["service", "records", "finance"];
18
18
  export type Toolset = (typeof TOOLSETS)[number];
19
- /** The vendor's hard cap on requests per hour per integration (the local limiter must not exceed it). */
19
+ /** The database-wide vendor hourly ceiling; the optional local quota must not exceed it. */
20
20
  export declare const VENDOR_HOURLY_CAP = 10000;
21
21
  /**
22
22
  * A run scope: the companies one operator principal may write in this run. `{all: true}` means the
@@ -14,7 +14,7 @@ export const TRANSPORTS = ['stdio', 'http'];
14
14
  export const PROFILES = ['readonly', 'operator'];
15
15
  /** The optional toolsets `AUTOTASK_TOOLSETS` selects; `core` is always registered. */
16
16
  export const TOOLSETS = ['service', 'records', 'finance'];
17
- /** The vendor's hard cap on requests per hour per integration (the local limiter must not exceed it). */
17
+ /** The database-wide vendor hourly ceiling; the optional local quota must not exceed it. */
18
18
  export const VENDOR_HOURLY_CAP = 10_000;
19
19
  /**
20
20
  * A run scope: the companies one operator principal may write in this run. `{all: true}` means the
@@ -192,11 +192,11 @@ export const CONFIG_FIELDS = z
192
192
  AUTOTASK_OUTPUT_DIR: blankToUndefined.optional(),
193
193
  /**
194
194
  * The client-side hourly budget (vendor cap 10,000 req/hour; the `agent` profile default is
195
- * 8,000). Positive integer only — `null`/off is rejected at boot: disabling the limiter
196
- * would void the local vendor-budget guard.
195
+ * 8,000). Positive integer only — `null`/off is rejected at boot to retain this lower local
196
+ * allowance. The SDK separately enforces its shared origin ceiling.
197
197
  */
198
198
  AUTOTASK_RATE_LIMIT_PER_HOUR: z.coerce.number().int().min(1).max(VENDOR_HOURLY_CAP).optional(),
199
- /** The concurrency guard (vendor allows <= 10). The `agent` profile default is 3. */
199
+ /** Local aggregate concurrency across objects (agent default 3); SDK object/tracking admission stays capped at 3. */
200
200
  AUTOTASK_MAX_CONCURRENT: z.coerce.number().int().min(1).max(10).optional(),
201
201
  /** The whole-call deadline in ms. The `agent` profile default is 20,000. */
202
202
  AUTOTASK_TIMEOUT_MS: z.coerce.number().int().positive().optional(),
@@ -107,7 +107,7 @@ export declare function sdkCacheOptions(cache: 'on' | 'off'): Pick<AutotaskConfi
107
107
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
108
108
  * describes the SDK behind it.
109
109
  */
110
- export declare const BUILT_AGAINST_PLAN_HASH = "448bad244d0dfa1f8af0f6dfa4bc1a080ca60a114dc10366660585ff2dbc3e55";
110
+ export declare const BUILT_AGAINST_PLAN_HASH = "959981d335cfd184d8b4e58074d1ab6997b2db87a62683ed13e99c149f8cd4fa";
111
111
  /**
112
112
  * Fail fast when the installed SDK's plan has moved out from under this surface.
113
113
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -55,6 +55,7 @@ export const TOOL_NAME_BY_OP = {
55
55
  'operations.relationshipMap': 'autotask_describe',
56
56
  'companies.resolve': 'autotask_resolve',
57
57
  'companies.search': 'autotask_resolve',
58
+ 'companies.searchFuzzy': 'autotask_resolve',
58
59
  'configuration_items.resolve': 'autotask_resolve',
59
60
  'contacts.resolve': 'autotask_resolve',
60
61
  'projects.resolve': 'autotask_resolve',
@@ -130,7 +131,7 @@ export const TOOL_DESCRIPTIONS = {
130
131
  autotask_catalog: `Find the exact operation key for anything without a dedicated tool: ranked search (q) over the ${RECORDS.length.toLocaleString('en-US')} registry operations, with effect and whether this deployment serves it. No vendor call.`,
131
132
  autotask_describe: 'One operation\'s (registry key or tool name) exact input/output contract, examples, errors, policy verdict and playbooks (operation), or one resource\'s relationship map: parent, children, lookup keys (resource). No vendor call.',
132
133
  autotask_read: 'Run one or several reads in one call by exact registry key: unbilled work, profitability and margin, SLA health. Scope by company/contract ids (unscoped = tenant walk); totals: autotask_query group_by; slim: includeFields, noteChars.',
133
- autotask_resolve: 'Find the record for an identifier: id or name, ticket number, CI serial, contact email (by), staff by email, user name or name (resource resources, include_api_users); one resource or a sweep. Exact, then contains on a miss.',
134
+ autotask_resolve: 'Find the record for an identifier: id or name, ticket number, CI serial, contact email (by), staff by email, user name or name (resource resources, include_api_users); one resource or a sweep. Exact, then contains; companies add fuzzy candidates.',
134
135
  autotask_query: 'List records or totals with a filter: tickets, time entries, service calls, contracts, time off, more. Totals, no rows: group_by, sum, count (hours logged by ticket, how many match). By id: id in. Scope by company ids (unscoped = tenant walk).',
135
136
  autotask_tenant_status: 'Identity (API user + impersonated user), Autotask API version, this server\'s package/SDK version and profile (server), request thresholds, and the time zone of the people asking, with local and UTC time (time). Use it first to check credentials.',
136
137
  autotask_ticket_full_context: 'One ticket with its company, contact, assigned resource, project, notes, time entries and attachment metadata. Missing parts degrade to typed absent; a missing ticket is not found.',
@@ -186,7 +187,7 @@ export function sdkCacheOptions(cache) {
186
187
  * fails the boot (or the CI test) instead of quietly shipping a tool surface that no longer
187
188
  * describes the SDK behind it.
188
189
  */
189
- export const BUILT_AGAINST_PLAN_HASH = '448bad244d0dfa1f8af0f6dfa4bc1a080ca60a114dc10366660585ff2dbc3e55';
190
+ export const BUILT_AGAINST_PLAN_HASH = '959981d335cfd184d8b4e58074d1ab6997b2db87a62683ed13e99c149f8cd4fa';
190
191
  /**
191
192
  * Fail fast when the installed SDK's plan has moved out from under this surface.
192
193
  * Called at boot (main.ts) and safe to call repeatedly (pure comparison).
@@ -24,8 +24,8 @@ export function buildSdkBaseOptions(config, log) {
24
24
  const defaultBase = config.AUTOTASK_BASE_URL;
25
25
  const defaultBaseUrl = defaultBase === undefined ? undefined : normalizeBaseUrl(defaultBase)?.baseUrl;
26
26
  return {
27
- // The vendor budget guard: never the `library` defaults, never an operator-tuned value
28
- // above the vendor cap (config validation enforces the cap).
27
+ // Lower per-client budgets supplement the SDK's always-on shared object/thread
28
+ // and origin/hourly admission. Config validation bounds local overrides.
29
29
  profile: 'agent',
30
30
  // Keep LLM-facing name/label siblings enabled (SDK labels are opt-in).
31
31
  labels: true,
@@ -29,14 +29,14 @@ import { zoneClock } from './clock.js';
29
29
  import { typedErrorPayload } from './results/errors.js';
30
30
  import { markResult, sanitiseVendorOutput } from './results/untrusted.js';
31
31
  import { errorEnvelope, ok } from './results/envelope.js';
32
- import { bm25Rank } from './rank.js';
32
+ import { compileBm25 } from './rank.js';
33
33
  import { playbooksFor } from './guide.js';
34
34
  import { FIELD_INFO_EXPENSIVE, fieldLookupCall, udfCatalogCall } from './field-pointer.js';
35
35
  import { SERVER_NAME, SERVER_VERSION } from './server-version.js';
36
36
  import { CATALOG_INPUT, DESCRIBE_INPUT, AR_AGING_INPUT, WIP_HOURS_INPUT, NON_CHARGEABLE_WORK_INPUT, COMPANY_FULL_PROFILE_INPUT, CONFIGURATION_ITEM_PROFILE_INPUT, CONTACT_FULL_PROFILE_INPUT, CONTRACT_FULL_PROFILE_INPUT, INVOICE_GET_INPUT, PORTFOLIO_MARGIN_INPUT, RECURRING_REVENUE_INPUT, REVENUE_ROLLUP_INPUT, PROJECT_GET_CONTEXT_INPUT, QUERY_INPUT, QUOTE_GET_INPUT, RESOLVE_INPUT, RESOURCE_WORKLOAD_INPUT, SERVICE_CALL_FULL_PROFILE_INPUT, TICKET_FULL_CONTEXT_INPUT, QUERY_LIMIT, READ_INPUT, TENANT_STATUS_INPUT, TENANT_STATUS_PARTS, readIgnoredKeys, closedInput, } from './schemas.js';
37
37
  import { refusalReason } from '../policy.js';
38
- /** Search text per catalog row (key words, the serving tool, purpose), built once. */
39
- const ROW_TEXT = CATALOG.catalog.map((r) => `${r.operation} ${r.operation.replace(/[._]/g, ' ')} ${toolForOp(r.operation) ?? ''} ${r.purpose ?? ''}`);
38
+ /** Static registry search metadata; vendor reads and per-deployment boosts never enter this index. */
39
+ const CATALOG_INDEX = compileBm25(CATALOG.catalog.map((r) => `${r.operation} ${r.operation.replace(/[._]/g, ' ')} ${toolForOp(r.operation) ?? ''} ${r.purpose ?? ''}`));
40
40
  /** `autotask_catalog`: the filtered, ranked, paged registry rows with this deployment's verdicts. */
41
41
  export function buildCatalog(ctx) {
42
42
  return {
@@ -51,7 +51,7 @@ export function buildCatalog(ctx) {
51
51
  const r = CATALOG.catalog[i];
52
52
  return (servedToolName(r, ctx.served) !== null && r.effect === 'read' ? 1.5 : 1) * (r.deprecated === true ? 0.5 : 1);
53
53
  };
54
- const order = args.q === undefined ? CATALOG.catalog.map((_, i) => i) : bm25Rank(ROW_TEXT, args.q, { boost, strict: true });
54
+ const order = args.q === undefined ? CATALOG.catalog.map((_, i) => i) : CATALOG_INDEX.rank(args.q, { boost, strict: true });
55
55
  // #277: the date-window helpers are hidden unless include_hidden; an exact key always resolves.
56
56
  const exact = CATALOG.catalog.findIndex((r) => r.operation === key);
57
57
  const ranked = exact >= 0 ? [exact, ...order.filter((i) => i !== exact)] : order;
@@ -128,7 +128,7 @@ const TOOL_INPUT = {
128
128
  };
129
129
  /** Tools whose argument SHAPE (not just casing) differs from the SDK call. */
130
130
  const SHAPE_NOTES = {
131
- autotask_resolve: 'flat args, not the SDK identifier + opts bag: identifier -> identifier (positional in every key); by picks the key (ticket_number -> tickets.findByTicketNumber, serial -> configuration_items.findBySerial, email -> contacts.findByEmail, id_or_name -> <resource>.resolve); no resource -> operations.resolveAny (match exact) or operations.searchAcrossResources (match contains), resource companies + match contains -> companies.search; resource tickets + match contains -> tickets.search (title contains; company_id -> companyID); the opts bag is built from expand, include_family (includeFamily), limit and resources',
131
+ autotask_resolve: 'flat args, not the SDK identifier + opts bag: identifier -> identifier (positional in every key); by picks the key (ticket_number -> tickets.findByTicketNumber, serial -> configuration_items.findBySerial, email -> contacts.findByEmail, id_or_name -> <resource>.resolve); no resource -> operations.resolveAny (match exact) or operations.searchAcrossResources (match contains), resource companies + match contains -> companies.search, match fuzzy -> companies.searchFuzzy (always candidates); auto companies: exact -> contains -> fuzzy on misses; include_inactive -> includeInactive only for fuzzy candidates (default false), never an exact/contains filter; resource tickets + match contains -> tickets.search (title contains; company_id -> companyID); the opts bag is built from expand, include_family (includeFamily), limit and resources',
132
132
  autotask_tenant_status: 'parts [identity, version, thresholds, server, time] picks which of resources.whoAmI, version.get, threshold_information.get run, plus zero-wire server and time parts (default all); identity also returns impersonationResourceId; none takes args',
133
133
  autotask_contact_full_profile: 'takes only id (+ ticket_limit), no parentId: the tool resolves the contact by id alone',
134
134
  autotask_invoice_get: 'format selects the key: record -> invoices.get, html -> invoices.markupHtml, xml -> invoices.markupXml, pdf -> invoices.pdf; output_path is tool-only (writes the export to a file)',
@@ -699,38 +699,42 @@ export function buildTenantStatus(ctx) {
699
699
  // whoAmI is the API user; the resource entries are logged as is the impersonation id (null: none). Zero wire, so present even when identity degrades.
700
700
  if (parts.includes('identity'))
701
701
  data.impersonationResourceId = ctx.poolConfig?.impersonationResourceId ?? null;
702
- for (const part of parts) {
703
- // Zero wire: this package's version (the same constant as serverInfo and /metadata), kept apart from the vendor `version` part.
702
+ // The SDK limiter bounds wire concurrency. Drain every part before answering so a
703
+ // late failure cannot outlive this request, and assemble only in requested order.
704
+ const settled = await Promise.allSettled(parts.map(async (part) => {
704
705
  if (part === 'server') {
705
- data.server = { name: SERVER_NAME, version: SERVER_VERSION, sdkVersion: SDK_VERSION, profile: ctx.config.AUTOTASK_PROFILE, ticketNoteVerificationProjection: TICKET_NOTE_VERIFICATION_PROJECTION, readRuntime: readRuntimeProof(ctx.client) };
706
- continue;
707
- }
708
- // Zero wire: the users' zone (AUTOTASK_USER_TIMEZONE) and its clock (#171), so a client need not guess today's date or zone.
709
- if (part === 'time') {
710
- data.time = zoneClock(ctx.config.AUTOTASK_USER_TIMEZONE);
711
- continue;
706
+ return { value: { name: SERVER_NAME, version: SERVER_VERSION, sdkVersion: SDK_VERSION, profile: ctx.config.AUTOTASK_PROFILE, ticketNoteVerificationProjection: TICKET_NOTE_VERIFICATION_PROJECTION, readRuntime: readRuntimeProof(ctx.client) } };
712
707
  }
708
+ if (part === 'time')
709
+ return { value: zoneClock(ctx.config.AUTOTASK_USER_TIMEZONE) };
713
710
  const op = STATUS_OPS[part];
714
- try {
715
- const value = await ctx.ops.invokeRead(ctx.client, op, [], undefined, signal);
716
- if (value === undefined)
717
- return abortedAnswer(ctx.correlationId);
718
- const model = markResult(value, ctx.untrustedFields(op));
719
- if (part !== 'thresholds') {
720
- data[part] = model;
721
- continue;
722
- }
723
- // The TENANT-wide vendor count (model) and the LOCAL per-credential window (budget,
724
- // zero wire): two numbers in different scopes.
725
- const budget = await ctx.ops.hourlyBudget(ctx.client);
726
- data.thresholds = budget === undefined ? { model, budget: null, budgetNote: 'No local hourly budget on this client (its rate limiting is off).' } : { model, budget };
727
- }
728
- catch (err) {
729
- // A credential refusal fails the call (every part would fail the same way).
730
- const payload = typedErrorPayload(err, ctx.correlationId, requestSecrets(ctx));
731
- if (payload.code === 'UNAUTHORIZED')
732
- throw err;
733
- firstError ??= err;
711
+ const value = await ctx.ops.invokeRead(ctx.client, op, [], undefined, signal);
712
+ if (value === undefined)
713
+ return { aborted: true };
714
+ const model = markResult(value, ctx.untrustedFields(op));
715
+ if (part !== 'thresholds')
716
+ return { value: model };
717
+ // The tenant-wide vendor count and local per-credential budget have different scopes.
718
+ const budget = await ctx.ops.hourlyBudget(ctx.client);
719
+ return { value: budget === undefined ? { model, budget: null, budgetNote: 'No local hourly budget on this client (its rate limiting is off).' } : { model, budget } };
720
+ }));
721
+ // A credential refusal fails the whole call, including when a sibling was cancelled.
722
+ for (const result of settled) {
723
+ if (result.status === 'rejected' && typedErrorPayload(result.reason, ctx.correlationId, requestSecrets(ctx)).code === 'UNAUTHORIZED')
724
+ throw result.reason;
725
+ }
726
+ // The SDK throws ABORTED; the mock seam can return undefined. Neither is a part miss.
727
+ if (signal?.aborted === true || settled.some((result) => result.status === 'fulfilled'
728
+ ? result.value.aborted === true
729
+ : result.reason?.code === 'ABORTED'))
730
+ return abortedAnswer(ctx.correlationId);
731
+ for (const [index, part] of parts.entries()) {
732
+ const result = settled[index];
733
+ if (result.status === 'fulfilled')
734
+ data[part] = result.value.value;
735
+ else {
736
+ const payload = typedErrorPayload(result.reason, ctx.correlationId, requestSecrets(ctx));
737
+ firstError ??= result.reason;
734
738
  data[part] = { value: null, absent: String(payload.code) };
735
739
  }
736
740
  }
@@ -18,4 +18,9 @@ export interface RankOptions {
18
18
  /** Multi-term questions (#277): coverage counts squared and a document matching under half the words is dropped. */
19
19
  strict?: boolean;
20
20
  }
21
+ export interface Bm25Index {
22
+ rank(query: string, opts?: RankOptions): number[];
23
+ }
24
+ /** Compile immutable document metadata once; query terms and boosts remain per invocation. */
25
+ export declare function compileBm25(docs: readonly string[]): Bm25Index;
21
26
  export declare function bm25Rank(docs: readonly string[], query: string, opts?: RankOptions): number[];
@@ -22,36 +22,54 @@ function stem(token) {
22
22
  return token.slice(0, -1);
23
23
  return token;
24
24
  }
25
- export function bm25Rank(docs, query, opts = {}) {
26
- const terms = [...new Set(tokenize(query))];
25
+ /** Compile immutable document metadata once; query terms and boosts remain per invocation. */
26
+ export function compileBm25(docs) {
27
27
  const toks = docs.map(tokenize);
28
28
  const avg = toks.reduce((n, t) => n + t.length, 0) / Math.max(toks.length, 1);
29
29
  const df = new Map();
30
30
  for (const t of toks)
31
31
  for (const term of new Set(t))
32
32
  df.set(term, (df.get(term) ?? 0) + 1);
33
- const scored = toks.map((t, i) => {
34
- let score = 0;
35
- let matched = 0;
36
- for (const term of terms) {
37
- const tf = t.filter((x) => x === term).length;
38
- if (tf === 0)
39
- continue;
40
- matched++;
33
+ const weights = toks.map((t) => {
34
+ const counts = new Map();
35
+ for (const term of t)
36
+ counts.set(term, (counts.get(term) ?? 0) + 1);
37
+ const row = new Map();
38
+ for (const [term, tf] of counts) {
41
39
  const n = df.get(term) ?? 0;
42
40
  const idf = Math.log(1 + (toks.length - n + 0.5) / (n + 0.5));
43
- score += idf * ((tf * 2.2) / (tf + 1.2 * (0.25 + (0.75 * t.length) / avg)));
41
+ row.set(term, idf * ((tf * 2.2) / (tf + 1.2 * (0.25 + (0.75 * t.length) / avg))));
44
42
  }
45
- // Coordination: a document matching more of the query's words outranks one that repeats a
46
- // single common word (`month` in every `lastFullMonth` key, for instance).
47
- const coverage = matched / Math.max(terms.length, 1);
48
- if (opts.strict === true && matched * 2 < terms.length)
49
- return { i, score: 0 };
50
- return { i, score: score * coverage * (opts.strict === true ? coverage : 1) * (opts.boost?.(i) ?? 1) };
43
+ return row;
51
44
  });
52
- return scored
53
- .filter((s) => s.score > 0)
54
- .sort((a, b) => b.score - a.score || a.i - b.i)
55
- .map((s) => s.i);
45
+ const rank = (query, opts = {}) => {
46
+ const terms = [...new Set(tokenize(query))];
47
+ const scored = weights.map((row, i) => {
48
+ let score = 0;
49
+ let matched = 0;
50
+ for (const term of terms) {
51
+ const weight = row.get(term);
52
+ if (weight === undefined)
53
+ continue;
54
+ matched++;
55
+ score += weight;
56
+ }
57
+ // Coordination: a document matching more of the query's words outranks one that repeats a
58
+ // single common word (`month` in every `lastFullMonth` key, for instance).
59
+ const coverage = matched / Math.max(terms.length, 1);
60
+ if (opts.strict === true && matched * 2 < terms.length)
61
+ return { i, score: 0 };
62
+ return { i, score: score * coverage * (opts.strict === true ? coverage : 1) * (opts.boost?.(i) ?? 1) };
63
+ });
64
+ return scored
65
+ .filter((s) => s.score > 0)
66
+ .sort((a, b) => b.score - a.score || a.i - b.i)
67
+ .map((s) => s.i);
68
+ };
69
+ // Only the rank function escapes: caller mutations cannot alter the compiled token weights.
70
+ return Object.freeze({ rank });
71
+ }
72
+ export function bm25Rank(docs, query, opts = {}) {
73
+ return compileBm25(docs).rank(query, opts);
56
74
  }
57
75
  //# sourceMappingURL=rank.js.map
@@ -7,16 +7,17 @@
7
7
  * - typed exact (`resource`, `by: id_or_name`): `<resource>.resolve` — numeric id first, else the
8
8
  * resource's exact primary text field;
9
9
  * - typed natural key (`by: ticket_number | serial | email`): the matching `findBy*` lookup;
10
- * - companies contains (`resource: companies`, `match: contains`): the SDK company search (issue
11
- * #9, with the family block on request);
10
+ * - companies contains/fuzzy (`resource: companies`, `match: contains | fuzzy`): SDK-owned searches
11
+ * with the family block on request (#9, #398);
12
12
  * - staff (`resource: resources`): `operations.resolveStaff` owns matching, active/API-user
13
13
  * exclusions and tenant metadata; this tool presents its result;
14
14
  * - sweep (no `resource`): `resolveAny` (exact/auto) or `searchAcrossResources` (contains) over the
15
15
  * five workflow resources or `resources`.
16
16
  *
17
17
  * `match: auto` (the default, #225): exact first; on an exact miss companies, tickets (title) and a
18
- * sweep fall back to contains — one hit answers `ok` with `matched: "contains"`, several answer
19
- * `ambiguous`, none the typed miss. `match: exact` keeps the exact-only miss.
18
+ * sweep fall back to contains. One contains hit answers `ok` with `matched: "contains"`, several
19
+ * answer `ambiguous`. Explicit companies then fall back to fuzzy candidates (#398): always
20
+ * `ambiguous` on a hit; empty searches keep metadata and qualified retry/input guidance. `match: exact` keeps the exact-only miss.
20
21
  *
21
22
  * Records drop `[REDACTED]`, null and empty fields unless `expand: "full"` (#225).
22
23
  *
@@ -147,6 +148,10 @@ function resolveText(resource, identifier, record) {
147
148
  }
148
149
  /** Refuse the invalid argument combinations before any request (INPUT_INVALID, zero wire). */
149
150
  function validateCombination(a) {
151
+ if (a.match === 'fuzzy' && (a.resource !== 'companies' || a.by !== 'id_or_name'))
152
+ throw new InputInvalidError('resolve: match "fuzzy" needs resource "companies" and by "id_or_name"', 'match');
153
+ if (a.include_inactive && !(a.resource === 'companies' && a.by === 'id_or_name' && (a.match === 'auto' || a.match === 'fuzzy')))
154
+ throw new InputInvalidError('resolve: include_inactive applies to companies fuzzy candidates only (match "fuzzy" or "auto")', 'include_inactive');
150
155
  if (a.resource !== undefined && a.resources !== undefined)
151
156
  throw new InputInvalidError('resolve: resources is for a sweep only — omit it when resource is set', 'resources');
152
157
  // #172: by email on resources narrows the staff match to the email field.
@@ -169,10 +174,10 @@ function validateCombination(a) {
169
174
  if (a.include_api_users && a.resource !== 'resources')
170
175
  throw new InputInvalidError('resolve: include_api_users applies to resource "resources" only', 'include_api_users');
171
176
  if (a.include_family && !(a.match !== 'exact' && a.resource === 'companies')) {
172
- throw new InputInvalidError('resolve: include_family applies to resource "companies" with match "contains" or "auto" only', 'include_family');
177
+ throw new InputInvalidError('resolve: include_family applies to resource "companies" with match "contains", "fuzzy" or "auto" only', 'include_family');
173
178
  }
174
- if (a.match === 'contains' && a.resource === 'companies' && a.limit > COMPANY_CONTAINS_MAX_LIMIT) {
175
- throw new InputInvalidError(`resolve: limit ${a.limit} exceeds the companies contains cap of ${COMPANY_CONTAINS_MAX_LIMIT} — it may be lowered, never raised`, 'limit');
179
+ if ((a.match === 'contains' || a.match === 'fuzzy') && a.resource === 'companies' && a.limit > COMPANY_CONTAINS_MAX_LIMIT) {
180
+ throw new InputInvalidError(`resolve: limit ${a.limit} exceeds the companies search cap of ${COMPANY_CONTAINS_MAX_LIMIT} — it may be lowered, never raised`, 'limit');
176
181
  }
177
182
  }
178
183
  const STAFF_NOTES = {
@@ -219,6 +224,26 @@ export function buildResolve(ctx) {
219
224
  const found = await ctx.ops.invokeRead(ctx.client, 'tickets.search', [String(a.identifier), opts], undefined, signal);
220
225
  return found === undefined ? undefined : Array.isArray(found) ? found : [];
221
226
  };
227
+ /** Fuzzy rows are suggestions, including a single distance-zero hit; the caller always chooses. */
228
+ const searchFuzzy = async () => {
229
+ gate('companies.searchFuzzy');
230
+ const opts = { limit: Math.min(a.limit, COMPANY_CONTAINS_MAX_LIMIT), includeFamily: a.include_family, includeInactive: a.include_inactive };
231
+ const value = await ctx.ops.invokeRead(ctx.client, 'companies.searchFuzzy', [String(a.identifier), opts], undefined, signal);
232
+ if (value === undefined)
233
+ return abortedAnswer(ctx.correlationId);
234
+ const found = value;
235
+ const data = { resource: 'companies', ...how(a.match, 'fuzzy'), count: found.items.length, tier: found.tier, truncated: found.truncated, pieces: found.pieces, index: found.index };
236
+ if (found.items.length > 0) {
237
+ const candidates = found.items.map(({ record, distance, matchedTerms, coverage, source }) => ({ ref: refOf('companies', record), record: slimRecord(record, a.expand), distance, matchedTerms, coverage, source }));
238
+ const detail = `${found.items.length} fuzzy company candidate(s); choose one by id, even when distance is zero.${found.truncated ? ' Results capped; narrow the name if needed.' : ''}`;
239
+ return outcome('ambiguous', 'choose_candidate', { code: 'AMBIGUOUS_MATCH', detail, field: 'identifier' }, data, { candidates: markResult(candidates, [...ctx.untrustedFields('companies.searchFuzzy'), 'matchedTerms']), summary: detail });
240
+ }
241
+ const building = found.index.state === 'cold' || found.index.state === 'building';
242
+ const detail = `No fuzzy company candidates in this bounded search; this is not proof of absence. ${building ? 'The name index is not ready; retry after it builds, narrow the name or supply a known company id.' : 'Narrow the name or supply a known company id.'}${found.truncated ? ' Live results were capped.' : ''}`;
243
+ const result = outcome('needs_input', building ? 'retry' : 'supply_input', { code: found.truncated ? 'RESULT_TRUNCATED' : 'TARGET_NOT_FOUND', detail, field: 'identifier' }, data, { summary: detail });
244
+ result.structuredContent.retryable = building;
245
+ return result;
246
+ };
222
247
  // ---- sweep: no resource ----
223
248
  if (a.resource === undefined) {
224
249
  const resources = a.resources;
@@ -337,6 +362,8 @@ export function buildResolve(ctx) {
337
362
  matches: markResult(rows, fields),
338
363
  });
339
364
  }
365
+ if (a.match === 'fuzzy')
366
+ return searchFuzzy();
340
367
  // ---- companies contains (issue #9) ----
341
368
  if (a.match === 'contains') {
342
369
  const found = await searchContains(resource);
@@ -380,6 +407,8 @@ export function buildResolve(ctx) {
380
407
  const found = await searchContains(resource);
381
408
  if (found === undefined)
382
409
  return abortedAnswer(ctx.correlationId);
410
+ if (found.length === 0 && resource === 'companies')
411
+ return searchFuzzy();
383
412
  if (found.length === 0)
384
413
  throw new NotFoundError(`resolve: no visible ${RESOURCES[resource].noun} matches "${a.identifier}" — tried EXACT then contains`, { operation });
385
414
  if (found.length === 1) {
@@ -112,20 +112,29 @@ export function documentCore(value) {
112
112
  * server recorded by provenance ({@link markResult}, {@link markServerField}).
113
113
  */
114
114
  export function sanitiseVendorOutput(value, opts = {}, kind, depth = 0) {
115
- const cap = opts.cap !== false;
115
+ return sanitise(value, opts, kind, depth);
116
+ }
117
+ function observeText(text, caps) {
118
+ if (caps !== undefined && !caps.found && text.includes(TRUNCATION_MARKER))
119
+ caps.found = true;
120
+ }
121
+ function sanitiseText(value, cap, kind) {
122
+ if (kind === 'server' || (kind === 'binary' && !NOT_BASE64.test(value)))
123
+ return value;
124
+ const inner = outerUnwrap(value);
125
+ const text = inner ?? value;
126
+ if (kind === 'document')
127
+ return wrapOrSelf(cleanUntrustedText(text, false));
128
+ if (kind === 'cursor' && inner === undefined)
129
+ return cleanUntrustedText(text, cap, CURSOR_CAP);
130
+ const clean = cleanUntrustedText(text, cap);
131
+ return kind === 'wrap' || inner !== undefined ? wrapOrSelf(clean) : clean;
132
+ }
133
+ function sanitise(value, opts, kind, depth, caps) {
116
134
  if (typeof value === 'string') {
117
- if (kind === 'server')
118
- return value;
119
- if (kind === 'binary' && !NOT_BASE64.test(value))
120
- return value;
121
- const inner = outerUnwrap(value);
122
- const text = inner ?? value;
123
- if (kind === 'document')
124
- return wrapOrSelf(cleanUntrustedText(text, false));
125
- if (kind === 'cursor' && inner === undefined)
126
- return cleanUntrustedText(text, cap, CURSOR_CAP);
127
- const clean = cleanUntrustedText(text, cap);
128
- return kind === 'wrap' || inner !== undefined ? wrapOrSelf(clean) : clean;
135
+ const clean = sanitiseText(value, opts.cap !== false, kind);
136
+ observeText(clean, caps);
137
+ return clean;
129
138
  }
130
139
  if (value === null || typeof value !== 'object')
131
140
  return value;
@@ -134,7 +143,7 @@ export function sanitiseVendorOutput(value, opts = {}, kind, depth = 0) {
134
143
  const fields = PROVENANCE.get(value);
135
144
  if (Array.isArray(value)) {
136
145
  const items = fields?.get(EVERY_ITEM) ?? (kind === 'wrap' ? 'wrap' : undefined);
137
- return value.map((v) => sanitiseVendorOutput(v, opts, items, depth + 1));
146
+ return value.map((v) => sanitise(v, opts, items, depth + 1, caps));
138
147
  }
139
148
  // Keys (sanitiser review S6): every key is cleaned; a key that is already clean is placed first
140
149
  // and keeps its provenance, so a look-alike key (`ti` + U+200B + `tle`) can never take a stamped
@@ -147,7 +156,12 @@ export function sanitiseVendorOutput(value, opts = {}, kind, depth = 0) {
147
156
  let key = clean;
148
157
  for (let n = 1; Object.prototype.hasOwnProperty.call(out, key); n++)
149
158
  key = `${clean}~${n}`;
150
- put(key, sanitiseVendorOutput(v, opts, k === clean ? fields?.get(k) : undefined, depth + 1));
159
+ const child = sanitise(v, opts, k === clean ? fields?.get(k) : undefined, depth + 1, caps);
160
+ // JSON omits object properties carrying undefined/functions/symbols: their keys never
161
+ // contributed to the previous serialized-data check either.
162
+ if (child !== undefined && typeof child !== 'function' && typeof child !== 'symbol')
163
+ observeText(key, caps);
164
+ put(key, child);
151
165
  }
152
166
  return out;
153
167
  }
@@ -170,7 +184,8 @@ export function cleanProse(text, cap = true) {
170
184
  */
171
185
  export function sanitiseToolReturn(result, serverCorrelationId = '') {
172
186
  const env = result.structuredContent;
173
- env.data = sanitiseVendorOutput(env.data);
187
+ const caps = env.textCapped === undefined ? { found: false } : undefined;
188
+ env.data = sanitise(env.data, {}, undefined, 0, caps);
174
189
  if (typeof env.summary === 'string')
175
190
  env.summary = cleanProse(env.summary);
176
191
  if (env.candidates !== undefined)
@@ -179,7 +194,7 @@ export function sanitiseToolReturn(result, serverCorrelationId = '') {
179
194
  env.reasons = env.reasons.map((r) => ({ ...r, detail: cleanProse(r.detail), ...(r.field !== undefined ? { field: cleanProse(r.field, false).slice(0, 200) } : {}) }));
180
195
  if (env.status !== 'ok' && !CORRELATION_ID.test(env.correlationId ?? ''))
181
196
  env.correlationId = serverCorrelationId;
182
- if (env.textCapped === undefined && JSON.stringify(env.data ?? null).includes(TRUNCATION_MARKER))
197
+ if (caps?.found === true)
183
198
  env.textCapped = true;
184
199
  const first = result.content[0];
185
200
  if (first !== undefined)
@@ -257,10 +257,12 @@ export declare const RESOLVE_INPUT: z.ZodObject<{
257
257
  exact: "exact";
258
258
  auto: "auto";
259
259
  contains: "contains";
260
+ fuzzy: "fuzzy";
260
261
  }>>;
261
262
  company_id: z.ZodOptional<z.ZodNumber>;
262
263
  expand: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodLiteral<"full">]>>;
263
264
  include_family: z.ZodDefault<z.ZodBoolean>;
265
+ include_inactive: z.ZodDefault<z.ZodBoolean>;
264
266
  include_api_users: z.ZodDefault<z.ZodBoolean>;
265
267
  limit: z.ZodDefault<z.ZodNumber>;
266
268
  }, z.core.$strip>;
@@ -463,6 +465,10 @@ export declare const WRITE_INPUT: z.ZodObject<{
463
465
  export declare const PLAN_HANDLE: RegExp;
464
466
  export declare const APPLY_INPUT: z.ZodObject<{
465
467
  plan: z.ZodString;
468
+ readBack: z.ZodOptional<z.ZodEnum<{
469
+ record: "record";
470
+ time_entry_verification_v1: "time_entry_verification_v1";
471
+ }>>;
466
472
  operation: z.ZodString;
467
473
  targets: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
468
474
  summary: z.ZodString;
@@ -474,6 +480,10 @@ export declare const APPLY_INPUT: z.ZodObject<{
474
480
  */
475
481
  export declare const APPLY_PARSE: z.ZodObject<{
476
482
  plan: z.ZodString;
483
+ readBack: z.ZodOptional<z.ZodEnum<{
484
+ record: "record";
485
+ time_entry_verification_v1: "time_entry_verification_v1";
486
+ }>>;
477
487
  operation: z.ZodOptional<z.ZodUnknown>;
478
488
  targets: z.ZodOptional<z.ZodUnknown>;
479
489
  summary: z.ZodOptional<z.ZodUnknown>;
@@ -242,16 +242,17 @@ export const READ_INPUT = z.object({
242
242
  expectedReadRuntime: z.string().regex(/^[a-f0-9]{64}$/).optional().describe('Require server.readRuntime.sha256 from autotask_tenant_status; changed or unavailable runtime refuses before any vendor dispatch.'),
243
243
  }).transform(v => v.projection === 'billing_review_entry_v1' ? v : numericQueryBag(v));
244
244
  export const RESOLVE_INPUT = z.object({
245
- identifier: z.union([z.number().int().nonnegative(), z.string().min(1).max(200)]).describe('Numeric id, name, ticket number, serial or email. resources: numeric identifiers are looked up as Resource ids.'),
246
- resource: RESOLVE_RESOURCE.optional().describe('Resource to resolve in; omit to sweep several. resources = staff by email, user name or name: active only, API users excluded.'),
245
+ identifier: z.union([z.number().int().nonnegative(), z.string().min(1).max(200)]).describe('Id/name, ticket number, serial, email. resources: numeric = id.'),
246
+ resource: RESOLVE_RESOURCE.optional().describe('Omit to sweep. resources: staff by email/user name/name; active, API users excluded.'),
247
247
  resources: z.array(WF).min(1).optional().describe('Sweep only: resources to try (default all five).'),
248
- by: z.enum(['id_or_name', 'ticket_number', 'serial', 'email']).default('id_or_name').describe('Identifier kind; non-default needs resource (resources: email only).'),
249
- match: z.enum(['auto', 'exact', 'contains']).default('auto').describe('auto: exact, then contains on a miss; contains: companies, tickets (title), sweep.'),
250
- company_id: z.number().int().positive().optional().describe('tickets, contains or auto: scope the title search to one company id.'),
251
- expand: z.union([z.boolean(), z.literal('full')]).default(false).describe('Record not summary; true drops empty fields, "full" keeps all.'),
248
+ by: z.enum(['id_or_name', 'ticket_number', 'serial', 'email']).default('id_or_name').describe('Kind; non-default needs resource (resources: email only).'),
249
+ match: z.enum(['auto', 'exact', 'contains', 'fuzzy']).default('auto').describe('auto: exact, contains, then fuzzy for companies. fuzzy: companies + id_or_name, always candidates. contains: companies/tickets title/sweep.'),
250
+ company_id: z.number().int().positive().optional().describe('tickets contains/auto: scope title search by company.'),
251
+ expand: z.union([z.boolean(), z.literal('full')]).default(false).describe('true: record, drop empty fields; "full": keep all.'),
252
252
  include_family: z.boolean().default(false).describe('Companies: parent and child ids per match.'),
253
- include_api_users: z.boolean().default(false).describe('resource resources only: also match API users (default excluded).'),
254
- limit: z.number().int().min(1).max(50).default(10).describe('Total matches; companies and resources also have an SDK cap.'),
253
+ include_inactive: z.boolean().default(false).describe('Companies fuzzy/auto: inactive fuzzy candidates too (default false). Exact/contains unchanged.'),
254
+ include_api_users: z.boolean().default(false).describe('resources only: include API users (default excluded).'),
255
+ limit: z.number().int().min(1).max(50).default(10).describe('Matches; companies/staff cap 10.'),
255
256
  });
256
257
  export const QUERY_INPUT = z.object({
257
258
  resource: z
@@ -434,6 +435,7 @@ export const WRITE_INPUT = z.object({
434
435
  export const PLAN_HANDLE = /^pln_[a-z2-7]{26}$/;
435
436
  export const APPLY_INPUT = z.object({
436
437
  plan: z.string().regex(PLAN_HANDLE, 'expected a plan handle from autotask_write (pln_...)').describe('The plan handle autotask_write returned.'),
438
+ readBack: z.enum(['record', 'time_entry_verification_v1']).optional().describe('record (default): stored record. time_entry_verification_v1: fresh time_entries.create verification metadata in data.record, with note hashes instead of note bodies. Replays return the recorded outcome without a read-back.'),
437
439
  // #301: the preview's `approval`, copied verbatim; each must equal the stored plan (PLAN_MISMATCH otherwise)
438
440
  operation: z.string().describe('approval.operation from the preview, verbatim.'),
439
441
  targets: z.record(z.string(), z.union([z.string(), z.number()])).describe('approval.targets from the preview, verbatim.'),
@@ -4,6 +4,7 @@
4
4
  * the ones that do; the transport decides who approves (stdio: this server, HTTP: the client or gateway).
5
5
  */
6
6
  import { APPLY_INPUT, APPLY_PARSE, closedInput } from '../schemas.js';
7
+ import { projectTimeEntryVerification } from '../time-entry-verification.js';
7
8
  import { writeDeps } from './common.js';
8
9
  import { impersonatedContext, validateImpersonation } from './impersonation.js';
9
10
  import { releaseClientOnError } from '../context/derive.js';
@@ -11,7 +12,7 @@ import { gateApply } from '../../access/gate.js';
11
12
  import { classifyWriteOutcome, MoveRefusedError } from 'node-autotask';
12
13
  import { notPersistedFields } from 'node-autotask/operations';
13
14
  import { stripUntrustedDeep } from 'node-autotask/untrusted';
14
- import { requestSecrets, readOneItem } from '../dispatch.js';
15
+ import { InputInvalidError, requestSecrets, readOneItem } from '../dispatch.js';
15
16
  import { abortedResult, typedErrorPayload } from '../results/errors.js';
16
17
  import {} from '../results/envelope.js';
17
18
  import { ConfigError } from '../../config/schema.js';
@@ -381,7 +382,14 @@ async function respond(a, r) {
381
382
  // A create reads its stored record back (one governed get); a failed read-back never fails the write.
382
383
  if (shape.startsWith('create') && entry.outcome?.id !== undefined) {
383
384
  try {
384
- const back = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, entry.outcome.id), undefined);
385
+ const id = entry.outcome.id;
386
+ let projectRaw;
387
+ if (a.readBack === 'time_entry_verification_v1') {
388
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id <= 0)
389
+ throw new InputInvalidError('time entry verification requires a positive numeric created id', 'readBack');
390
+ projectRaw = (result) => projectTimeEntryVerification(result, id);
391
+ }
392
+ const back = await readOneItem(ctx, `${record.resource}.get`, getIds(ctx, record.resource, plan.targets.parentId, id), undefined, { fresh: true }, projectRaw);
385
393
  return outcomeAnswer(plan, entry, { replayed: false, data: { record: back.result ?? null } });
386
394
  }
387
395
  catch (err) {
@@ -455,7 +463,8 @@ export function buildApply(ctx, destructive = false) {
455
463
  if ('content' in admitted)
456
464
  return admitted;
457
465
  const effective = impersonatedContext(ctx, admitted.impersonationResourceId);
458
- const a = { ...first, ctx: effective, plan: admitted };
466
+ const readBack = raw.readBack ?? 'record';
467
+ const a = { ...first, ctx: effective, plan: admitted, readBack };
459
468
  const plan = a.plan;
460
469
  const mismatch = echoAnswer(a, raw);
461
470
  if (mismatch !== undefined)
@@ -464,6 +473,9 @@ export function buildApply(ctx, destructive = false) {
464
473
  if (applyToolFor(plan) !== tool) {
465
474
  return refused('denied', 'supply_input', reason('PLAN_MISMATCH', `this plan ${plan.decision === 'gate' ? 'hits a hard rule' : 'hits no hard rule'}: apply it with ${applyToolFor(plan)}; nothing was sent`), plan);
466
475
  }
476
+ if (readBack === 'time_entry_verification_v1' && plan.op !== 'time_entries.create') {
477
+ return refused('error', 'supply_input', reason('INPUT_INVALID', 'readBack time_entry_verification_v1 requires time_entries.create', 'readBack'), plan);
478
+ }
467
479
  // Who approves (#302). HTTP: the client or gateway did, so the server never asks. stdio: the
468
480
  // mode decides; a person's answer runs over the LOADED plan and OUTSIDE the apply lock (it must
469
481
  // never hold it). A ledger hit that ends the apply (a replay) answers in execute() without asking;
@@ -0,0 +1,4 @@
1
+ /** Drain independent reads before returning or releasing their shared client, including on error. */
2
+ export declare function drainReads<T extends readonly unknown[]>(reads: {
3
+ [K in keyof T]: Promise<T[K]>;
4
+ }): Promise<T>;
@@ -0,0 +1,9 @@
1
+ /** Drain independent reads before returning or releasing their shared client, including on error. */
2
+ export async function drainReads(reads) {
3
+ const results = await Promise.allSettled(reads);
4
+ for (const result of results)
5
+ if (result.status === 'rejected')
6
+ throw result.reason;
7
+ return results.map((result) => result.value);
8
+ }
9
+ //# sourceMappingURL=concurrent.js.map
@@ -13,6 +13,7 @@ import { PLAN_TTL_MS } from '../../write/store.js';
13
13
  import { Cancelled, writeDeps, tenantIdentity, answer, reason } from './common.js';
14
14
  import { parseArgs } from './parse.js';
15
15
  import { honestImpact } from './payload.js';
16
+ import { drainReads } from './concurrent.js';
16
17
  import { takeSnapshot, moveSummary, parentOf } from './snapshot.js';
17
18
  import { catalogFindings, pairFindings } from './checks.js';
18
19
  import { unresolvedReason, markedDiff, deriveFacts } from './facts.js';
@@ -271,8 +272,9 @@ async function execute(ctx, args, signal, ownerTenantId) {
271
272
  if (identityRefusal !== undefined)
272
273
  return identityRefusal;
273
274
  let snap;
275
+ let resource;
274
276
  try {
275
- snap = await takeSnapshot(ctx, record, parsed, dedupFor(loaded, op), signal);
277
+ [snap, resource] = await drainReads([takeSnapshot(ctx, record, parsed, dedupFor(loaded, op), signal), entryResource(r, a)]);
276
278
  }
277
279
  catch (err) {
278
280
  if (err instanceof Cancelled)
@@ -326,7 +328,7 @@ async function execute(ctx, args, signal, ownerTenantId) {
326
328
  return abortedResult();
327
329
  const udf = shape === 'create' || shape === 'create_child' ? udfPreviewWarning(UDF_CAPABLE.has(record.resource), parsed.data, 'create') : shape === 'update' || shape === 'update_child' ? udfPreviewWarning(UDF_CAPABLE.has(record.resource), parsed.data, 'update') : undefined;
328
330
  const dried = { ...dry, warnings: [...(udf === undefined ? [] : [udf]), ...checked.warn, ...(loc === undefined ? [] : [loc]), ...(dry.warnings ?? [])] };
329
- return persist(r, a, evaluatePreview(r, a, snap, dried, await entryResource(r, a), checked.types));
331
+ return persist(r, a, evaluatePreview(r, a, snap, dried, resource, checked.types));
330
332
  }
331
333
  export function buildWrite(ctx) {
332
334
  return { title: 'Preview an Autotask write (changes nothing)', input: closedInput(WRITE_INPUT), run: async (raw, signal) => {
@@ -4,6 +4,7 @@ import { writeShape } from '../../write/hard-rules.js';
4
4
  import { Cancelled, reason, isNotFound } from './common.js';
5
5
  import { CALL_COMPANY_ARGS, CALL_ID_ARGS, asIdOrZero } from './parse.js';
6
6
  import { ci } from './payload.js';
7
+ import { drainReads } from './concurrent.js';
7
8
  // ---------------------------------------------------------------------------
8
9
  // The snapshot: fresh reads, the companies the write touches, the duplicate query
9
10
  // ---------------------------------------------------------------------------
@@ -64,16 +65,25 @@ function createReader(ctx, targetKey, signal) {
64
65
  // a record that is only REFERENCED (the ticket a time entry is logged on) is hashed by its stable
65
66
  // facts only, so a volatile stamp the first of two outstanding writes moves (lastActivityDate,
66
67
  // modified stamps) does not read as drift for the second (issue #108).
68
+ // Only this snapshot owns these promises; nothing survives into another preview or apply.
69
+ const pending = new Map();
67
70
  const get = async (resource, ids) => {
68
71
  const key = `${resource}:${ids.join('/')}`;
69
- if (!(key in reads)) {
70
- const v = await ctx.ops.invokeRead(ctx.client, `${resource}.get`, ids, { fresh: true }, signal); // per-call fresh: a snapshot never rests on a cached row
71
- if (v === undefined)
72
- throw new Cancelled();
73
- reads[key] = v;
74
- hashed[key] = key === targetKey ? v : stableFacts(v);
72
+ if (key in reads)
73
+ return reads[key];
74
+ let request = pending.get(key);
75
+ if (request === undefined) {
76
+ request = (async () => {
77
+ const v = await ctx.ops.invokeRead(ctx.client, `${resource}.get`, ids, { fresh: true }, signal);
78
+ if (v === undefined)
79
+ throw new Cancelled();
80
+ reads[key] = v;
81
+ hashed[key] = key === targetKey ? v : stableFacts(v);
82
+ return v;
83
+ })();
84
+ pending.set(key, request);
75
85
  }
76
- return reads[key];
86
+ return request;
77
87
  };
78
88
  // The positional ids for one reference's get; a parent-scoped get needs the parent id from the same record.
79
89
  const idsFor = async (resource, id, rec) => {
@@ -104,26 +114,32 @@ function createReader(ctx, targetKey, signal) {
104
114
  unresolved.push(`${resource}.companyID`);
105
115
  const parent = await parentOf(resource);
106
116
  const refs = [...(parent === undefined ? [] : [[parent.field, parent.resource]]), ...ANCHORS.filter(([f]) => f !== parent?.field)];
107
- for (const [field, res] of refs) {
117
+ // Fetch siblings together, then walk their descendants in the original order. This keeps
118
+ // unresolved-reference diagnostics deterministic and shares reads reached by several paths.
119
+ const children = await drainReads(refs.map(async ([field, res]) => {
108
120
  const v = ci(rec, field);
109
121
  if (v === undefined || v === null)
110
- continue;
122
+ return undefined;
111
123
  const ids = isRefId(v, res) && depth < 3 ? await idsFor(res, v, rec) : undefined;
112
- if (ids === undefined) {
113
- unresolved.push(`${resource}.${field}`);
114
- continue;
115
- }
116
- let child;
124
+ if (ids === undefined)
125
+ return null;
117
126
  try {
118
- child = await get(res, ids);
127
+ return await get(res, ids);
119
128
  }
120
129
  catch (err) {
121
130
  if (!isNotFound(err))
122
131
  throw err;
123
- unresolved.push(`${resource}.${field}`);
124
- continue;
132
+ return null;
125
133
  }
126
- await anchor(res, child, depth + 1, false);
134
+ }));
135
+ for (const [i, [field, res]] of refs.entries()) {
136
+ const child = children[i];
137
+ if (child === undefined)
138
+ continue;
139
+ if (child === null)
140
+ unresolved.push(`${resource}.${field}`);
141
+ else
142
+ await anchor(res, child, depth + 1, false);
127
143
  }
128
144
  };
129
145
  return { reads, hashed, companies, unresolved, get, idsFor, anchor };
@@ -242,88 +258,97 @@ export async function takeSnapshot(ctx, record, parsed, duplicateFields, signal)
242
258
  const r = createReader(ctx, targetKey, signal);
243
259
  const { get, idsFor, anchor, reads, hashed, unresolved, companies } = r;
244
260
  const { targets, data } = parsed;
245
- let current;
246
- if (targets.id !== undefined) {
247
- if (targets.toId !== undefined && !hasSimpleGet(record.resource, ctx)) {
248
- // a move's source whose get is parent-scoped (a ticket charge): read it by id, as the SDK does; its ticketID anchors it
249
- const key = `${record.resource}:${targets.id}`;
250
- const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter: [{ field: 'id', op: 'eq', value: targets.id }], limit: 1 }], undefined, signal);
251
- if (found === undefined)
252
- throw new Cancelled();
253
- const row = (found.items ?? [])[0];
254
- if (row === null || typeof row !== 'object')
255
- return reason('INPUT_INVALID', `${record.resource} ${targets.id} does not exist`, 'args.0');
256
- reads[key] = row;
257
- hashed[key] = row;
258
- current = row;
259
- }
260
- else {
261
- try {
262
- current = await get(record.resource, getIds(ctx, record.resource, targets.parentId, targets.id));
261
+ if (duplicateFields !== undefined && data !== undefined) {
262
+ const missing = duplicateFields.filter((f) => ci(data, f) === undefined || ci(data, f) === null);
263
+ if (missing.length > 0)
264
+ return reason('INPUT_MISSING', `AUTOTASK_DEDUP needs data.${missing.join(', data.')}`, `data.${missing[0]}`);
265
+ }
266
+ const references = async () => {
267
+ let current;
268
+ if (targets.id !== undefined) {
269
+ if (targets.toId !== undefined && !hasSimpleGet(record.resource, ctx)) {
270
+ // a move's source whose get is parent-scoped (a ticket charge): read it by id, as the SDK does; its ticketID anchors it
271
+ const key = `${record.resource}:${targets.id}`;
272
+ const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter: [{ field: 'id', op: 'eq', value: targets.id }], limit: 1 }], undefined, signal);
273
+ if (found === undefined)
274
+ throw new Cancelled();
275
+ const row = (found.items ?? [])[0];
276
+ if (row === null || typeof row !== 'object')
277
+ return reason('INPUT_INVALID', `${record.resource} ${targets.id} does not exist`, 'args.0');
278
+ reads[key] = row;
279
+ hashed[key] = row;
280
+ current = row;
263
281
  }
264
- catch (err) {
265
- if (targets.toId === undefined || !isNotFound(err))
266
- throw err;
267
- return reason('INPUT_INVALID', `${record.resource} ${targets.id} does not exist`, 'args.0');
282
+ else {
283
+ try {
284
+ current = await get(record.resource, getIds(ctx, record.resource, targets.parentId, targets.id));
285
+ }
286
+ catch (err) {
287
+ if (targets.toId === undefined || !isNotFound(err))
288
+ throw err;
289
+ return reason('INPUT_INVALID', `${record.resource} ${targets.id} does not exist`, 'args.0');
290
+ }
268
291
  }
292
+ await anchor(record.resource, current, 0, false);
269
293
  }
270
- await anchor(record.resource, current, 0, false);
271
- }
272
- if (targets.toId !== undefined) {
273
- // the TARGET ticket is a scope fact of its own (its company joins the union), read live
274
- try {
275
- await anchor('tickets', await get('tickets', [targets.toId]), 1, false);
276
- }
277
- catch (err) {
278
- if (!isNotFound(err))
279
- throw err;
280
- unresolved.push('tickets.toTicketId');
281
- }
282
- }
283
- if (data !== undefined) {
284
- // The payload's references: a create's would-be record, or what an update moves the record to.
285
- // `id` in a payload is never a scope fact (the payload flag).
286
- await anchor(record.resource, data, 0, true);
287
- }
288
- if (targets.parentId !== undefined) {
289
- // The parent the caller names is a scope fact of its own, read live, whatever the payload says.
290
- const parent = await parentOf(record.resource);
291
- const ids = parent === undefined || !isRefId(targets.parentId, parent.resource) ? undefined : await idsFor(parent.resource, targets.parentId, data ?? current ?? {});
292
- if (parent === undefined || ids === undefined)
293
- unresolved.push(`${record.resource}.parent`);
294
- else {
294
+ if (targets.toId !== undefined) {
295
+ // the TARGET ticket is a scope fact of its own (its company joins the union), read live
295
296
  try {
296
- await anchor(parent.resource, await get(parent.resource, ids), 1, false);
297
+ await anchor('tickets', await get('tickets', [targets.toId]), 1, false);
297
298
  }
298
299
  catch (err) {
299
300
  if (!isNotFound(err))
300
301
  throw err;
301
- unresolved.push(`${record.resource}.${parent.field}`);
302
+ unresolved.push('tickets.toTicketId');
302
303
  }
303
304
  }
304
- }
305
- let duplicates = 0;
306
- let duplicateIds = [];
307
- if (duplicateFields !== undefined && data !== undefined) {
308
- const missing = duplicateFields.filter((f) => ci(data, f) === undefined || ci(data, f) === null);
309
- if (missing.length > 0)
310
- return reason('INPUT_MISSING', `AUTOTASK_DEDUP needs data.${missing.join(', data.')}`, `data.${missing[0]}`);
311
- const filter = duplicateFields.flatMap((field) => duplicateFilter(field, ci(data, field)));
312
- const parent = targets.parentId === undefined ? undefined : await parentOf(record.resource);
313
- if (parent !== undefined)
314
- filter.push({ field: parent.field, op: 'eq', value: targets.parentId });
315
- const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter, limit: 5 }], undefined, signal);
316
- if (found === undefined)
317
- throw new Cancelled();
318
- const items = found.items ?? [];
319
- duplicates = items.length;
320
- duplicateIds = items.map((i) => i.id);
321
- }
305
+ if (data !== undefined) {
306
+ // The payload's references: a create's would-be record, or what an update moves the record to.
307
+ // `id` in a payload is never a scope fact (the payload flag).
308
+ await anchor(record.resource, data, 0, true);
309
+ }
310
+ if (targets.parentId !== undefined) {
311
+ // The parent the caller names is a scope fact of its own, read live, whatever the payload says.
312
+ const parent = await parentOf(record.resource);
313
+ const ids = parent === undefined || !isRefId(targets.parentId, parent.resource) ? undefined : await idsFor(parent.resource, targets.parentId, data ?? current ?? {});
314
+ if (parent === undefined || ids === undefined)
315
+ unresolved.push(`${record.resource}.parent`);
316
+ else {
317
+ try {
318
+ await anchor(parent.resource, await get(parent.resource, ids), 1, false);
319
+ }
320
+ catch (err) {
321
+ if (!isNotFound(err))
322
+ throw err;
323
+ unresolved.push(`${record.resource}.${parent.field}`);
324
+ }
325
+ }
326
+ }
327
+ return { current };
328
+ };
329
+ const duplicates = async () => {
330
+ if (duplicateFields !== undefined && data !== undefined) {
331
+ const filter = duplicateFields.flatMap((field) => duplicateFilter(field, ci(data, field)));
332
+ const parent = targets.parentId === undefined ? undefined : await parentOf(record.resource);
333
+ if (parent !== undefined)
334
+ filter.push({ field: parent.field, op: 'eq', value: targets.parentId });
335
+ const found = await ctx.ops.invokeRead(ctx.client, `${record.resource}.query`, [{ filter, limit: 5 }], undefined, signal);
336
+ if (found === undefined)
337
+ throw new Cancelled();
338
+ const items = found.items ?? [];
339
+ return items.map((i) => i.id);
340
+ }
341
+ return [];
342
+ };
343
+ const [referenceResult, duplicateIds] = await drainReads([references(), duplicates()]);
344
+ if ('code' in referenceResult)
345
+ return referenceResult;
346
+ const { current } = referenceResult;
322
347
  return {
323
348
  companyIds: [...companies].sort((a, b) => a - b),
324
349
  unresolved: [...new Set(unresolved)],
325
350
  ...(current !== undefined ? { current } : {}),
326
- duplicates,
351
+ duplicates: duplicateIds.length,
327
352
  inputs: { reads: hashed, duplicateIds },
328
353
  };
329
354
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.61.1",
3
+ "version": "0.62.0",
4
4
  "description": "MCP server for the Autotask (Datto) PSA domain, built on the node-autotask SDK",
5
5
  "license": "MIT",
6
6
  "author": "Max Soukhomlinov",
@@ -54,7 +54,7 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@modelcontextprotocol/server": "^2.2.0",
57
- "node-autotask": "0.67.0",
57
+ "node-autotask": "0.69.0",
58
58
  "zod": "^4.6.7"
59
59
  },
60
60
  "devDependencies": {
package/server.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.61.1",
3
+ "version": "0.62.0",
4
4
  "description": "MCP server for the Autotask (Datto) PSA API, powered by the node-autotask SDK",
5
5
  "mcpProtocolBaseline": "2026-07-28",
6
6
  "legacyProtocolFallback": "2025-11-25",
@@ -62,7 +62,7 @@
62
62
  "capabilitiesManifest": "capabilities.json",
63
63
  "sdk": {
64
64
  "package": "node-autotask",
65
- "versionRange": "0.67.0"
65
+ "versionRange": "0.69.0"
66
66
  },
67
67
  "vendorExtensions": false,
68
68
  "credentialModelNote": "per-request; server-held under stdio or, on HTTP, only behind AUTOTASK_HTTP_AUTH=tokens; operator plans and the ledger are keyed by principal and tenant id, never by credential, and an apply authenticates the request credential and restores the plan's per-write impersonation"
@@ -5,7 +5,7 @@ version: 1
5
5
  profile: readonly
6
6
  description: One customer's picture: profile and configuration items, or tickets and hours in a period.
7
7
  when_not_to_use: billing questions (unbilled-work-review, contract-profitability); many companies at once (autotask_query or autotask_read companies.query)
8
- ops: ["autotask_resolve:companies.resolve", "autotask_resolve:companies.search", "autotask_company_full_profile:companies.fullProfile", "autotask_read:configuration_items.query", "autotask_query:tickets.query", "autotask_query:operations.aggregate"]
8
+ ops: ["autotask_resolve:companies.resolve", "autotask_resolve:companies.search", "autotask_resolve:companies.searchFuzzy", "autotask_company_full_profile:companies.fullProfile", "autotask_read:configuration_items.query", "autotask_query:tickets.query", "autotask_query:operations.aggregate"]
9
9
  inputs: {"type": "object", "required": ["company"], "properties": {"company": {"type": ["string", "integer"], "description": "Company name or numeric company id"}}}
10
10
  outcomes: ["ok", "needs_input", "ambiguous", "error"]
11
11
  hazards: ["companies are a blind surface: a miss is not proof of absence"]
@@ -21,7 +21,7 @@ eval: evals/company-360.json
21
21
 
22
22
  ## Steps
23
23
 
24
- 1. `autotask_resolve {identifier: "<company>", resource: "companies"}` (name or id): exact first, then contains on a miss. One match continues with it (`matched` says how), several return `ambiguous` with their ids and `ref` names, `TARGET_NOT_FOUND` returns `needs_input`.
24
+ 1. `autotask_resolve {identifier: "<company>", resource: "companies"}` (name or id): exact first, then contains, then fuzzy on misses. One exact/contains match continues with it (`matched` says how); fuzzy always returns `ambiguous`, including one distance-zero hit. Present candidates with their ids, `ref`, distance, matched terms, coverage and source; the caller chooses. `match: "fuzzy"` searches directly, at most 10 candidates (lower with `limit`); `include_family` adds family data. `include_inactive: true` includes inactive fuzzy candidates only (default false); exact/contains keep their existing activity behavior. Inspect `tier`, `truncated`, `pieces` and `index.state` before interpreting a miss.
25
25
  2. `autotask_company_full_profile {id: <id>}`: locations, contacts, notes, open tickets, projects. Each list part is capped at 10 rows by default (`contact_limit`, `note_limit`, `ticket_limit`, `project_limit`, 1-500; locations stay at 50, `location_limit`). To cut context further pass `fields: {contacts: ["firstName", "emailAddress"]}` (parts: locations, contacts, notes, projects, openTickets; unlisted parts keep every field). A part with `capped: true` has more rows: re-call with a higher limit for that part only if the task needs them.
26
26
  3. Configuration items: `autotask_read {operation: "configuration_items.query", args: [{filter: [{field: "companyID", op: "eq", value: <id>}], limit: 50}]}`. The answer is `data.results[0].result`.
27
27
 
@@ -33,7 +33,7 @@ Company activity in a period ("tickets for <company> created in the last 4 weeks
33
33
  ## Guardrails
34
34
 
35
35
  - Read-only. Contacts carry personal data: report names and roles, not more than the task needs.
36
- - Never pick one of several contains matches on your own.
36
+ - Never pick one of several contains matches or any fuzzy candidate on your own.
37
37
 
38
38
  ## Verify
39
39
 
@@ -42,7 +42,8 @@ The summary names the company by its `ref` (the `companyName` as safe text, capp
42
42
  ## Failure and rollback
43
43
 
44
44
  - `ambiguous` in step 1: return it with the candidate ids and names; the caller chooses.
45
- - `TARGET_NOT_FOUND` (exact and contains both missed): return `needs_input` for `company`.
45
+ - Empty fuzzy search: return its `needs_input` and metadata; it is not proof of absence. For cold/building indexes follow `next: retry` after the index builds; otherwise ask for a narrower name or known id. Capped results are partial.
46
+ - `TARGET_NOT_FOUND` on exact-only lookups: return `needs_input` for `company`.
46
47
  - A part with `absent` in step 2: report it as missing and continue.
47
48
  - Other `error`: return it unchanged.
48
49
 
@@ -62,6 +63,7 @@ The summary names the company by its `ref` (the `companyName` as safe text, capp
62
63
  |---|---|---|---|
63
64
  | autotask_resolve | companies.resolve | read | identifier |
64
65
  | autotask_resolve | companies.search | read | query |
66
+ | autotask_resolve | companies.searchFuzzy | read | query |
65
67
  | autotask_company_full_profile | companies.fullProfile | read | id |
66
68
  | autotask_read | configuration_items.query | read | - |
67
69
  | autotask_query | tickets.query | read | - |