@vectros-ai/mcp-server 0.16.1 → 0.17.1

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/cli-http.mjs CHANGED
@@ -37,6 +37,7 @@ __export(api_exports, {
37
37
  FieldDef: () => FieldDef,
38
38
  FileUploadRequest: () => FileUploadRequest,
39
39
  ForbiddenError: () => ForbiddenError,
40
+ GatewayTimeoutError: () => GatewayTimeoutError,
40
41
  IdentityLookupRequest: () => IdentityLookupRequest,
41
42
  IndexFailure: () => IndexFailure,
42
43
  InternalServerError: () => InternalServerError,
@@ -61,9 +62,12 @@ __export(api_exports, {
61
62
  SearchRequest: () => SearchRequest,
62
63
  SearchResult: () => SearchResult,
63
64
  SearchResultsEvent: () => SearchResultsEvent,
65
+ ServiceUnavailableError: () => ServiceUnavailableError,
64
66
  TooManyRequestsError: () => TooManyRequestsError,
67
+ TriggerFailureResponse: () => TriggerFailureResponse,
65
68
  TruncationWarningEvent: () => TruncationWarningEvent,
66
69
  UnauthorizedError: () => UnauthorizedError,
70
+ UnprocessableEntityError: () => UnprocessableEntityError,
67
71
  UserExistsResponse: () => UserExistsResponse,
68
72
  UserRequest: () => UserRequest,
69
73
  UserResponse: () => UserResponse,
@@ -75,7 +79,9 @@ __export(api_exports, {
75
79
  inference: () => inference_exports,
76
80
  records: () => records_exports,
77
81
  schemas: () => schemas_exports,
78
- search: () => search_exports
82
+ scripts: () => scripts_exports,
83
+ search: () => search_exports,
84
+ triggers: () => triggers_exports
79
85
  });
80
86
  var toJson = (value, replacer, space) => {
81
87
  return JSON.stringify(value, replacer, space);
@@ -195,6 +201,21 @@ var ForbiddenError = class extends VectrosError {
195
201
  this.name = this.constructor.name;
196
202
  }
197
203
  };
204
+ var GatewayTimeoutError = class extends VectrosError {
205
+ constructor(body, rawResponse) {
206
+ super({
207
+ message: "GatewayTimeoutError",
208
+ statusCode: 504,
209
+ body,
210
+ rawResponse
211
+ });
212
+ Object.setPrototypeOf(this, new.target.prototype);
213
+ if (Error.captureStackTrace) {
214
+ Error.captureStackTrace(this, this.constructor);
215
+ }
216
+ this.name = this.constructor.name;
217
+ }
218
+ };
198
219
  var InternalServerError = class extends VectrosError {
199
220
  constructor(body, rawResponse) {
200
221
  super({
@@ -255,6 +276,21 @@ var PaymentRequiredError = class extends VectrosError {
255
276
  this.name = this.constructor.name;
256
277
  }
257
278
  };
279
+ var ServiceUnavailableError = class extends VectrosError {
280
+ constructor(body, rawResponse) {
281
+ super({
282
+ message: "ServiceUnavailableError",
283
+ statusCode: 503,
284
+ body,
285
+ rawResponse
286
+ });
287
+ Object.setPrototypeOf(this, new.target.prototype);
288
+ if (Error.captureStackTrace) {
289
+ Error.captureStackTrace(this, this.constructor);
290
+ }
291
+ this.name = this.constructor.name;
292
+ }
293
+ };
258
294
  var TooManyRequestsError = class extends VectrosError {
259
295
  constructor(body, rawResponse) {
260
296
  super({
@@ -285,6 +321,21 @@ var UnauthorizedError = class extends VectrosError {
285
321
  this.name = this.constructor.name;
286
322
  }
287
323
  };
324
+ var UnprocessableEntityError = class extends VectrosError {
325
+ constructor(body, rawResponse) {
326
+ super({
327
+ message: "UnprocessableEntityError",
328
+ statusCode: 422,
329
+ body,
330
+ rawResponse
331
+ });
332
+ Object.setPrototypeOf(this, new.target.prototype);
333
+ if (Error.captureStackTrace) {
334
+ Error.captureStackTrace(this, this.constructor);
335
+ }
336
+ this.name = this.constructor.name;
337
+ }
338
+ };
288
339
  var auth_exports = {};
289
340
  var ErasureRequest;
290
341
  ((ErasureRequest2) => {
@@ -374,6 +425,7 @@ var LookupRecordsRequestOrder = {
374
425
  Desc: "desc"
375
426
  };
376
427
  var schemas_exports = {};
428
+ var scripts_exports = {};
377
429
  var SearchRequest;
378
430
  ((SearchRequest2) => {
379
431
  SearchRequest2.Mode = {
@@ -399,6 +451,7 @@ var search_exports = {};
399
451
  __export(search_exports, {
400
452
  SearchRequest: () => SearchRequest
401
453
  });
454
+ var triggers_exports = {};
402
455
  var AccessProfileRequest;
403
456
  ((AccessProfileRequest2) => {
404
457
  AccessProfileRequest2.Status = {
@@ -428,7 +481,9 @@ var BatchWriteResult;
428
481
  Created: "created",
429
482
  Updated: "updated",
430
483
  Conflict: "conflict",
431
- Invalid: "invalid"
484
+ Invalid: "invalid",
485
+ Forbidden: "forbidden",
486
+ NotCommitted: "not_committed"
432
487
  };
433
488
  })(BatchWriteResult || (BatchWriteResult = {}));
434
489
  var ChatMessage;
@@ -732,13 +787,23 @@ var SearchResultsEvent;
732
787
  SearchResults: "search_results"
733
788
  };
734
789
  })(SearchResultsEvent || (SearchResultsEvent = {}));
790
+ var TriggerFailureResponse;
791
+ ((TriggerFailureResponse2) => {
792
+ TriggerFailureResponse2.Event = {
793
+ Create: "CREATE",
794
+ Update: "UPDATE",
795
+ Delete: "DELETE"
796
+ };
797
+ })(TriggerFailureResponse || (TriggerFailureResponse = {}));
735
798
  var TruncationWarningEvent;
736
799
  ((TruncationWarningEvent2) => {
737
800
  TruncationWarningEvent2.Event = {
738
801
  TruncationWarning: "truncation_warning"
739
802
  };
740
803
  TruncationWarningEvent2.Reason = {
741
- ContextWindowBudget: "context_window_budget"
804
+ ContextWindowBudget: "context_window_budget",
805
+ NoGroundableContent: "no_groundable_content",
806
+ ContextWindowBudgetAndNoContent: "context_window_budget_and_no_content"
742
807
  };
743
808
  })(TruncationWarningEvent || (TruncationWarningEvent = {}));
744
809
  var UserExistsResponse;
@@ -753,8 +818,7 @@ var UserRequest;
753
818
  ((UserRequest2) => {
754
819
  UserRequest2.Status = {
755
820
  Active: "ACTIVE",
756
- Suspended: "SUSPENDED",
757
- Pending: "PENDING"
821
+ Suspended: "SUSPENDED"
758
822
  };
759
823
  UserRequest2.Type = {
760
824
  Human: "HUMAN",
@@ -2222,6 +2286,16 @@ function mergeHeaders(...headersArray) {
2222
2286
  }
2223
2287
  return result;
2224
2288
  }
2289
+ function mergeOnlyDefinedHeaders(...headersArray) {
2290
+ const result = {};
2291
+ for (const [key, value] of headersArray.filter((headers) => headers != null).flatMap((headers) => Object.entries(headers))) {
2292
+ const insensitiveKey = key.toLowerCase();
2293
+ if (value != null) {
2294
+ result[insensitiveKey] = value;
2295
+ }
2296
+ }
2297
+ return result;
2298
+ }
2225
2299
  function normalizeClientOptions(options) {
2226
2300
  const headers = mergeHeaders(
2227
2301
  {
@@ -2492,7 +2566,7 @@ var AuthClient = class {
2492
2566
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/admin/keys/scoped");
2493
2567
  }
2494
2568
  /**
2495
- * Creates a scoped API key (an `ssk_*` secret) that inherits its permissions from an existing access profile in your account. The call is idempotent on the combination of tenant, context, user, and key name: re-issuing the same request returns the existing key WITHOUT re-disclosing its raw secret. The raw key is returned ONLY in this response — store it securely, as it cannot be retrieved again. Requires the `keys:c` scope. If you use a scoped credential, `keys:c` alone is not sufficient: because the minted key is durably bound to the profile you name, the profile's effective scopes may not exceed your own, and you may only mint against a profile whose `identityOverrides` values your own identity holds. Minting a key bound to your OWN principal needs nothing further; minting one bound to a DIFFERENT principal additionally requires the `delegate-mint` capability (`granted_capabilities`) on your credential — without it the request is refused. A root API key (`sk_`) is exempt from all three bounds.
2569
+ * Creates a scoped API key (an `ssk_*` secret) that inherits its permissions from an existing access profile in your account. The call is idempotent on the combination of tenant, context, user, and key name: re-issuing the same request returns the existing key WITHOUT re-disclosing its raw secret. The raw key is returned ONLY in this response — store it securely, as it cannot be retrieved again. Requires the `keys:c` scope. If you use a scoped credential, `keys:c` alone is not sufficient: because the minted key is durably bound to the profile you name, the profile's effective scopes may not exceed your own, and you may only mint against a profile whose `identityOverrides` values your own identity holds. Minting a key bound to your OWN principal needs nothing further; minting one bound to a DIFFERENT principal additionally requires the `delegate-mint` capability (`granted_capabilities`) on your credential — without it the request is refused. A root API key (`sk_`) is exempt from all three bounds. The profile you name must be `active` AND the user you name must not be `SUSPENDED`: either is refused with `409`, and no root exemption applies to that. Both refusals stop ISSUANCE only. Suspending the profile additionally stops credentials already bound to it, within about five minutes; suspending the user does not stop their existing keys at all. A `PENDING` user is fine.
2496
2570
  *
2497
2571
  * @param {Vectros.CreateScopedKeyRequest} request
2498
2572
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -2500,6 +2574,7 @@ var AuthClient = class {
2500
2574
  * @throws {@link Vectros.BadRequestError}
2501
2575
  * @throws {@link Vectros.ForbiddenError}
2502
2576
  * @throws {@link Vectros.NotFoundError}
2577
+ * @throws {@link Vectros.ConflictError}
2503
2578
  * @throws {@link Vectros.TooManyRequestsError}
2504
2579
  *
2505
2580
  * @example
@@ -2548,6 +2623,8 @@ var AuthClient = class {
2548
2623
  throw new ForbiddenError(_response.error.body, _response.rawResponse);
2549
2624
  case 404:
2550
2625
  throw new NotFoundError(_response.error.body, _response.rawResponse);
2626
+ case 409:
2627
+ throw new ConflictError(_response.error.body, _response.rawResponse);
2551
2628
  case 429:
2552
2629
  throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
2553
2630
  default:
@@ -2959,7 +3036,7 @@ var AuthClient = class {
2959
3036
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/app-contexts");
2960
3037
  }
2961
3038
  /**
2962
- * Creates a new app context. This call is idempotent by `contextId`: if an app context with the same `contextId` already exists, the existing app context is returned (with status 200) instead of creating a duplicate. The response's `created` field (and the HTTP status — 201 when created, 200 when an existing context was returned) tells the two apart. To overwrite an existing context's `name`/`description` instead of returning it unchanged, set `?upsert=true` (this also requires the `app-contexts:u` scope). The reserved `contextId` value `vectros-admin` cannot be created through this endpoint; it is provisioned automatically for your account. Requires the `app-contexts:c` scope.
3039
+ * Creates a new app context. This call is idempotent by `contextId`: if an app context with the same `contextId` already exists, the existing app context is returned (with status 200) instead of creating a duplicate. The response's `created` field (and the HTTP status — 201 when created, 200 when an existing context was returned) tells the two apart. To overwrite an existing context's `name`/`description`/`companyName` instead of returning it unchanged, set `?upsert=true` (this also requires the `app-contexts:u` scope). The reserved `contextId` value `vectros-admin` cannot be created through this endpoint; it is provisioned automatically for your account. Requires the `app-contexts:c` scope.
2963
3040
  *
2964
3041
  * @param {Vectros.CreateAppContextRequest} request
2965
3042
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -3325,6 +3402,7 @@ var AuthClient = class {
3325
3402
  *
3326
3403
  * @throws {@link Vectros.ForbiddenError}
3327
3404
  * @throws {@link Vectros.NotFoundError}
3405
+ * @throws {@link Vectros.ConflictError}
3328
3406
  * @throws {@link Vectros.TooManyRequestsError}
3329
3407
  *
3330
3408
  * @example
@@ -3367,6 +3445,8 @@ var AuthClient = class {
3367
3445
  throw new ForbiddenError(_response.error.body, _response.rawResponse);
3368
3446
  case 404:
3369
3447
  throw new NotFoundError(_response.error.body, _response.rawResponse);
3448
+ case 409:
3449
+ throw new ConflictError(_response.error.body, _response.rawResponse);
3370
3450
  case 429:
3371
3451
  throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
3372
3452
  default:
@@ -3443,7 +3523,7 @@ var AuthClient = class {
3443
3523
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/app-contexts/{contextId}");
3444
3524
  }
3445
3525
  /**
3446
- * Updates the name and/or description of an app context. This is a partial update: any field you omit (or send as null) keeps its existing value. The `contextId` is immutable and is taken from the URL path, so any `contextId` in the request body is ignored. Requires the `app-contexts:u` scope.
3526
+ * Updates the name, description, and/or companyName of an app context. This is a partial update: any field you omit (or send as null) keeps its existing value. The `contextId` is immutable and is taken from the URL path, so any `contextId` in the request body is ignored. Requires the `app-contexts:u` scope.
3447
3527
  *
3448
3528
  * @param {Vectros.UpdateAppContextRequest} request
3449
3529
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -3511,7 +3591,7 @@ var AuthClient = class {
3511
3591
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/app-contexts/{contextId}");
3512
3592
  }
3513
3593
  /**
3514
- * Permanently deletes an app context and everything in it — every record, document, folder, schema, role, and access profile belonging to the context. This is irreversible. The deletion runs asynchronously: the call returns 202 immediately and the context's data drains in the background. Poll the context's `status` field to observe when the teardown completes (`purging` while draining, then `deleted`). To guard against accidental deletion, you must echo the contextId back in the `confirm` query parameter (`?confirm={contextId}`). The reserved `default` and `vectros-admin` contexts cannot be deleted. This operation requires a root API key (one beginning with `sk_`): no scoped credential, not even one with full wildcard (`*`) scope, can trigger this teardown.
3594
+ * Permanently deletes an app context and everything in it — every record, document, folder, schema, role, access profile, and trusted-issuer registration belonging to the context. This is irreversible. The deletion runs asynchronously: the call returns 202 immediately and the context's data drains in the background. Poll the context's `status` field to observe when the teardown completes (`purging` while draining, then `deleted`). To guard against accidental deletion, you must echo the contextId back in the `confirm` query parameter (`?confirm={contextId}`). The reserved `default` and `vectros-admin` contexts cannot be deleted. This operation requires a root API key (one beginning with `sk_`): no scoped credential, not even one with full wildcard (`*`) scope, can trigger this teardown.
3515
3595
  *
3516
3596
  * @param {Vectros.DeleteAppContextRequest} request
3517
3597
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -3925,7 +4005,7 @@ var AuthClient = class {
3925
4005
  );
3926
4006
  }
3927
4007
  /**
3928
- * Returns full usage detail for the requested calendar month, broken down by category (search, documents, and records) with per-category credit estimates and a split between your live and test environments. Defaults to the current month when `year` and `month` are omitted. Requires the `billing:r` scope on scoped tokens; API keys always have access. **A token confined to a single app context sees only that context's usage**: totals, the environment split, and the `contexts` breakdown narrow to it, and the environment your context is not bound to is omitted (`null`), not zeroed. Only a token with cross-context reach sees your full account-wide totals. Two exceptions to the narrowing, since they have no per-context breakdown to narrow to: `reads.calls.used`/`reads.dataOut.bytes` (metered per account, not per context) read as `0` for a confined token rather than a narrowed figure — the corresponding overage-credit charge fields narrow correctly; and `credits.limit` stays your whole plan's ceiling, so `credits.remaining` may overstate the account's true remaining room.
4008
+ * Returns full usage detail for the requested calendar month, broken down by category (search, documents, records, and trigger-script execution time) with per-category credit estimates and a split between your live and test environments. Defaults to the current month when `year` and `month` are omitted. Requires the `billing:r` scope on scoped tokens; API keys always have access. **A token confined to a single app context sees only that context's usage**: totals, the environment split, and the `contexts` breakdown narrow to it, and the environment your context is not bound to is omitted (`null`), not zeroed. Only a token with cross-context reach sees your full account-wide totals. Two exceptions to the narrowing, since they have no per-context breakdown to narrow to: `reads.calls.used`/`reads.dataOut.bytes` (metered per account, not per context) read as `0` for a confined token rather than a narrowed figure — the corresponding overage-credit charge fields narrow correctly; and `credits.limit` stays your whole plan's ceiling, so `credits.remaining` may overstate the account's true remaining room. The `execution` section narrows correctly for a confined token, like the other per-context charge fields — but note its credits carry sub-credit remainders forward across your whole account for the period, so compare `execution.creditsMilli` against your account-wide figure rather than recomputing it from one context's `billableMillis`.
3929
4009
  *
3930
4010
  * @param {Vectros.GetUsageRequest} request
3931
4011
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -4046,7 +4126,7 @@ var AuthClient = class {
4046
4126
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/auth/issuers/{issuerId}");
4047
4127
  }
4048
4128
  /**
4049
- * Updates the mutable fields of a registered issuer: `subClaim`, `emailClaim`, `status` (`active`/`suspended` — a suspended issuer's tokens are rejected identically to an unregistered issuer at exchange time), and `selfSignupPolicies`. Fields omitted from the body are left unchanged (partial update). `issuer`, `jwksUri`, `audience`, and `contextId` are trust-anchor / routing-pin fields and are immutable via this route — supplying a value that differs from the current registration is rejected with 400; supplying the current value back is a no-op. Rotating a trust anchor requires deleting and re-registering the issuer, which is itself refused while any user is bound through it. Requires a root API key or the bootstrap's provisioning capability, gated identically to every other operation on this surface. A credential confined to one app context may only update an issuer registered in that context; naming one registered in another context returns 404, identically to a nonexistent issuerId. A root API key may update any issuer.
4129
+ * Updates the mutable fields of a registered issuer: `subClaim`, `emailClaim`, `userinfoUri`, `capturedClaims`, `restrictedToDomain` (a new non-blank value must already be a VERIFIED domain for your account; an empty string clears it back to domain-less; see `IssuerUpdateRequest.restrictedToDomain` for the full semantics), `status` (`active`/`suspended` — a suspended issuer's tokens are rejected identically to an unregistered issuer at exchange time), and `selfSignupPolicies`. Fields omitted from the body are left unchanged (partial update). `issuer`, `jwksUri`, `audience`, and `contextId` are trust-anchor / routing-pin fields and are immutable via this route — supplying a value that differs from the current registration is rejected with 400; supplying the current value back is a no-op. Rotating a trust anchor requires deleting and re-registering the issuer, which is itself refused while any user is bound through it. **`subClaim` is identity-determining, not merely cosmetic**: it names which verified JWT claim is read as the federated user's identifier, so changing it on an issuer that already has bound users would silently re-identify (or, under self-signup, orphan) every one of them — changing it is therefore refused once any user has bound through this issuer, the same guard `DELETE` already applies, and is only free before the first real login. Requires a root API key or the bootstrap's provisioning capability, gated identically to every other operation on this surface. A credential confined to one app context may only update an issuer registered in that context; naming one registered in another context returns 404, identically to a nonexistent issuerId. A root API key may update any issuer.
4050
4130
  *
4051
4131
  * @param {Vectros.IssuerUpdateRequest} request
4052
4132
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -4113,7 +4193,7 @@ var AuthClient = class {
4113
4193
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/auth/issuers/{issuerId}");
4114
4194
  }
4115
4195
  /**
4116
- * Deregisters a trusted third-party IdP issuer. Requires a root API key or the bootstrap's provisioning capability. A credential confined to one app context may only deregister an issuer registered in that context; naming one registered in another context returns 404, identically to a nonexistent issuerId. A root API key may deregister any issuer. Refused if any user account was ever created or matched via this issuer (by a prior self-signup or accepted invite, through `POST /v1/auth/token/exchange`) — that access cannot be silently orphaned. Deactivate the affected users first if you intend to cut off their access, or register a replacement issuer before removing this one. An issuer that has never been used for an exchange (no bound users yet) can always be deregistered.
4196
+ * Deregisters a trusted third-party IdP issuer. Requires a root API key or the bootstrap's provisioning capability. A credential confined to one app context may only deregister an issuer registered in that context; naming one registered in another context returns 404, identically to a nonexistent issuerId. A root API key may deregister any issuer. Refused if any user account was ever created or matched via this issuer (by a prior self-signup or accepted invite, through `POST /v1/auth/token/exchange`) — that access cannot be silently orphaned. This is unconditional on the affected users' `status`: suspending them first does not lift the refusal. **A bound registration cannot be replaced, self-service, within its own app context**: registering a replacement issuer under a different issuerId in the SAME context also fails, because the context's one-active-issuer claim is released only when THIS registration is deleted. Two real options: suspend this issuer (stops new exchanges immediately) and register a replacement under a DIFFERENT app context — note that targets a different context, so this context's existing users/roles/access profiles are not carried over; or contact your platform operator, who can force-release this registration so a replacement may be registered in the SAME context under a new issuerId. **The operator path is not a lighter-weight alternative to the first — it PERMANENTLY RETIRES this issuerId and leaves every bound user unable to ever exchange through it again; it does not preserve continuity for them any better than registering under a different context does.** An issuer that has never been used for an exchange (no bound users yet) can always be deregistered.
4117
4197
  *
4118
4198
  * @param {Vectros.DeleteIssuerRequest} request
4119
4199
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -4239,7 +4319,7 @@ var AuthClient = class {
4239
4319
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/auth/issuers");
4240
4320
  }
4241
4321
  /**
4242
- * Registers a trusted third-party IdP issuer that BYO-IdP token exchange (`POST /v1/auth/token/exchange`) may accept a `subject_token` from. Requires a root API key or the CLI bootstrap's provisioning capability — never an ordinary partner-grantable scope. A credential authorized only via the provisioning capability may register only against the app context it is bound to; naming a different one returns 403. A root API key is unaffected and may register against any of its contexts. Idempotent by `issuerId` within your tenant; the `(issuer, audience)` pair must not already be registered by a different issuerId/tenant. If `issuerId` collides with a registration owned by a different app context than the one you're confined to, the request fails with 400 rather than returning that context's configuration. An app context may have at most one active issuer — deregister the existing one first if you need to replace it. One issuer MAY serve several contexts today, each via its own registration row with a distinct `audience`.
4322
+ * Registers a trusted third-party IdP issuer that BYO-IdP token exchange (`POST /v1/auth/token/exchange`) may accept a `subject_token` from. Requires a root API key or the CLI bootstrap's provisioning capability — never an ordinary partner-grantable scope. A credential authorized only via the provisioning capability may register only against the app context it is bound to; naming a different one returns 403. A root API key is unaffected and may register against any of its contexts. Idempotent by `issuerId` within your tenant; the `(issuer, audience)` pair must not already be registered by a different issuerId/tenant. If `issuerId` collides with a registration owned by a different app context than the one you're confined to, the request fails with 400 rather than returning that context's configuration. An app context may have at most one active issuer — deregister the existing one first if you need to replace it. One issuer MAY serve several contexts today, each via its own registration row with a distinct `audience`. Optionally name `restrictedToDomain` to scope this registration's (issuer, audience) uniqueness to a specific VERIFIED domain rather than the bare pair — see that field's own description for the full contract, including why it does NOT protect a shared/consumer-IdP registration with no company-domain population.
4243
4323
  *
4244
4324
  * @param {Vectros.IssuerRequest} request
4245
4325
  * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -5737,7 +5817,7 @@ var DocumentsClient = class {
5737
5817
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/documents/{id}/versions");
5738
5818
  }
5739
5819
  /**
5740
- * Starts a file-based document by returning a short-lived presigned S3 PUT URL. Upload the file bytes directly to `uploadUrl`; the document is then automatically queued for text extraction and asynchronous indexing. Supplying an `externalId` makes this idempotent — re-initiating an upload with the same `externalId` re-issues a fresh presigned URL to the SAME existing document/object (so a re-upload inherently replaces the file body) rather than creating a duplicate. The response's `created` field (and the HTTP status — 201 when a new document was minted, 200 when an existing one was matched) tells the two apart. With `?upsert=true`, the submitted `payload`/`title` are also applied to the matched document (file-body divergence cannot be diffed at upload-init — the bytes have not arrived yet — so the re-upload itself replaces the body). Creating a NEW document requires the `documents:c` scope. Re-uploading over an EXISTING document overwrites (and re-indexes) its body, so it is an update: it requires the `documents:u` scope (as does `?upsert=true` for the metadata).
5820
+ * Starts a file-based document by returning a short-lived presigned S3 PUT URL. Upload the file bytes directly to `uploadUrl`; the document is then automatically queued for text extraction and asynchronous indexing. Supplying an `externalId` makes this idempotent — re-initiating an upload with the same `externalId` re-issues a fresh presigned URL for the SAME existing document, targeting a newly-staged object rather than the document's current one — your PUT lands there first, and the document only adopts it once the upload is validated (so a re-upload inherently replaces the file body) rather than creating a duplicate. The response's `created` field (and the HTTP status — 201 when a new document was minted, 200 when an existing one was matched) tells the two apart. With `?upsert=true`, the submitted `payload`/`title` are also applied to the matched document (file-body divergence cannot be diffed at upload-init — the bytes have not arrived yet — so the re-upload itself replaces the body). Creating a NEW document requires the `documents:c` scope. Re-uploading over an EXISTING document overwrites (and re-indexes) its body, so it is an update: it requires the `documents:u` scope (as does `?upsert=true` for the metadata). **Your PUT to `uploadUrl` MUST include the header named in the response's `requiredHeaderName`, set to `requiredHeaderValue` exactly.** It is a signed part of the presigned request — the PUT never reaches this service either way, so neither failure uses this API's JSON error shape. Omitting it, or sending a different value, invalidates the request's signature and S3 rejects it with a 403 `SignatureDoesNotMatch`. Sending it correctly makes the URL single-use: `requiredHeaderName` is always `If-None-Match` and `requiredHeaderValue` is always `*` — a create, a recovery upload for a document whose earlier file is missing, and a re-upload ALL target a freshly-minted, never-written key, so the same S3 conditional-write precondition applies uniformly (S3's own documented conditional-write behavior): a replay after the object already exists (from your own completed PUT, or anyone else's) fails with `412 Precondition Failed`; a replay after the object was deleted and never re-created finds an absent key again and can succeed — single-use is a property of the object's existence, not a one-time token. **Either precondition can also fail with `409 Conflict` if your PUT genuinely races a concurrent delete on the same object.** Whichever of `412` or `409` you receive, the remedy is the same: call this endpoint again for a fresh URL rather than retrying the same PUT — a fresh call always targets a new key, so it is never subject to whatever raced the previous one.
5741
5821
  *
5742
5822
  * @param {Vectros.FileUploadRequest} request
5743
5823
  * @param {DocumentsClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -6059,7 +6139,7 @@ var FoldersClient = class {
6059
6139
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/folders/{id}");
6060
6140
  }
6061
6141
  /**
6062
- * Permanently deletes a folder. The folder must be empty (contain no documents or sub-folders) and must not be protected. Your context's root folder is protected and cannot be deleted. Requires the `folders:d` scope.
6142
+ * Permanently deletes a folder. The folder must be empty — it must contain no documents, no records, and no sub-folders — and must not be protected. Your context's root folder is protected and cannot be deleted. Requires the `folders:d` scope.
6063
6143
  *
6064
6144
  * @param {Vectros.DeleteFolderRequest} request
6065
6145
  * @param {FoldersClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -6468,11 +6548,12 @@ var IdentityClient = class {
6468
6548
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/entities/{namespace}/{id}");
6469
6549
  }
6470
6550
  /**
6471
- * Updates the mutable fields of an entity. Omitted fields are preserved (a null value does not clear a field), and the `payload` object is replaced in full when supplied. Providing `scopes` replaces the entity's parent edges. Requires the `entities:u:<namespace>` scope.
6551
+ * Updates the mutable fields of an entity. Omitted fields are preserved (a null value does not clear a field), and the `payload` object is replaced in full when supplied. Providing `scopes` replaces the entity's parent edges. Supplying a different `externalId` re-points the entity's identifier; it must still be unused in this namespace and app context. Requires the `entities:u:<namespace>` scope.
6472
6552
  *
6473
6553
  * @param {Vectros.UpdateEntityRequest} request
6474
6554
  * @param {IdentityClient.RequestOptions} requestOptions - Request-specific configuration.
6475
6555
  *
6556
+ * @throws {@link Vectros.BadRequestError}
6476
6557
  * @throws {@link Vectros.NotFoundError}
6477
6558
  * @throws {@link Vectros.TooManyRequestsError}
6478
6559
  *
@@ -6522,6 +6603,8 @@ var IdentityClient = class {
6522
6603
  }
6523
6604
  if (_response.error.reason === "status-code") {
6524
6605
  switch (_response.error.statusCode) {
6606
+ case 400:
6607
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
6525
6608
  case 404:
6526
6609
  throw new NotFoundError(_response.error.body, _response.rawResponse);
6527
6610
  case 429:
@@ -7500,7 +7583,7 @@ var IdentityClient = class {
7500
7583
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/users/exists-by-email");
7501
7584
  }
7502
7585
  /**
7503
- * Returns the audit trail of changes to a user, most recent first. Identity history is always recorded and always available. Sensitive field values are redacted in every historical version. Returns a page in the `{data, nextCursor}` envelope. Requires the `users:r` scope.
7586
+ * Returns the audit trail of changes to a user, most recent first, including after the user has been deleted. Identity history is always recorded. Post-delete, this is readable by an account-level (root) API key only — a context-confined credential 404s after the delete, the same response it would get for a nonexistent id. Sensitive field values are redacted in every historical version. Returns a page in the `{data, nextCursor}` envelope. Requires the `users:r` scope.
7504
7587
  *
7505
7588
  * @param {Vectros.GetUserVersionsRequest} request
7506
7589
  * @param {IdentityClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -7746,7 +7829,7 @@ var InferenceClient = class {
7746
7829
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/documents/{id}/ask");
7747
7830
  }
7748
7831
  /**
7749
- * Runs hybrid search over your indexed content, then streams a model answer grounded in the top results. The SSE stream emits a `search_results` event first (carrying the matched results and their metadata), an optional `truncation_warning` if lower-scoring results were dropped to fit the model's context window, then `content_delta` chunks, and finally a terminal `done` event. Requires the `inference:r` scope.
7832
+ * Runs hybrid search over your indexed content, then streams a model answer grounded in the top results. The SSE stream emits a `search_results` event first (carrying the matched results and their metadata), an optional `truncation_warning` if some retrieved results were dropped before the prompt was built — either because they didn't fit the model's context window or because a result had no groundable text to include — then `content_delta` chunks, and finally a terminal `done` event. Requires the `inference:r` scope.
7750
7833
  */
7751
7834
  ragInference(request, requestOptions) {
7752
7835
  return HttpResponsePromise.fromPromise(this.__ragInference(request, requestOptions));
@@ -7941,14 +8024,18 @@ var RecordsClient = class {
7941
8024
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/records/lookup/batch");
7942
8025
  }
7943
8026
  /**
7944
- * Reserved endpoint for bulk record writes. The published response shape includes a per-item partial-failure envelope and an atomicity flag. It currently returns 501 (not implemented). The documented 200 response schema is the stable shape this endpoint will use once available, published now so SDK integrations against it will not break when it ships. Requires the `records:c` scope.
8027
+ * Writes up to 50 records (or 50 with `atomicity: all_or_nothing`) in a single request. Each item in `items` has exactly the same shape, and goes through exactly the same validation, authorization and idempotency rules, as the body of a single `POST /v1/records` — including schema validation, `externalId` idempotency, unique-field enforcement, and the `records:c:<type>` scope check, which is applied per item against that item's own record type. A batch is not a way to write a type your credential could not write one at a time.
8028
+ *
8029
+ * `atomicity` selects how the batch commits. `best_effort` (the default) writes each item independently: some can succeed while others fail, and each item's own outcome is reported. `all_or_nothing` commits every item in one transaction — if any item fails, no record is created or updated at all, and every item that was itself fine reports `not_committed` while the ones that failed report why. Because the transaction is bounded by the number of underlying storage rows rather than by the number of records, a large `all_or_nothing` batch can be refused as too large to commit atomically even when it is within the item limit; the error says so, and nothing is written when it happens.
8030
+ *
8031
+ * The response is HTTP 200 whenever the batch was processed at all — including when every item failed — so always inspect `results` rather than relying on the status code. Match each result to the item you sent using its `index`. Requires the `records:c` scope.
7945
8032
  *
7946
8033
  * @param {Vectros.BatchWriteRequest} request
7947
8034
  * @param {RecordsClient.RequestOptions} requestOptions - Request-specific configuration.
7948
8035
  *
8036
+ * @throws {@link Vectros.BadRequestError}
7949
8037
  * @throws {@link Vectros.ForbiddenError}
7950
8038
  * @throws {@link Vectros.TooManyRequestsError}
7951
- * @throws {@link Vectros.NotImplementedError}
7952
8039
  *
7953
8040
  * @example
7954
8041
  * await client.records.batchWriteRecords()
@@ -7957,6 +8044,11 @@ var RecordsClient = class {
7957
8044
  return HttpResponsePromise.fromPromise(this.__batchWriteRecords(request, requestOptions));
7958
8045
  }
7959
8046
  async __batchWriteRecords(request = {}, requestOptions) {
8047
+ const { upsert, allowClear, ..._body } = request;
8048
+ const _queryParams = {
8049
+ upsert,
8050
+ allowClear
8051
+ };
7960
8052
  const _authRequest = await this._options.authProvider.getAuthRequest();
7961
8053
  const _headers = mergeHeaders(
7962
8054
  _authRequest.headers,
@@ -7971,9 +8063,9 @@ var RecordsClient = class {
7971
8063
  method: "POST",
7972
8064
  headers: _headers,
7973
8065
  contentType: "application/json",
7974
- queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
8066
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
7975
8067
  requestType: "json",
7976
- body: request,
8068
+ body: _body,
7977
8069
  timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
7978
8070
  maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
7979
8071
  abortSignal: requestOptions?.abortSignal,
@@ -7985,12 +8077,12 @@ var RecordsClient = class {
7985
8077
  }
7986
8078
  if (_response.error.reason === "status-code") {
7987
8079
  switch (_response.error.statusCode) {
8080
+ case 400:
8081
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
7988
8082
  case 403:
7989
8083
  throw new ForbiddenError(_response.error.body, _response.rawResponse);
7990
8084
  case 429:
7991
8085
  throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
7992
- case 501:
7993
- throw new NotImplementedError(_response.error.body, _response.rawResponse);
7994
8086
  default:
7995
8087
  throw new VectrosError({
7996
8088
  statusCode: _response.error.statusCode,
@@ -8561,7 +8653,7 @@ var RecordsClient = class {
8561
8653
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/records/lookup");
8562
8654
  }
8563
8655
  /**
8564
- * Returns the tombstone left behind when a record was hard-deleted, confirming the deletion and recording when it happened. Look it up using the deleted record's original ID. Requires the `records:r:<type>` scope.
8656
+ * Returns the tombstone left behind when a record was hard-deleted, confirming the deletion and recording when it happened. Look it up using the deleted record's original ID. Requires the `records:r:<type>` scope, granted without a `data_scope` restriction: the owner of a deleted record cannot be checked, so a credential confined to an ownership compartment (e.g. `data_scope: {scope:org: [org_A]}`) cannot read tombstones, including for records it owned.
8565
8657
  *
8566
8658
  * @param {Vectros.GetRecordTombstoneRequest} request
8567
8659
  * @param {RecordsClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -8893,7 +8985,7 @@ var SchemasClient = class {
8893
8985
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/schemas/{id}");
8894
8986
  }
8895
8987
  /**
8896
- * Updates a record schema. Fields you omit are preserved; `typeName` is immutable and cannot be changed. Collection fields (`fields`, `lookupFields`, `renderHints`, `capabilities`) are replaced in full when supplied. Requires the `schemas:u` scope.
8988
+ * Updates a record schema. Fields you omit are preserved; `typeName` is immutable and cannot be changed. Collection fields (`fields`, `lookupFields`, `renderHints`, `capabilities`) are replaced in full when supplied. Because `capabilities` is replaced in full, omitting `triggersEnabled` clears it — the request is refused with 409 if that would disable triggers while trigger rules still fire off this schema, so delete those rules first. Requires the `schemas:u` scope.
8897
8989
  *
8898
8990
  * @param {Vectros.UpdateSchemaRequest} request
8899
8991
  * @param {SchemasClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -8901,6 +8993,7 @@ var SchemasClient = class {
8901
8993
  * @throws {@link Vectros.BadRequestError}
8902
8994
  * @throws {@link Vectros.ForbiddenError}
8903
8995
  * @throws {@link Vectros.NotFoundError}
8996
+ * @throws {@link Vectros.ConflictError}
8904
8997
  * @throws {@link Vectros.TooManyRequestsError}
8905
8998
  *
8906
8999
  * @example
@@ -8952,6 +9045,8 @@ var SchemasClient = class {
8952
9045
  throw new ForbiddenError(_response.error.body, _response.rawResponse);
8953
9046
  case 404:
8954
9047
  throw new NotFoundError(_response.error.body, _response.rawResponse);
9048
+ case 409:
9049
+ throw new ConflictError(_response.error.body, _response.rawResponse);
8955
9050
  case 429:
8956
9051
  throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
8957
9052
  default:
@@ -8965,7 +9060,7 @@ var SchemasClient = class {
8965
9060
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/schemas/{id}");
8966
9061
  }
8967
9062
  /**
8968
- * Permanently deletes a record schema. The request is refused with 409 if records of this type still exist — delete those records first, since every record must reference a live schema. A lineage base (a schema other schemas declare `basedOn`) also cannot be deleted while any such variant still exists — delete the variant schema(s) first. Requires the `schemas:d` scope.
9063
+ * Permanently deletes a record schema. The request is refused with 409 if records of this type still exist — delete those records first, since every record must reference a live schema. The same applies to documents bound to this schema (for a schema declaring the `document` surface) — delete those documents first. A lineage base (a schema other schemas declare `basedOn`) also cannot be deleted while any such variant still exists — delete the variant schema(s) first. It is likewise refused while any trigger rule fires off this schema — delete those trigger rules first. Requires the `schemas:d` scope.
8969
9064
  *
8970
9065
  * @param {Vectros.DeleteSchemaRequest} request
8971
9066
  * @param {SchemasClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -9087,46 +9182,70 @@ var SchemasClient = class {
9087
9182
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/schemas/{id}/versions");
9088
9183
  }
9089
9184
  };
9090
- var SearchClient = class {
9185
+ var ScriptsClient = class {
9091
9186
  constructor(options) {
9092
9187
  this._options = normalizeClientOptionsWithAuth(options);
9093
9188
  }
9094
9189
  /**
9095
- * Runs a hybrid, semantic, or text search across the content you have indexed. By default it returns both documents and records in a single unified result set; pass `contentTypes` to narrow the results (for example `["documents"]`). Each result carries a `sourceType` discriminator (`PartnerDocument` or `GenericRecord`) so you can branch on the type. Requires the `search:r` scope.
9190
+ * Runs a script you previously pushed to `POST /v1/scripts`, under your own credential, and returns what it returned. Every write the script makes is buffered and committed as ONE transaction after the script finishes: either all of them land or none do, and the response is sent only after they have committed — so everything in `result` is committed state or the script's own computation over it. On any failure the body is the standard error envelope and nothing the script staged is committed: its rows are written only when the transaction commits, and a document body or a large payload is DECIDED at that point and WRITTEN to storage only after the commit, so an aborted execution leaves nothing behind. The one residual sits after a successful commit, outside this response: if storing a body fails then, the row exists and the body does not until the platform's repair lands — so a `200` guarantees the rows, and a document's text should be read before it is relied on.
9096
9191
  *
9097
- * @param {Vectros.SearchRequest} request
9098
- * @param {SearchClient.RequestOptions} requestOptions - Request-specific configuration.
9192
+ * **Permission.** Requires the `scripts:x` scope — the permission to *execute* — separate from the `scripts:c` permission to push scripts. Bare `scripts:x` grants every script in the context; `scripts:x:<name>` grants exactly that script name, every version of it. Execution discloses no source, so `scripts:r` is not needed. Inside the script, every read and write is enforced by your credential's data scopes exactly as the equivalent REST call would be — `scripts:x` alone can read and write nothing.
9193
+ *
9194
+ * **Input.** Your script sees `input.event` (the literal `"execute"`), `input.userId` (your credential's user id, or null), and `input.params` (the `input` object you sent, verbatim). That is the same `input` grammar a trigger rule uses, so one script can serve both by branching on `input.event`. `params` is not validated — a script that needs a shape checks for it and throws; the script's `declaredInputContract` is documentation for readers and is not enforced.
9195
+ *
9196
+ * **Budget.** Seconds of useful work: the script has 15 s of wall clock (never more than 16) and a bounded number of statements and host calls; a runaway script is stopped early with `RESOURCE_LIMIT_EXCEEDED`. The transaction is bounded by the number of underlying storage rows it writes — 100 rows after merging — rather than by the number of entities: creating a folder costs 3 rows; creating a plain text document or a record costs 1 row plus one per range-indexed lookup field plus one per `reference` field. So "create a folder and file N documents" holds up to 97 plain documents, 48 with one range field or one reference, 32 with both; if a script exceeds the limit the error says so (`WRITE_BUFFER_CAP_EXCEEDED`, with `total` and `limit`) and nothing is committed. This request takes the write-path limits (burst, credit ceiling, principal quota) once, before the script runs — there is no free-read allowance here, so an account over its credit ceiling is refused even for a read-only script. Reads the script performs are metered as reads, writes as writes, and execution time beyond what those operations include is charged as script execution time (see `GET /v1/usage`).
9197
+ *
9198
+ * **Reads inside the script.** A `get` sees the script's own staged writes. A list, query or lookup never shows a row the script has deleted, shows a row it re-saved with the updated content, and does not show a row it created — you hold that row's id from `create()`.
9199
+ *
9200
+ * **Retries.** Send an optional `Idempotency-Key` header (1–128 characters of letters, digits, `.`, `_`, `:` or `-`) to make a retry safe: a request repeated under the same key within 24 hours receives the same response as the first attempt without executing again — when that first attempt SUCCEEDED (a duplicate still in flight is refused with `409 IDEMPOTENCY_IN_PROGRESS`; the same key on a different request is refused with `422 IDEMPOTENCY_KEY_REUSED`). A first attempt that FAILED with any other status is not remembered: the same key is free to try again, so a retry after a `400` or a `429` executes. If an execution's outcome cannot be determined — the script did not finish inside the budget while its writes may have committed — the response is `500 EXECUTION_OUTCOME_UNKNOWN` carrying `execution.id`, and a keyed retry receives that same answer: inspect what the script would have written, then use a NEW key for a new attempt. When a key is present the serialised `result` is capped at 16 KB instead of 256 KB. Without a key, a lost response cannot be distinguished from a failed one; re-read before retrying.
9201
+ *
9202
+ * @param {Vectros.ScriptExecuteRequest} request
9203
+ * @param {ScriptsClient.RequestOptions} requestOptions - Request-specific configuration.
9099
9204
  *
9100
9205
  * @throws {@link Vectros.BadRequestError}
9206
+ * @throws {@link Vectros.PaymentRequiredError}
9101
9207
  * @throws {@link Vectros.ForbiddenError}
9208
+ * @throws {@link Vectros.NotFoundError}
9209
+ * @throws {@link Vectros.ConflictError}
9210
+ * @throws {@link Vectros.ContentTooLargeError}
9211
+ * @throws {@link Vectros.UnprocessableEntityError}
9102
9212
  * @throws {@link Vectros.TooManyRequestsError}
9213
+ * @throws {@link Vectros.InternalServerError}
9214
+ * @throws {@link Vectros.ServiceUnavailableError}
9215
+ * @throws {@link Vectros.GatewayTimeoutError}
9103
9216
  *
9104
9217
  * @example
9105
- * await client.search.content({
9106
- * query: "patient intake form diabetes"
9218
+ * await client.scripts.executeScript({
9219
+ * "Idempotency-Key": "order-8412-attempt",
9220
+ * scriptRef: {
9221
+ * name: "notify-assignee",
9222
+ * version: "3"
9223
+ * }
9107
9224
  * })
9108
9225
  */
9109
- content(request, requestOptions) {
9110
- return HttpResponsePromise.fromPromise(this.__content(request, requestOptions));
9226
+ executeScript(request, requestOptions) {
9227
+ return HttpResponsePromise.fromPromise(this.__executeScript(request, requestOptions));
9111
9228
  }
9112
- async __content(request, requestOptions) {
9229
+ async __executeScript(request, requestOptions) {
9230
+ const { "Idempotency-Key": idempotencyKey, ..._body } = request;
9113
9231
  const _authRequest = await this._options.authProvider.getAuthRequest();
9114
9232
  const _headers = mergeHeaders(
9115
9233
  _authRequest.headers,
9116
9234
  this._options?.headers,
9235
+ mergeOnlyDefinedHeaders({ "Idempotency-Key": idempotencyKey }),
9117
9236
  requestOptions?.headers
9118
9237
  );
9119
9238
  const _response = await fetcher({
9120
9239
  url: url_exports.join(
9121
9240
  await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9122
- "v1/search"
9241
+ "v1/scripts/execute"
9123
9242
  ),
9124
9243
  method: "POST",
9125
9244
  headers: _headers,
9126
9245
  contentType: "application/json",
9127
9246
  queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9128
9247
  requestType: "json",
9129
- body: request,
9248
+ body: _body,
9130
9249
  timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9131
9250
  maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9132
9251
  abortSignal: requestOptions?.abortSignal,
@@ -9140,10 +9259,26 @@ var SearchClient = class {
9140
9259
  switch (_response.error.statusCode) {
9141
9260
  case 400:
9142
9261
  throw new BadRequestError(_response.error.body, _response.rawResponse);
9262
+ case 402:
9263
+ throw new PaymentRequiredError(_response.error.body, _response.rawResponse);
9143
9264
  case 403:
9144
9265
  throw new ForbiddenError(_response.error.body, _response.rawResponse);
9266
+ case 404:
9267
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
9268
+ case 409:
9269
+ throw new ConflictError(_response.error.body, _response.rawResponse);
9270
+ case 413:
9271
+ throw new ContentTooLargeError(_response.error.body, _response.rawResponse);
9272
+ case 422:
9273
+ throw new UnprocessableEntityError(_response.error.body, _response.rawResponse);
9145
9274
  case 429:
9146
9275
  throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
9276
+ case 500:
9277
+ throw new InternalServerError(_response.error.body, _response.rawResponse);
9278
+ case 503:
9279
+ throw new ServiceUnavailableError(_response.error.body, _response.rawResponse);
9280
+ case 504:
9281
+ throw new GatewayTimeoutError(_response.error.body, _response.rawResponse);
9147
9282
  default:
9148
9283
  throw new VectrosError({
9149
9284
  statusCode: _response.error.statusCode,
@@ -9152,101 +9287,879 @@ var SearchClient = class {
9152
9287
  });
9153
9288
  }
9154
9289
  }
9155
- return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/search");
9156
- }
9157
- };
9158
- var VectrosClient = class {
9159
- constructor(options) {
9160
- this._options = normalizeClientOptionsWithAuth(options);
9161
- }
9162
- get auth() {
9163
- return this._auth ?? (this._auth = new AuthClient(this._options));
9164
- }
9165
- get documents() {
9166
- return this._documents ?? (this._documents = new DocumentsClient(this._options));
9167
- }
9168
- get identity() {
9169
- return this._identity ?? (this._identity = new IdentityClient(this._options));
9170
- }
9171
- get compliance() {
9172
- return this._compliance ?? (this._compliance = new ComplianceClient(this._options));
9173
- }
9174
- get folders() {
9175
- return this._folders ?? (this._folders = new FoldersClient(this._options));
9176
- }
9177
- get inference() {
9178
- return this._inference ?? (this._inference = new InferenceClient(this._options));
9179
- }
9180
- get records() {
9181
- return this._records ?? (this._records = new RecordsClient(this._options));
9182
- }
9183
- get schemas() {
9184
- return this._schemas ?? (this._schemas = new SchemasClient(this._options));
9185
- }
9186
- get search() {
9187
- return this._search ?? (this._search = new SearchClient(this._options));
9290
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/scripts/execute");
9188
9291
  }
9189
9292
  /**
9190
- * Make a passthrough request using the SDK's configured auth, retry, logging, etc.
9191
- * This is useful for making requests to endpoints not yet supported in the SDK.
9192
- * The input can be a URL string, URL object, or Request object. Relative paths are resolved against the configured base URL.
9293
+ * Returns a paginated list of your scripts. Pass `name` to list every version of one script name (oldest first); omit it for a flat list across every name in your account (newest first). Results are returned as a `{data, nextCursor}` envelope — pass `nextCursor` as `startFrom` to fetch the next page. Requires the `scripts:r` scope. **Each row's `source` is omitted by default** (`sourceOmitted: true`) — scripts are immutable per version, so a name's version history can otherwise carry every version's complete source in one response. Pass `?includeSource=true` to get it back inline, or fetch one version's full source with a by-id GET. **`?name=<n>&latest=true`** answers "what is the current version of this name" in one bounded call — a single `ScriptResponse` object (not a page), instead of draining every page of the name's version history to find the newest yourself.
9193
9294
  *
9194
- * @param {Request | string | URL} input - The URL, path, or Request object.
9195
- * @param {RequestInit} init - Standard fetch RequestInit options.
9196
- * @param {core.PassthroughRequest.RequestOptions} requestOptions - Per-request overrides (timeout, retries, headers, abort signal).
9197
- * @returns {Promise<Response>} A standard Response object.
9295
+ * @param {Vectros.ListScriptsRequest} request
9296
+ * @param {ScriptsClient.RequestOptions} requestOptions - Request-specific configuration.
9297
+ *
9298
+ * @throws {@link Vectros.BadRequestError}
9299
+ * @throws {@link Vectros.NotFoundError}
9300
+ *
9301
+ * @example
9302
+ * await client.scripts.listScripts({
9303
+ * name: "notify-assignee",
9304
+ * startFrom: "b3BhcXVlLWN1cnNvci1mcm9tLXRoZS1wcmV2aW91cy1wYWdl"
9305
+ * })
9198
9306
  */
9199
- async fetch(input, init, requestOptions) {
9200
- return makePassthroughRequest(
9201
- input,
9202
- init,
9203
- {
9204
- baseUrl: this._options.baseUrl ?? this._options.environment,
9205
- headers: this._options.headers,
9206
- timeoutInSeconds: this._options.timeoutInSeconds,
9207
- maxRetries: this._options.maxRetries,
9208
- fetch: this._options.fetch,
9209
- logging: this._options.logging,
9210
- getAuthHeaders: async () => (await this._options.authProvider.getAuthRequest()).headers
9211
- },
9212
- requestOptions
9213
- );
9214
- }
9215
- };
9216
- var logging;
9217
- ((logging2) => {
9218
- logging2.LogLevel = LogLevel;
9219
- logging2.ConsoleLogger = ConsoleLogger;
9220
- })(logging || (logging = {}));
9221
-
9222
- // src/server.ts
9223
- import {
9224
- CallToolRequestSchema,
9225
- ListResourcesRequestSchema,
9226
- ListToolsRequestSchema,
9227
- ReadResourceRequestSchema
9228
- } from "@modelcontextprotocol/sdk/types.js";
9229
- import { z as z23 } from "zod";
9230
-
9231
- // src/auth.ts
9232
- var KEY_RE = /^(sk|ssk|st)_(live|test)_/;
9233
- var InvalidApiKeyError = class extends Error {
9234
- constructor(reason) {
9235
- super(`Invalid VECTROS_API_KEY: ${reason}`);
9236
- this.name = "InvalidApiKeyError";
9307
+ listScripts(request = {}, requestOptions) {
9308
+ return HttpResponsePromise.fromPromise(this.__listScripts(request, requestOptions));
9237
9309
  }
9238
- };
9239
- function parseApiKey(raw) {
9240
- if (!raw || raw.trim().length === 0) {
9241
- throw new InvalidApiKeyError(
9242
- "env var is missing or empty. Set VECTROS_API_KEY to a Vectros key (recommended: ssk_live_... or ssk_test_...)."
9310
+ async __listScripts(request = {}, requestOptions) {
9311
+ const { name, startFrom, limit, includeSource, latest } = request;
9312
+ const _queryParams = {
9313
+ name,
9314
+ startFrom,
9315
+ limit,
9316
+ includeSource,
9317
+ latest
9318
+ };
9319
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9320
+ const _headers = mergeHeaders(
9321
+ _authRequest.headers,
9322
+ this._options?.headers,
9323
+ requestOptions?.headers
9243
9324
  );
9325
+ const _response = await fetcher({
9326
+ url: url_exports.join(
9327
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9328
+ "v1/scripts"
9329
+ ),
9330
+ method: "GET",
9331
+ headers: _headers,
9332
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
9333
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9334
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9335
+ abortSignal: requestOptions?.abortSignal,
9336
+ fetchFn: this._options?.fetch,
9337
+ logging: this._options.logging
9338
+ });
9339
+ if (_response.ok) {
9340
+ return { data: _response.body, rawResponse: _response.rawResponse };
9341
+ }
9342
+ if (_response.error.reason === "status-code") {
9343
+ switch (_response.error.statusCode) {
9344
+ case 400:
9345
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
9346
+ case 404:
9347
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
9348
+ default:
9349
+ throw new VectrosError({
9350
+ statusCode: _response.error.statusCode,
9351
+ body: _response.error.body,
9352
+ rawResponse: _response.rawResponse
9353
+ });
9354
+ }
9355
+ }
9356
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/scripts");
9244
9357
  }
9245
- const match = raw.match(KEY_RE);
9246
- if (!match) {
9247
- throw new InvalidApiKeyError(
9248
- `key must start with sk_, ssk_, or st_ followed by "live_" or "test_". Got prefix "${raw.slice(0, 12)}...".`
9249
- );
9358
+ /**
9359
+ * Stores a new version of a script object. Every POST creates a genuinely new version — this is NOT idempotent-by-name: pushing `name` again always creates a new row with `scriptVersion` auto-incremented (the first version pushed for a name is 1). `source` is stored as-is: nothing parses or validates it at push time. A version runs when a trigger rule references it (`POST /v1/triggers`) or when `POST /v1/scripts/execute` names it. `provisionedBy` MAY BE SET ON ABSENT, NEVER CHANGED, evaluated against the CURRENT LATEST version of this `name` at push time: if the latest version has no marker recorded, this push may set any value; if the latest version already has one, an omitted value inherits it forward and a DIFFERENT value is refused — a live comparison against whichever version is newest at push time, not a value fixed for the name's whole history. Pushing onto an EXISTING name with no `provisionedBy` recorded on its current latest version additionally requires that you were the caller who pushed that latest version — a name carrying a `provisionedBy` marker is exempt from this check (proving you can supply or inherit the matching marker is itself the ownership proof there). Requires the `scripts:c` scope.
9360
+ *
9361
+ * @param {Vectros.ScriptRequest} request
9362
+ * @param {ScriptsClient.RequestOptions} requestOptions - Request-specific configuration.
9363
+ *
9364
+ * @throws {@link Vectros.BadRequestError}
9365
+ * @throws {@link Vectros.ForbiddenError}
9366
+ * @throws {@link Vectros.ConflictError}
9367
+ * @throws {@link Vectros.TooManyRequestsError}
9368
+ *
9369
+ * @example
9370
+ * await client.scripts.createScript({
9371
+ * name: "notify-assignee",
9372
+ * source: "export default function(input) { return { ok: true }; }"
9373
+ * })
9374
+ */
9375
+ createScript(request, requestOptions) {
9376
+ return HttpResponsePromise.fromPromise(this.__createScript(request, requestOptions));
9377
+ }
9378
+ async __createScript(request, requestOptions) {
9379
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9380
+ const _headers = mergeHeaders(
9381
+ _authRequest.headers,
9382
+ this._options?.headers,
9383
+ requestOptions?.headers
9384
+ );
9385
+ const _response = await fetcher({
9386
+ url: url_exports.join(
9387
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9388
+ "v1/scripts"
9389
+ ),
9390
+ method: "POST",
9391
+ headers: _headers,
9392
+ contentType: "application/json",
9393
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9394
+ requestType: "json",
9395
+ body: request,
9396
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9397
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9398
+ abortSignal: requestOptions?.abortSignal,
9399
+ fetchFn: this._options?.fetch,
9400
+ logging: this._options.logging
9401
+ });
9402
+ if (_response.ok) {
9403
+ return { data: _response.body, rawResponse: _response.rawResponse };
9404
+ }
9405
+ if (_response.error.reason === "status-code") {
9406
+ switch (_response.error.statusCode) {
9407
+ case 400:
9408
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
9409
+ case 403:
9410
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
9411
+ case 409:
9412
+ throw new ConflictError(_response.error.body, _response.rawResponse);
9413
+ case 429:
9414
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
9415
+ default:
9416
+ throw new VectrosError({
9417
+ statusCode: _response.error.statusCode,
9418
+ body: _response.error.body,
9419
+ rawResponse: _response.rawResponse
9420
+ });
9421
+ }
9422
+ }
9423
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/scripts");
9424
+ }
9425
+ /**
9426
+ * Retrieves a single script version by its ID. Requires the `scripts:r` scope.
9427
+ *
9428
+ * @param {Vectros.GetScriptRequest} request
9429
+ * @param {ScriptsClient.RequestOptions} requestOptions - Request-specific configuration.
9430
+ *
9431
+ * @throws {@link Vectros.NotFoundError}
9432
+ *
9433
+ * @example
9434
+ * await client.scripts.getScript({
9435
+ * id: "id"
9436
+ * })
9437
+ */
9438
+ getScript(request, requestOptions) {
9439
+ return HttpResponsePromise.fromPromise(this.__getScript(request, requestOptions));
9440
+ }
9441
+ async __getScript(request, requestOptions) {
9442
+ const { id } = request;
9443
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9444
+ const _headers = mergeHeaders(
9445
+ _authRequest.headers,
9446
+ this._options?.headers,
9447
+ requestOptions?.headers
9448
+ );
9449
+ const _response = await fetcher({
9450
+ url: url_exports.join(
9451
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9452
+ `v1/scripts/${url_exports.encodePathParam(id)}`
9453
+ ),
9454
+ method: "GET",
9455
+ headers: _headers,
9456
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9457
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9458
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9459
+ abortSignal: requestOptions?.abortSignal,
9460
+ fetchFn: this._options?.fetch,
9461
+ logging: this._options.logging
9462
+ });
9463
+ if (_response.ok) {
9464
+ return { data: _response.body, rawResponse: _response.rawResponse };
9465
+ }
9466
+ if (_response.error.reason === "status-code") {
9467
+ switch (_response.error.statusCode) {
9468
+ case 404:
9469
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
9470
+ default:
9471
+ throw new VectrosError({
9472
+ statusCode: _response.error.statusCode,
9473
+ body: _response.error.body,
9474
+ rawResponse: _response.rawResponse
9475
+ });
9476
+ }
9477
+ }
9478
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/scripts/{id}");
9479
+ }
9480
+ /**
9481
+ * Scripts are immutable per version; this endpoint always returns a 400 regardless of scope or credential — push a new version via `POST /v1/scripts` instead.
9482
+ *
9483
+ * @param {Vectros.UpdateScriptRequest} request
9484
+ * @param {ScriptsClient.RequestOptions} requestOptions - Request-specific configuration.
9485
+ *
9486
+ * @throws {@link Vectros.BadRequestError}
9487
+ * @throws {@link Vectros.TooManyRequestsError}
9488
+ *
9489
+ * @example
9490
+ * await client.scripts.updateScript({
9491
+ * id: "id",
9492
+ * body: {
9493
+ * name: "notify-assignee",
9494
+ * source: "export default function(input) { return { ok: true }; }"
9495
+ * }
9496
+ * })
9497
+ */
9498
+ updateScript(request, requestOptions) {
9499
+ return HttpResponsePromise.fromPromise(this.__updateScript(request, requestOptions));
9500
+ }
9501
+ async __updateScript(request, requestOptions) {
9502
+ const { id, body: _body } = request;
9503
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9504
+ const _headers = mergeHeaders(
9505
+ _authRequest.headers,
9506
+ this._options?.headers,
9507
+ requestOptions?.headers
9508
+ );
9509
+ const _response = await fetcher({
9510
+ url: url_exports.join(
9511
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9512
+ `v1/scripts/${url_exports.encodePathParam(id)}`
9513
+ ),
9514
+ method: "PUT",
9515
+ headers: _headers,
9516
+ contentType: "application/json",
9517
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9518
+ requestType: "json",
9519
+ body: _body,
9520
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9521
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9522
+ abortSignal: requestOptions?.abortSignal,
9523
+ fetchFn: this._options?.fetch,
9524
+ logging: this._options.logging
9525
+ });
9526
+ if (_response.ok) {
9527
+ return { data: void 0, rawResponse: _response.rawResponse };
9528
+ }
9529
+ if (_response.error.reason === "status-code") {
9530
+ switch (_response.error.statusCode) {
9531
+ case 400:
9532
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
9533
+ case 429:
9534
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
9535
+ default:
9536
+ throw new VectrosError({
9537
+ statusCode: _response.error.statusCode,
9538
+ body: _response.error.body,
9539
+ rawResponse: _response.rawResponse
9540
+ });
9541
+ }
9542
+ }
9543
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/scripts/{id}");
9544
+ }
9545
+ /**
9546
+ * Permanently deletes one script version by ID. Deleting one version does not affect any other version of the same name. Requires the `scripts:d` scope. Refused with 409 if a live trigger rule still references this version — either directly (a pinned `scriptRef`), or via `"latest"` when this IS the newest version of its name. Delete or re-point those rules first.
9547
+ *
9548
+ * @param {Vectros.DeleteScriptRequest} request
9549
+ * @param {ScriptsClient.RequestOptions} requestOptions - Request-specific configuration.
9550
+ *
9551
+ * @throws {@link Vectros.NotFoundError}
9552
+ * @throws {@link Vectros.ConflictError}
9553
+ * @throws {@link Vectros.TooManyRequestsError}
9554
+ *
9555
+ * @example
9556
+ * await client.scripts.deleteScript({
9557
+ * id: "id"
9558
+ * })
9559
+ */
9560
+ deleteScript(request, requestOptions) {
9561
+ return HttpResponsePromise.fromPromise(this.__deleteScript(request, requestOptions));
9562
+ }
9563
+ async __deleteScript(request, requestOptions) {
9564
+ const { id } = request;
9565
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9566
+ const _headers = mergeHeaders(
9567
+ _authRequest.headers,
9568
+ this._options?.headers,
9569
+ requestOptions?.headers
9570
+ );
9571
+ const _response = await fetcher({
9572
+ url: url_exports.join(
9573
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9574
+ `v1/scripts/${url_exports.encodePathParam(id)}`
9575
+ ),
9576
+ method: "DELETE",
9577
+ headers: _headers,
9578
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9579
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9580
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9581
+ abortSignal: requestOptions?.abortSignal,
9582
+ fetchFn: this._options?.fetch,
9583
+ logging: this._options.logging
9584
+ });
9585
+ if (_response.ok) {
9586
+ return { data: void 0, rawResponse: _response.rawResponse };
9587
+ }
9588
+ if (_response.error.reason === "status-code") {
9589
+ switch (_response.error.statusCode) {
9590
+ case 404:
9591
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
9592
+ case 409:
9593
+ throw new ConflictError(_response.error.body, _response.rawResponse);
9594
+ case 429:
9595
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
9596
+ default:
9597
+ throw new VectrosError({
9598
+ statusCode: _response.error.statusCode,
9599
+ body: _response.error.body,
9600
+ rawResponse: _response.rawResponse
9601
+ });
9602
+ }
9603
+ }
9604
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/v1/scripts/{id}");
9605
+ }
9606
+ };
9607
+ var SearchClient = class {
9608
+ constructor(options) {
9609
+ this._options = normalizeClientOptionsWithAuth(options);
9610
+ }
9611
+ /**
9612
+ * Runs a hybrid, semantic, or text search across the content you have indexed. By default it returns both documents and records in a single unified result set; pass `contentTypes` to narrow the results (for example `["documents"]`). Each result carries a `sourceType` discriminator (`PartnerDocument` or `GenericRecord`) so you can branch on the type. Requires the `search:r` scope.
9613
+ *
9614
+ * @param {Vectros.SearchRequest} request
9615
+ * @param {SearchClient.RequestOptions} requestOptions - Request-specific configuration.
9616
+ *
9617
+ * @throws {@link Vectros.BadRequestError}
9618
+ * @throws {@link Vectros.ForbiddenError}
9619
+ * @throws {@link Vectros.TooManyRequestsError}
9620
+ *
9621
+ * @example
9622
+ * await client.search.content({
9623
+ * query: "patient intake form diabetes"
9624
+ * })
9625
+ */
9626
+ content(request, requestOptions) {
9627
+ return HttpResponsePromise.fromPromise(this.__content(request, requestOptions));
9628
+ }
9629
+ async __content(request, requestOptions) {
9630
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9631
+ const _headers = mergeHeaders(
9632
+ _authRequest.headers,
9633
+ this._options?.headers,
9634
+ requestOptions?.headers
9635
+ );
9636
+ const _response = await fetcher({
9637
+ url: url_exports.join(
9638
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9639
+ "v1/search"
9640
+ ),
9641
+ method: "POST",
9642
+ headers: _headers,
9643
+ contentType: "application/json",
9644
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9645
+ requestType: "json",
9646
+ body: request,
9647
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9648
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9649
+ abortSignal: requestOptions?.abortSignal,
9650
+ fetchFn: this._options?.fetch,
9651
+ logging: this._options.logging
9652
+ });
9653
+ if (_response.ok) {
9654
+ return { data: _response.body, rawResponse: _response.rawResponse };
9655
+ }
9656
+ if (_response.error.reason === "status-code") {
9657
+ switch (_response.error.statusCode) {
9658
+ case 400:
9659
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
9660
+ case 403:
9661
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
9662
+ case 429:
9663
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
9664
+ default:
9665
+ throw new VectrosError({
9666
+ statusCode: _response.error.statusCode,
9667
+ body: _response.error.body,
9668
+ rawResponse: _response.rawResponse
9669
+ });
9670
+ }
9671
+ }
9672
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/search");
9673
+ }
9674
+ };
9675
+ var TriggersClient = class {
9676
+ constructor(options) {
9677
+ this._options = normalizeClientOptionsWithAuth(options);
9678
+ }
9679
+ /**
9680
+ * Returns a page of trigger executions that failed — what went wrong, whether the platform will retry it, and which of your records and rules were involved. Use this to find automation that has stopped running.
9681
+ *
9682
+ * A record appears once per FIRING, not once per attempt: if the platform retries a retryable failure, the same record's `attempts` count rises rather than a new record appearing. **If a retry later succeeds, the record is removed** — so this endpoint describes what is currently broken, not a permanent history. Records also expire 30 days after the firing first failed.
9683
+ *
9684
+ * `detail` is safe to surface to your own users: it carries only your own content (a script's own thrown message) or public API vocabulary, never platform internals. For `INTERNAL_ERROR` it is absent and a `correlationId` is returned instead — quote that to support.
9685
+ *
9686
+ * Scoped to your account and app context, derived from your token — never from input. Requires the `triggers:r` scope.
9687
+ *
9688
+ * @param {Vectros.ListTriggerFailuresRequest} request
9689
+ * @param {TriggersClient.RequestOptions} requestOptions - Request-specific configuration.
9690
+ *
9691
+ * @example
9692
+ * await client.triggers.listTriggerFailures({
9693
+ * ruleId: "3b1c9f2e7a5d8410f6c2e9a1b7d4038f5e6a91c2d7f0b3a4586c9e2f1d0a7b3c",
9694
+ * category: "SCRIPT_ERROR",
9695
+ * startFrom: "b3BhcXVlLWN1cnNvci1mcm9tLXRoZS1wcmV2aW91cy1wYWdl"
9696
+ * })
9697
+ */
9698
+ listTriggerFailures(request = {}, requestOptions) {
9699
+ return HttpResponsePromise.fromPromise(this.__listTriggerFailures(request, requestOptions));
9700
+ }
9701
+ async __listTriggerFailures(request = {}, requestOptions) {
9702
+ const { ruleId, category, retryable, from: from_, to, startFrom, limit } = request;
9703
+ const _queryParams = {
9704
+ ruleId,
9705
+ category,
9706
+ retryable,
9707
+ from: from_,
9708
+ to,
9709
+ startFrom,
9710
+ limit
9711
+ };
9712
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9713
+ const _headers = mergeHeaders(
9714
+ _authRequest.headers,
9715
+ this._options?.headers,
9716
+ requestOptions?.headers
9717
+ );
9718
+ const _response = await fetcher({
9719
+ url: url_exports.join(
9720
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9721
+ "v1/trigger-failures"
9722
+ ),
9723
+ method: "GET",
9724
+ headers: _headers,
9725
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
9726
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9727
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9728
+ abortSignal: requestOptions?.abortSignal,
9729
+ fetchFn: this._options?.fetch,
9730
+ logging: this._options.logging
9731
+ });
9732
+ if (_response.ok) {
9733
+ return { data: _response.body, rawResponse: _response.rawResponse };
9734
+ }
9735
+ if (_response.error.reason === "status-code") {
9736
+ throw new VectrosError({
9737
+ statusCode: _response.error.statusCode,
9738
+ body: _response.error.body,
9739
+ rawResponse: _response.rawResponse
9740
+ });
9741
+ }
9742
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/trigger-failures");
9743
+ }
9744
+ /**
9745
+ * Returns a paginated list of your trigger rules, newest first. Results are returned as a `{data, nextCursor}` envelope — pass `nextCursor` as `startFrom` to fetch the next page. Requires the `triggers:r` scope.
9746
+ *
9747
+ * @param {Vectros.ListTriggersRequest} request
9748
+ * @param {TriggersClient.RequestOptions} requestOptions - Request-specific configuration.
9749
+ *
9750
+ * @example
9751
+ * await client.triggers.listTriggers({
9752
+ * startFrom: "b3BhcXVlLWN1cnNvci1mcm9tLXRoZS1wcmV2aW91cy1wYWdl"
9753
+ * })
9754
+ */
9755
+ listTriggers(request = {}, requestOptions) {
9756
+ return HttpResponsePromise.fromPromise(this.__listTriggers(request, requestOptions));
9757
+ }
9758
+ async __listTriggers(request = {}, requestOptions) {
9759
+ const { startFrom, limit } = request;
9760
+ const _queryParams = {
9761
+ startFrom,
9762
+ limit
9763
+ };
9764
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9765
+ const _headers = mergeHeaders(
9766
+ _authRequest.headers,
9767
+ this._options?.headers,
9768
+ requestOptions?.headers
9769
+ );
9770
+ const _response = await fetcher({
9771
+ url: url_exports.join(
9772
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9773
+ "v1/triggers"
9774
+ ),
9775
+ method: "GET",
9776
+ headers: _headers,
9777
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
9778
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9779
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9780
+ abortSignal: requestOptions?.abortSignal,
9781
+ fetchFn: this._options?.fetch,
9782
+ logging: this._options.logging
9783
+ });
9784
+ if (_response.ok) {
9785
+ return { data: _response.body, rawResponse: _response.rawResponse };
9786
+ }
9787
+ if (_response.error.reason === "status-code") {
9788
+ throw new VectrosError({
9789
+ statusCode: _response.error.statusCode,
9790
+ body: _response.error.body,
9791
+ rawResponse: _response.rawResponse
9792
+ });
9793
+ }
9794
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/triggers");
9795
+ }
9796
+ /**
9797
+ * Declares a new trigger rule, or (with `?upsert=true`) reconciles an existing one of the same name to the submitted shape. Once declared, the rule fires: a record write on the named schema dispatches the referenced script, which runs asynchronously under this rule's own grant. Because that grant is executed, a scoped credential may not declare a trigger whose grant exceeds its own — such a request is rejected with a `403`, and a `roleIds` entry that does not resolve in this context with a `400`. Requires the `triggers:c` scope (also `triggers:u` when `?upsert=true` matches an existing row).
9798
+ *
9799
+ * @param {Vectros.CreateTriggerRequest} request
9800
+ * @param {TriggersClient.RequestOptions} requestOptions - Request-specific configuration.
9801
+ *
9802
+ * @throws {@link Vectros.BadRequestError}
9803
+ * @throws {@link Vectros.ForbiddenError}
9804
+ * @throws {@link Vectros.TooManyRequestsError}
9805
+ *
9806
+ * @example
9807
+ * await client.triggers.createTrigger({
9808
+ * body: {
9809
+ * name: "on-intake-create",
9810
+ * firingSource: {
9811
+ * schemaId: "sch_9f8e7d6c",
9812
+ * event: "CREATE"
9813
+ * },
9814
+ * scriptRef: {
9815
+ * name: "notify-assignee",
9816
+ * version: "3"
9817
+ * }
9818
+ * }
9819
+ * })
9820
+ */
9821
+ createTrigger(request, requestOptions) {
9822
+ return HttpResponsePromise.fromPromise(this.__createTrigger(request, requestOptions));
9823
+ }
9824
+ async __createTrigger(request, requestOptions) {
9825
+ const { upsert, body: _body } = request;
9826
+ const _queryParams = {
9827
+ upsert
9828
+ };
9829
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9830
+ const _headers = mergeHeaders(
9831
+ _authRequest.headers,
9832
+ this._options?.headers,
9833
+ requestOptions?.headers
9834
+ );
9835
+ const _response = await fetcher({
9836
+ url: url_exports.join(
9837
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9838
+ "v1/triggers"
9839
+ ),
9840
+ method: "POST",
9841
+ headers: _headers,
9842
+ contentType: "application/json",
9843
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
9844
+ requestType: "json",
9845
+ body: _body,
9846
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9847
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9848
+ abortSignal: requestOptions?.abortSignal,
9849
+ fetchFn: this._options?.fetch,
9850
+ logging: this._options.logging
9851
+ });
9852
+ if (_response.ok) {
9853
+ return { data: _response.body, rawResponse: _response.rawResponse };
9854
+ }
9855
+ if (_response.error.reason === "status-code") {
9856
+ switch (_response.error.statusCode) {
9857
+ case 400:
9858
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
9859
+ case 403:
9860
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
9861
+ case 429:
9862
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
9863
+ default:
9864
+ throw new VectrosError({
9865
+ statusCode: _response.error.statusCode,
9866
+ body: _response.error.body,
9867
+ rawResponse: _response.rawResponse
9868
+ });
9869
+ }
9870
+ }
9871
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/triggers");
9872
+ }
9873
+ /**
9874
+ * Retrieves a single trigger rule by its ID. Requires the `triggers:r` scope.
9875
+ *
9876
+ * @param {Vectros.GetTriggerRequest} request
9877
+ * @param {TriggersClient.RequestOptions} requestOptions - Request-specific configuration.
9878
+ *
9879
+ * @throws {@link Vectros.NotFoundError}
9880
+ *
9881
+ * @example
9882
+ * await client.triggers.getTrigger({
9883
+ * id: "id"
9884
+ * })
9885
+ */
9886
+ getTrigger(request, requestOptions) {
9887
+ return HttpResponsePromise.fromPromise(this.__getTrigger(request, requestOptions));
9888
+ }
9889
+ async __getTrigger(request, requestOptions) {
9890
+ const { id } = request;
9891
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9892
+ const _headers = mergeHeaders(
9893
+ _authRequest.headers,
9894
+ this._options?.headers,
9895
+ requestOptions?.headers
9896
+ );
9897
+ const _response = await fetcher({
9898
+ url: url_exports.join(
9899
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9900
+ `v1/triggers/${url_exports.encodePathParam(id)}`
9901
+ ),
9902
+ method: "GET",
9903
+ headers: _headers,
9904
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9905
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9906
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9907
+ abortSignal: requestOptions?.abortSignal,
9908
+ fetchFn: this._options?.fetch,
9909
+ logging: this._options.logging
9910
+ });
9911
+ if (_response.ok) {
9912
+ return { data: _response.body, rawResponse: _response.rawResponse };
9913
+ }
9914
+ if (_response.error.reason === "status-code") {
9915
+ switch (_response.error.statusCode) {
9916
+ case 404:
9917
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
9918
+ default:
9919
+ throw new VectrosError({
9920
+ statusCode: _response.error.statusCode,
9921
+ body: _response.error.body,
9922
+ rawResponse: _response.rawResponse
9923
+ });
9924
+ }
9925
+ }
9926
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/triggers/{id}");
9927
+ }
9928
+ /**
9929
+ * Updates an existing trigger rule in place. The rule's resulting grant must be within your own granted scope — including a grant you did not change, because a trigger's other fields (its `scriptRef`, its `principalId`) determine what that grant executes. `name`, `principalId` and `provisionedBy` are immutable once set. Requires the `triggers:u` scope.
9930
+ *
9931
+ * @param {Vectros.UpdateTriggerRequest} request
9932
+ * @param {TriggersClient.RequestOptions} requestOptions - Request-specific configuration.
9933
+ *
9934
+ * @throws {@link Vectros.BadRequestError}
9935
+ * @throws {@link Vectros.ForbiddenError}
9936
+ * @throws {@link Vectros.NotFoundError}
9937
+ * @throws {@link Vectros.TooManyRequestsError}
9938
+ *
9939
+ * @example
9940
+ * await client.triggers.updateTrigger({
9941
+ * id: "id",
9942
+ * body: {
9943
+ * name: "on-intake-create",
9944
+ * firingSource: {
9945
+ * schemaId: "sch_9f8e7d6c",
9946
+ * event: "CREATE"
9947
+ * },
9948
+ * scriptRef: {
9949
+ * name: "notify-assignee",
9950
+ * version: "3"
9951
+ * }
9952
+ * }
9953
+ * })
9954
+ */
9955
+ updateTrigger(request, requestOptions) {
9956
+ return HttpResponsePromise.fromPromise(this.__updateTrigger(request, requestOptions));
9957
+ }
9958
+ async __updateTrigger(request, requestOptions) {
9959
+ const { id, body: _body } = request;
9960
+ const _authRequest = await this._options.authProvider.getAuthRequest();
9961
+ const _headers = mergeHeaders(
9962
+ _authRequest.headers,
9963
+ this._options?.headers,
9964
+ requestOptions?.headers
9965
+ );
9966
+ const _response = await fetcher({
9967
+ url: url_exports.join(
9968
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
9969
+ `v1/triggers/${url_exports.encodePathParam(id)}`
9970
+ ),
9971
+ method: "PUT",
9972
+ headers: _headers,
9973
+ contentType: "application/json",
9974
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
9975
+ requestType: "json",
9976
+ body: _body,
9977
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
9978
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
9979
+ abortSignal: requestOptions?.abortSignal,
9980
+ fetchFn: this._options?.fetch,
9981
+ logging: this._options.logging
9982
+ });
9983
+ if (_response.ok) {
9984
+ return { data: _response.body, rawResponse: _response.rawResponse };
9985
+ }
9986
+ if (_response.error.reason === "status-code") {
9987
+ switch (_response.error.statusCode) {
9988
+ case 400:
9989
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
9990
+ case 403:
9991
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
9992
+ case 404:
9993
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
9994
+ case 429:
9995
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
9996
+ default:
9997
+ throw new VectrosError({
9998
+ statusCode: _response.error.statusCode,
9999
+ body: _response.error.body,
10000
+ rawResponse: _response.rawResponse
10001
+ });
10002
+ }
10003
+ }
10004
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/triggers/{id}");
10005
+ }
10006
+ /**
10007
+ * Permanently deletes one trigger rule by ID. Requires the `triggers:d` scope.
10008
+ *
10009
+ * @param {Vectros.DeleteTriggerRequest} request
10010
+ * @param {TriggersClient.RequestOptions} requestOptions - Request-specific configuration.
10011
+ *
10012
+ * @throws {@link Vectros.NotFoundError}
10013
+ * @throws {@link Vectros.TooManyRequestsError}
10014
+ *
10015
+ * @example
10016
+ * await client.triggers.deleteTrigger({
10017
+ * id: "id"
10018
+ * })
10019
+ */
10020
+ deleteTrigger(request, requestOptions) {
10021
+ return HttpResponsePromise.fromPromise(this.__deleteTrigger(request, requestOptions));
10022
+ }
10023
+ async __deleteTrigger(request, requestOptions) {
10024
+ const { id } = request;
10025
+ const _authRequest = await this._options.authProvider.getAuthRequest();
10026
+ const _headers = mergeHeaders(
10027
+ _authRequest.headers,
10028
+ this._options?.headers,
10029
+ requestOptions?.headers
10030
+ );
10031
+ const _response = await fetcher({
10032
+ url: url_exports.join(
10033
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
10034
+ `v1/triggers/${url_exports.encodePathParam(id)}`
10035
+ ),
10036
+ method: "DELETE",
10037
+ headers: _headers,
10038
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
10039
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
10040
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
10041
+ abortSignal: requestOptions?.abortSignal,
10042
+ fetchFn: this._options?.fetch,
10043
+ logging: this._options.logging
10044
+ });
10045
+ if (_response.ok) {
10046
+ return { data: void 0, rawResponse: _response.rawResponse };
10047
+ }
10048
+ if (_response.error.reason === "status-code") {
10049
+ switch (_response.error.statusCode) {
10050
+ case 404:
10051
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
10052
+ case 429:
10053
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
10054
+ default:
10055
+ throw new VectrosError({
10056
+ statusCode: _response.error.statusCode,
10057
+ body: _response.error.body,
10058
+ rawResponse: _response.rawResponse
10059
+ });
10060
+ }
10061
+ }
10062
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/v1/triggers/{id}");
10063
+ }
10064
+ };
10065
+ var VectrosClient = class {
10066
+ constructor(options) {
10067
+ this._options = normalizeClientOptionsWithAuth(options);
10068
+ }
10069
+ get auth() {
10070
+ return this._auth ?? (this._auth = new AuthClient(this._options));
10071
+ }
10072
+ get documents() {
10073
+ return this._documents ?? (this._documents = new DocumentsClient(this._options));
10074
+ }
10075
+ get identity() {
10076
+ return this._identity ?? (this._identity = new IdentityClient(this._options));
10077
+ }
10078
+ get compliance() {
10079
+ return this._compliance ?? (this._compliance = new ComplianceClient(this._options));
10080
+ }
10081
+ get folders() {
10082
+ return this._folders ?? (this._folders = new FoldersClient(this._options));
10083
+ }
10084
+ get inference() {
10085
+ return this._inference ?? (this._inference = new InferenceClient(this._options));
10086
+ }
10087
+ get records() {
10088
+ return this._records ?? (this._records = new RecordsClient(this._options));
10089
+ }
10090
+ get schemas() {
10091
+ return this._schemas ?? (this._schemas = new SchemasClient(this._options));
10092
+ }
10093
+ get scripts() {
10094
+ return this._scripts ?? (this._scripts = new ScriptsClient(this._options));
10095
+ }
10096
+ get search() {
10097
+ return this._search ?? (this._search = new SearchClient(this._options));
10098
+ }
10099
+ get triggers() {
10100
+ return this._triggers ?? (this._triggers = new TriggersClient(this._options));
10101
+ }
10102
+ /**
10103
+ * Make a passthrough request using the SDK's configured auth, retry, logging, etc.
10104
+ * This is useful for making requests to endpoints not yet supported in the SDK.
10105
+ * The input can be a URL string, URL object, or Request object. Relative paths are resolved against the configured base URL.
10106
+ *
10107
+ * @param {Request | string | URL} input - The URL, path, or Request object.
10108
+ * @param {RequestInit} init - Standard fetch RequestInit options.
10109
+ * @param {core.PassthroughRequest.RequestOptions} requestOptions - Per-request overrides (timeout, retries, headers, abort signal).
10110
+ * @returns {Promise<Response>} A standard Response object.
10111
+ */
10112
+ async fetch(input, init, requestOptions) {
10113
+ return makePassthroughRequest(
10114
+ input,
10115
+ init,
10116
+ {
10117
+ baseUrl: this._options.baseUrl ?? this._options.environment,
10118
+ headers: this._options.headers,
10119
+ timeoutInSeconds: this._options.timeoutInSeconds,
10120
+ maxRetries: this._options.maxRetries,
10121
+ fetch: this._options.fetch,
10122
+ logging: this._options.logging,
10123
+ getAuthHeaders: async () => (await this._options.authProvider.getAuthRequest()).headers
10124
+ },
10125
+ requestOptions
10126
+ );
10127
+ }
10128
+ };
10129
+ var logging;
10130
+ ((logging2) => {
10131
+ logging2.LogLevel = LogLevel;
10132
+ logging2.ConsoleLogger = ConsoleLogger;
10133
+ })(logging || (logging = {}));
10134
+
10135
+ // src/server.ts
10136
+ import {
10137
+ CallToolRequestSchema,
10138
+ ListResourcesRequestSchema,
10139
+ ListToolsRequestSchema,
10140
+ ReadResourceRequestSchema
10141
+ } from "@modelcontextprotocol/sdk/types.js";
10142
+ import { z as z24 } from "zod";
10143
+
10144
+ // src/auth.ts
10145
+ var KEY_RE = /^(sk|ssk|st)_(live|test)_/;
10146
+ var InvalidApiKeyError = class extends Error {
10147
+ constructor(reason) {
10148
+ super(`Invalid VECTROS_API_KEY: ${reason}`);
10149
+ this.name = "InvalidApiKeyError";
10150
+ }
10151
+ };
10152
+ function parseApiKey(raw) {
10153
+ if (!raw || raw.trim().length === 0) {
10154
+ throw new InvalidApiKeyError(
10155
+ "env var is missing or empty. Set VECTROS_API_KEY to a Vectros key (recommended: ssk_live_... or ssk_test_...)."
10156
+ );
10157
+ }
10158
+ const match = raw.match(KEY_RE);
10159
+ if (!match) {
10160
+ throw new InvalidApiKeyError(
10161
+ `key must start with sk_, ssk_, or st_ followed by "live_" or "test_". Got prefix "${raw.slice(0, 12)}...".`
10162
+ );
9250
10163
  }
9251
10164
  return {
9252
10165
  prefix: match[1],
@@ -9270,8 +10183,8 @@ function warnOnSuboptimalKey(key, log) {
9270
10183
 
9271
10184
  // src/build-info.ts
9272
10185
  var BUILD_INFO = {
9273
- mcpServer: true ? "0.16.1" : "dev",
9274
- sdk: true ? "0.42.0" : "dev"
10186
+ mcpServer: true ? "0.17.1" : "dev",
10187
+ sdk: true ? "0.44.0" : "dev"
9275
10188
  };
9276
10189
 
9277
10190
  // src/log.ts
@@ -9579,11 +10492,18 @@ var inputSchema = {
9579
10492
  // Ownership.
9580
10493
  userId: z.string().optional().describe("Restrict to content owned by this user (Vectros UUID)."),
9581
10494
  scope: z.string().optional().describe(
9582
- 'Restrict to content carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "client:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself.'
10495
+ 'Restrict to content carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "client:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself. Mutually exclusive with `scopeFilters` \u2014 use this for ONE dimension.'
10496
+ ),
10497
+ scopeFilters: z.array(z.string()).min(1, "scopeFilters must name at least one dimension when supplied").optional().describe(
10498
+ 'Restrict to content matching ALL of these scope values \u2014 one per namespace \u2014 for a credential whose access spans more than one ownership dimension. e.g. ["org:<uuid>", "client:<uuid>"] narrows to one specific client WITHIN one specific org, which `scope` alone cannot express. Same `namespace:value` form as `scope`; naming the same namespace twice is rejected. Mutually exclusive with `scope` \u2014 use `scope` for a single dimension.'
9583
10499
  ),
9584
10500
  // Date window.
9585
- createdAfter: z.string().optional().describe("Restrict to content created at/after this ISO 8601 UTC timestamp."),
9586
- createdBefore: z.string().optional().describe("Restrict to content created at/before this ISO 8601 UTC timestamp."),
10501
+ createdAfter: z.string().optional().describe(
10502
+ "Restrict to content CREATED at/after this ISO 8601 UTC timestamp \u2014 the item's own creation time, which does NOT move when the item is later re-indexed. One bounded exception: an item matched on its FIRST index may be checked against the moment it was indexed instead, a small allowance for clock skew between creating and indexing it. Do not confuse this with a hit's returned `createdAt`, which is the index timestamp and can be later \u2014 see the tool description."
10503
+ ),
10504
+ createdBefore: z.string().optional().describe(
10505
+ "Restrict to content CREATED at/before this ISO 8601 UTC timestamp \u2014 same creation-time basis, and the same first-index allowance, as createdAfter."
10506
+ ),
9587
10507
  // Relevance tuning.
9588
10508
  minSimilarity: z.number().min(0).max(1).optional().describe("Minimum semantic similarity (0.0\u20131.0); results below are excluded."),
9589
10509
  minTextRelevance: z.number().min(0).max(1).optional().describe("Minimum relative keyword (BM25) relevance (0.0\u20131.0); the keyword-leg analogue of minSimilarity."),
@@ -9598,11 +10518,21 @@ var inputSchema = {
9598
10518
  var hybridSearch = ({ client, log }) => ({
9599
10519
  name: "hybrid_search",
9600
10520
  title: "Hybrid search",
9601
- description: 'Search your tenant\'s indexed content (documents + structured records) using hybrid BM25 + dense ranking. Returns up to `limit` results (default 3, max 50 \u2014 raise it in one call when you can accept the larger result) with citations and surrounding context for grounding follow-up reasoning. Narrow with contentTypes/typeName/filters, ownership (userId/scope), folder scope, a created date window, keyword precision (textMode OR/AND/PHRASE), relevance floors (minSimilarity/minTextRelevance), uniqueDocuments, and requireComplete (fail closed on a degraded backend). Tenant-isolated; the caller\'s scoped key fully constrains which content is visible. ARCHIVED (soft-retracted) documents never appear in results \u2014 fetch them by id via document_get, or restore them via document_update. To stay within the agent context window each hit returns its matched chunkText + a short snippet by default; set includeContext:true for the broader surrounding passage. If the whole result would be too large it is truncated to the top hits (truncated:true). totalResults is the full matching pool and hasMore:true means results remain past this page \u2014 raise limit or advance offset to fetch them. textLegEmpty:true flags that the keyword (BM25) leg matched nothing (all textScores 0) \u2014 typically the default PHRASE mode finding no contiguous match for a long natural-language query. Loosen the keyword leg: shorten the query to its key terms, or set textMode "AND" (all terms, higher precision) or "OR" (any term, broad recall).',
10521
+ description: 'Search your tenant\'s indexed content (documents + structured records) using hybrid BM25 + dense ranking. Returns up to `limit` results (default 3, max 50 \u2014 raise it in one call when you can accept the larger result) with citations and surrounding context for grounding follow-up reasoning. Narrow with contentTypes/typeName/filters, ownership (userId, and scope for ONE ownership dimension or scopeFilters for several at once \u2014 e.g. one client within one org), folder scope, a created date window, keyword precision (textMode OR/AND/PHRASE), relevance floors (minSimilarity/minTextRelevance), uniqueDocuments, and requireComplete (fail closed on a degraded backend). Tenant-isolated; the caller\'s scoped key fully constrains which content is visible. ARCHIVED (soft-retracted) documents AND records are excluded from results \u2014 fetch them by id via document_get/record_get, or restore them by setting status back to ACTIVE. One exception to know: an item archived before the platform enforced this can still be returned here until it is next written to, and nothing sweeps for those \u2014 if an archived item does come back as a hit, re-send status ARCHIVED on it (document_update / record_update) to re-assert the retraction. A hit\'s `createdAt` is when the item entered the search INDEX, which is the moment it was created in the common case but is later for anything re-indexed since \u2014 so do not report it to a user as the creation time; fetch the item with document_get/record_get and read its own createdAt for that. (The createdAfter/createdBefore filters are a separate thing and do filter on true creation time.) To stay within the agent context window each hit returns its matched chunkText + a short snippet by default; set includeContext:true for the broader surrounding passage. If the whole result would be too large it is truncated to the top hits (truncated:true). totalResults is the full matching pool and hasMore:true means results remain past this page \u2014 raise limit or advance offset to fetch them. textLegEmpty:true flags that the keyword (BM25) leg matched nothing (all textScores 0) \u2014 typically the default PHRASE mode finding no contiguous match for a long natural-language query. Loosen the keyword leg: shorten the query to its key terms, or set textMode "AND" (all terms, higher precision) or "OR" (any term, broad recall).',
9602
10522
  inputSchema,
10523
+ // A pure read — never creates, modifies, or deletes anything server-side.
10524
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
9603
10525
  handler: async (args) => {
9604
10526
  const limit = args.limit ?? MCP_DEFAULT_LIMIT;
9605
10527
  const mode = args.mode ?? "HYBRID";
10528
+ if (args.scope !== void 0 && args.scopeFilters !== void 0) {
10529
+ return toolError(
10530
+ "hybrid_search",
10531
+ new Error(
10532
+ "'scope' and 'scopeFilters' are mutually exclusive \u2014 pass 'scope' for a single ownership dimension, or 'scopeFilters' for more than one, not both."
10533
+ )
10534
+ );
10535
+ }
9606
10536
  try {
9607
10537
  const result = await client.search.content({
9608
10538
  query: args.query,
@@ -9617,6 +10547,7 @@ var hybridSearch = ({ client, log }) => ({
9617
10547
  filters: args.filters,
9618
10548
  userId: args.userId,
9619
10549
  scope: args.scope,
10550
+ scopeFilters: args.scopeFilters,
9620
10551
  createdAfter: args.createdAfter,
9621
10552
  createdBefore: args.createdBefore,
9622
10553
  minSimilarity: args.minSimilarity,
@@ -9695,7 +10626,9 @@ async function drainPages(fetchPage) {
9695
10626
  var MCP_DEFAULT_LIMIT2 = 3;
9696
10627
  var MCP_MAX_LIMIT2 = 100;
9697
10628
  var inputSchema2 = {
9698
- type: z2.string().min(1, "type (record type) is required").describe('Record type / schema name (e.g. "patient", "clinical_note").'),
10629
+ type: z2.string().min(1, "type must be non-empty when supplied").optional().describe(
10630
+ 'Record type / schema name (e.g. "patient", "clinical_note"). REQUIRED for a lookup (`field`). In list mode it is one of three ways to choose what to list \u2014 supply `type`, `folderId`, or `recent` \u2014 and it may be combined with `folderId` to list one type within one folder.'
10631
+ ),
9699
10632
  // Lookup-mode args — provide `field` plus EXACTLY ONE of: value | values | from+to | prefix.
9700
10633
  field: z2.string().optional().describe(
9701
10634
  'Lookup mode: name of the lookup-indexed field to query by. `externalId` is always queryable \u2014 e.g. `{type:"control", field:"externalId", value:"ctrl-scoped-key"}` finds the record you created under that externalId. (record_get / record_update also accept externalId directly.) For a SCHEMA-declared composite lookup \u2014 check list_schemas\' lookupFields for a fieldNames entry, not any two fields you pick \u2014 give those field names comma-joined in the declared order (e.g. "status,area"). Use `values` to match on several of those fields at once, or `value` to match on just the FIRST field named (equivalent to a one-element `values`); range/prefix are not valid on a composite field.'
@@ -9717,6 +10650,12 @@ var inputSchema2 = {
9717
10650
  "Lookup mode: sort direction by the looked-up field. `asc` (default) or `desc` \u2014 use `desc` with a range/prefix lookup to get the most-recent / highest values first (e.g. latest-N). Ignored in list mode."
9718
10651
  ),
9719
10652
  // List-mode args:
10653
+ folderId: z2.string().optional().describe(
10654
+ "List mode: list the records filed in this folder (a Vectros folder UUID), regardless of type \u2014 the record-side counterpart of document_query's folderId. Combine with `type` to list a single type within the folder. Use this to see what a folder holds before deleting it: folder_delete refuses a folder that still contains records."
10655
+ ),
10656
+ recent: z2.boolean().optional().describe(
10657
+ "List mode: return the account-wide recently-updated feed across ALL record types, newest first \u2014 a type-agnostic activity view, and the one way to read records without naming a type. Standalone: it cannot be combined with `type`, `folderId`, `userId` or `scope` (the API ignores them here, so this tool rejects the combination rather than silently returning something else). You still see only the record types your credential may read."
10658
+ ),
9720
10659
  userId: z2.string().optional().describe("List mode: scope to records owned by this user."),
9721
10660
  scope: z2.string().optional().describe(
9722
10661
  'List mode: filter to records carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "client:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself.'
@@ -9729,11 +10668,15 @@ var inputSchema2 = {
9729
10668
  var recordQuery = ({ client, log }) => ({
9730
10669
  name: "record_query",
9731
10670
  title: "Record query (list or lookup)",
9732
- description: "Query structured records of a given type. Two modes:\n \u2022 Lookup on a lookup-indexed field: pass `field` plus exactly one of `value` (exact), `values` (exact, composite \u2014 one value per field; a single-element array is the same as `value`), `from`+`to` (range), or `prefix`. `values` with more than one entry, or a comma-joined `field`, ONLY works for a lookup the schema itself declared over several fields together \u2014 check list_schemas' lookupFields for a fieldNames entry, then pass those field names comma-joined as `field`; `from`/`to`/`prefix` are not valid there. Works on sensitive fields too. Optionally narrow an exact match to a window with `sortFrom`/`sortTo`.\n \u2022 List by type: omit `field`; optionally filter by `userId` or `scope` (`namespace:value`).\nReturns a `{ data, nextCursor }` page: `data` holds up to `limit` records (default 3, max 100 \u2014 raise it in one call when you can accept the payload), and a non-null `nextCursor` means more remain \u2014 pass it back as `startFrom` to page. A composite lookup given fewer than its full field count returns records grouped by the unspecified fields, ordered within each group. Mode is auto-detected from the arguments present.",
10671
+ description: "Query structured records of a given type. Two modes:\n \u2022 Lookup on a lookup-indexed field: pass `field` plus exactly one of `value` (exact), `values` (exact, composite \u2014 one value per field; a single-element array is the same as `value`), `from`+`to` (range), or `prefix`. `values` with more than one entry, or a comma-joined `field`, ONLY works for a lookup the schema itself declared over several fields together \u2014 check list_schemas' lookupFields for a fieldNames entry, then pass those field names comma-joined as `field`; `from`/`to`/`prefix` are not valid there. Works on sensitive fields too. Optionally narrow an exact match to a window with `sortFrom`/`sortTo`.\n \u2022 List: omit `field`, then choose ONE of `type` (every record of a type), `folderId` (every record filed in a folder, any type \u2014 combine with `type` for one type within one folder), or `recent` (the account-wide recently-updated feed across every type, newest first \u2014 the only way to read records without naming a type, and standalone: no other filter applies to it). `userId`/`scope` further narrow the type and folder modes.\nReturns a `{ data, nextCursor }` page: `data` holds up to `limit` records (default 3, max 100 \u2014 raise it in one call when you can accept the payload), and a non-null `nextCursor` means more remain \u2014 pass it back as `startFrom` to page. A composite lookup given fewer than its full field count returns records grouped by the unspecified fields, ordered within each group. Mode is auto-detected from the arguments present.",
9733
10672
  inputSchema: inputSchema2,
10673
+ // A pure read — never creates, modifies, or deletes anything server-side.
10674
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
9734
10675
  handler: async (args) => {
9735
10676
  const limit = args.limit ?? MCP_DEFAULT_LIMIT2;
9736
10677
  const type = args.type;
10678
+ const folderId = args.folderId;
10679
+ const recent = args.recent;
9737
10680
  const field = args.field;
9738
10681
  const value = args.value;
9739
10682
  const values = args.values;
@@ -9751,6 +10694,48 @@ var recordQuery = ({ client, log }) => ({
9751
10694
  )
9752
10695
  );
9753
10696
  }
10697
+ if (field && (folderId !== void 0 || recent !== void 0)) {
10698
+ return toolError(
10699
+ "record_query",
10700
+ new Error(
10701
+ "'folderId' and 'recent' are list-mode selectors and do not apply to a lookup ('field') \u2014 a lookup runs within one `type` and would ignore them. Drop `field` to list, or drop these to look up."
10702
+ )
10703
+ );
10704
+ }
10705
+ if (field && !type) {
10706
+ return toolError(
10707
+ "record_query",
10708
+ new Error(
10709
+ "a lookup ('field') is always within one record type \u2014 pass 'type'. To read across types, use list mode with 'folderId' or 'recent'."
10710
+ )
10711
+ );
10712
+ }
10713
+ if (!field) {
10714
+ if (recent && (type !== void 0 || folderId !== void 0)) {
10715
+ return toolError(
10716
+ "record_query",
10717
+ new Error(
10718
+ "'recent' is the account-wide feed across all types and cannot be narrowed \u2014 it is mutually exclusive with 'type' and 'folderId'. Drop 'recent' to list by type/folder."
10719
+ )
10720
+ );
10721
+ }
10722
+ if (recent && (args.userId !== void 0 || args.scope !== void 0)) {
10723
+ return toolError(
10724
+ "record_query",
10725
+ new Error(
10726
+ "'recent' ignores the owner filters \u2014 'userId'/'scope' would be silently dropped. List by 'type' or 'folderId' to filter by owner."
10727
+ )
10728
+ );
10729
+ }
10730
+ if (!recent && type === void 0 && folderId === void 0) {
10731
+ return toolError(
10732
+ "record_query",
10733
+ new Error(
10734
+ "list mode needs one of 'type' (records of a type), 'folderId' (records in a folder, any type), or 'recent' (the account-wide recently-updated feed). Add 'field' to run a lookup."
10735
+ )
10736
+ );
10737
+ }
10738
+ }
9754
10739
  try {
9755
10740
  let page;
9756
10741
  if (field) {
@@ -9814,6 +10799,7 @@ var recordQuery = ({ client, log }) => ({
9814
10799
  }
9815
10800
  }
9816
10801
  page = await client.records.lookupRecordsByBody({
10802
+ // Non-null: the `field && !type` guard above returns before reaching lookup mode.
9817
10803
  type,
9818
10804
  field: normalizedField,
9819
10805
  value,
@@ -9834,13 +10820,22 @@ var recordQuery = ({ client, log }) => ({
9834
10820
  } else {
9835
10821
  page = await client.records.listRecords({
9836
10822
  type,
10823
+ folderId,
10824
+ ...recent ? { recent: "true" } : {},
9837
10825
  userId: args.userId,
9838
10826
  scope: args.scope,
9839
10827
  startFrom,
9840
10828
  limit
9841
10829
  });
9842
10830
  log.debug(
9843
- { tool: "record_query", mode: "list", type, limit, returned: pageItems(page).length },
10831
+ {
10832
+ tool: "record_query",
10833
+ mode: recent ? "list:recent" : folderId ? "list:folder" : "list:type",
10834
+ type,
10835
+ folderId,
10836
+ limit,
10837
+ returned: pageItems(page).length
10838
+ },
9844
10839
  "record_query list ok"
9845
10840
  );
9846
10841
  }
@@ -9922,6 +10917,8 @@ var recordGet = ({ client, log }) => ({
9922
10917
  title: "Get a record by id or externalId",
9923
10918
  description: "Fetch a single structured record, including the full payload. Select it EITHER by its Vectros `id` (e.g. from record_query / hybrid_search) OR by your own `externalId` + `type` \u2014 the same key you passed to record_create, resolved for you (no manual record_query lookup needed). Very large payloads are truncated to protect the agent context window. The response carries the record's processing `indexStatus`; when it is FAILED an `indexFailure.code` explains whether the content is still searchable (e.g. VECTOR_LIMIT_EXCEEDED keeps keyword search vs INDEXING_FAILED = not findable at all) \u2014 branch on the `code`, not the message.",
9924
10919
  inputSchema: inputSchema3,
10920
+ // A pure read — never creates, modifies, or deletes anything server-side.
10921
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
9925
10922
  handler: async (args) => {
9926
10923
  const id = args.id;
9927
10924
  const externalId = args.externalId;
@@ -9967,6 +10964,8 @@ var recordBatchGet = ({ client, log }) => ({
9967
10964
  title: "Get multiple records by id in one call",
9968
10965
  description: "Fetch several structured records by id in a single call (1-100 ids), each with its full payload \u2014 the same hydration record_get gives a single id. Use this instead of N record_get calls when you already hold several ids (e.g. a page of record_query/hybrid_search results). Any id you can't access is silently omitted from `data`; the response also returns `missingIds` \u2014 every requested id not present in `data` \u2014 so you can tell a partial result from a complete one. As with record_get, an oversized payload is truncated into a labelled `payloadPreview` rather than shipped whole.",
9969
10966
  inputSchema: inputSchema4,
10967
+ // A pure read — never creates, modifies, or deletes anything server-side.
10968
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
9970
10969
  handler: async (args) => {
9971
10970
  const ids = args.ids;
9972
10971
  try {
@@ -10017,7 +11016,7 @@ var inputSchema5 = {
10017
11016
  folderId: z5.string().optional().describe("Group this record into a folder."),
10018
11017
  userId: z5.string().optional().describe("Owning user id."),
10019
11018
  scopes: z5.array(z5.string()).optional().describe(
10020
- 'Scope ownership as `namespace:value` entries, at most 2 (e.g. ["org:<uuid>", "group:eng-team"]). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself. This is the record\'s COMPLETE scope declaration and values must come from the credential\'s own identity. An empty array `[]` creates a PRIVATE record owned by the calling user alone. Omit to stamp the credential\'s full identity \u2014 the default.'
11019
+ 'Scope ownership as `namespace:value` entries, at most 2 (e.g. ["org:<uuid>", "group:eng-team"]). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself. This is the record\'s COMPLETE scope declaration, and each entry must fall inside the `data_scope` of a single clause of your credential that also grants this write \u2014 your identity supplies the DEFAULT when you state none, it does not limit which value you may state. An empty array `[]` creates a PRIVATE record owned by the calling user alone. Omit to stamp the credential\'s full identity \u2014 the default.'
10021
11020
  )
10022
11021
  };
10023
11022
  var recordCreate = ({ client, log }) => ({
@@ -10025,6 +11024,13 @@ var recordCreate = ({ client, log }) => ({
10025
11024
  title: "Create a record",
10026
11025
  description: "Create a structured record of a given type. Provide `type` and `fields` (the payload, validated against the type schema \u2014 call list_schemas first to learn required fields and enums). Idempotent by `externalId`. Requires the key to allow records:c (and records:r to receive the existing record on a collision).",
10027
11026
  inputSchema: inputSchema5,
11027
+ // Creates, never modifies or deletes an existing record. Idempotent ONLY when the caller
11028
+ // supplies `externalId` (optional, per the doc comment above) — re-creating with the same
11029
+ // one returns the existing record rather than duplicating it. `externalId` is not required,
11030
+ // so annotated for the less-safe default (omit it, and a retry creates a second record),
11031
+ // not the safer opt-in — same standard applied to record_batch_write, which has the
11032
+ // identical optional-externalId shape.
11033
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
10028
11034
  handler: async (args) => {
10029
11035
  const type = args.type;
10030
11036
  try {
@@ -10050,19 +11056,110 @@ var recordCreate = ({ client, log }) => ({
10050
11056
  });
10051
11057
  var record_create_default = recordCreate;
10052
11058
 
10053
- // src/tools/record_update.ts
11059
+ // src/tools/record_batch_write.ts
10054
11060
  import { z as z6 } from "zod";
10055
- var inputSchema6 = {
10056
- id: z6.string().optional().describe("The Vectros record id to update. Provide this OR externalId+type."),
11061
+ var MCP_MAX_ITEMS = 50;
11062
+ var itemSchema = z6.strictObject({
11063
+ type: z6.string().min(1, "type is required").describe('Record type / schema name (e.g. "task"). Must match an existing schema \u2014 see list_schemas.'),
11064
+ fields: z6.record(z6.string(), z6.unknown()).describe(
11065
+ "The record payload \u2014 a JSON object of field\u2192value, validated against the type schema. Same rules as record_create, including the signed 64-bit range on numbers (send a larger whole number as a STRING)."
11066
+ ),
10057
11067
  externalId: z6.string().optional().describe(
11068
+ 'Stable caller-supplied id, unique per type \u2014 supply it to make a batch safely retryable, since without one a re-submitted item creates a second record. Without `upsert`, an item whose externalId already matches a COMMITTED record comes back `updated` (the idempotent repeat \u2014 nothing was overwritten) if your credential can read that type; a create-only credential gets `conflict` instead, because it may not be shown the existing record. \u26A0\uFE0F Two items sharing ONE externalId WITHIN a single batch are only refused as a `conflict` under atomicity:"all_or_nothing". Under the DEFAULT best_effort each item is written independently, so the second matches what the first just wrote and reports `updated` \u2014 a duplicate key in your input silently collapses two rows into one, counted in `succeeded`, not in `failed`. De-duplicate by externalId before sending, or use all_or_nothing if you need the batch to refuse. A result returns the record\'s `id`, not the record itself; fetch that with record_get/record_batch_get.'
11069
+ ),
11070
+ indexMode: z6.enum(["HYBRID", "SEMANTIC", "TEXT", "NONE"]).optional().describe(
11071
+ "Search-index strategy for this record, set at create only and NOT changeable later. HYBRID (BM25 + dense), SEMANTIC (dense only), TEXT (BM25 only), NONE (store-only \u2014 the record never appears in hybrid_search/rag_ask, though it stays retrievable by id and by structured-field lookup). Omit to inherit the type schema's default; if that default is NONE and you want these records searchable, set it here, because it cannot be fixed after the write."
11072
+ ),
11073
+ status: z6.string().optional().describe("Record lifecycle status. Defaults to ACTIVE server-side."),
11074
+ folderId: z6.string().optional().describe("Group this record into a folder."),
11075
+ userId: z6.string().optional().describe("Owning user id."),
11076
+ scopes: z6.array(z6.string()).optional().describe(
11077
+ "Scope ownership as `namespace:value` entries, at most 2 namespaces. When supplied this is the record's COMPLETE scope declaration, and each entry must fall inside the `data_scope` of a single clause of your credential that also grants this write \u2014 your identity supplies the DEFAULT when you state none, it does not limit which value you may state. `[]` creates a PRIVATE record owned by the calling user alone. Omit to inherit the credential's full identity."
11078
+ )
11079
+ });
11080
+ var inputSchema6 = {
11081
+ items: z6.array(itemSchema).min(1).max(MCP_MAX_ITEMS).describe(
11082
+ `The records to write, 1-${MCP_MAX_ITEMS}. Each item is shaped like a record_create call (\`type\` + \`fields\`, plus the same optional externalId/indexMode/status/folderId/userId/scopes) and is validated and scope-checked individually against its OWN type \u2014 items may mix types.`
11083
+ ),
11084
+ atomicity: z6.enum(["best_effort", "all_or_nothing"]).optional().describe(
11085
+ 'How the batch commits. "best_effort" (the default) writes each item independently \u2014 some can succeed while others fail. "all_or_nothing" commits every item in ONE transaction: if any item fails nothing is written at all, and the items that were themselves fine report status "not_committed". Choose all_or_nothing when the records are interdependent or a half-written set would be worse than none; note it can still be refused as too large to commit atomically even within the item limit, because that transaction is bounded by underlying storage rows rather than by item count (nothing is written when that happens).'
11086
+ ),
11087
+ upsert: z6.boolean().optional().describe(
11088
+ "Applies to every item: when true, an item whose `externalId` already exists OVERWRITES that record instead of returning it unchanged. Needs records:u:<type> in addition to records:c:<type>, checked per item. Default false."
11089
+ ),
11090
+ allowClear: z6.boolean().optional().describe(
11091
+ "Only meaningful with upsert:true, which overwrites as a FULL replacement. If an item's `fields` omits (or nulls) a stored field that only comes back as an indexed projection \u2014 a large record whose payload is stored externally \u2014 the overwrite is refused unless you set this to true to confirm you mean to clear those fields. Default false. To change some fields without clearing the omitted ones, use record_update instead of an upserting batch."
11092
+ )
11093
+ };
11094
+ var recordBatchWrite = ({ client, log }) => ({
11095
+ name: "record_batch_write",
11096
+ title: "Create or upsert multiple records in one call",
11097
+ description: 'Write up to 50 structured records in a single call \u2014 use this instead of N record_create calls when you hold several records (e.g. filing a parsed table, or seeding a set of tasks). Items may mix types; each one is schema-validated, externalId-idempotent and scope-checked individually against its own type (records:c:<type> per item), so a batch cannot write a type you could not write one at a time. `atomicity` chooses the commit shape: "best_effort" (default) writes each item independently; "all_or_nothing" commits every item in one transaction, writing nothing at all if any item fails \u2014 prefer it when a half-written set would be worse than none. IMPORTANT: this call reports success whenever the batch was PROCESSED, including when every item failed \u2014 so always read the per-item `results` and the `succeeded`/`failed` counts rather than treating a non-error result as "all written". This differs from record_create, where a failure is an error result. Results are NOT guaranteed to arrive in the order you submitted: match each one to its item by its `index` (zero-based, the position in your `items` array). A result carries the written record\'s `id` (null on failure) and, when it failed, an `error` with a machine-readable `code` and a human-readable `message` \u2014 read it before resubmitting. It does NOT carry the record itself; fetch that with record_get/record_batch_get. A per-item `status` is created (new record written), updated (an existing record matched \u2014 overwritten only if you passed upsert:true, otherwise returned unchanged, so this is not by itself evidence of a write), conflict (uniqueness or version), invalid (validation \u2014 read `error.message` for which field), forbidden (your credential lacks the scope or ownership that item needed \u2014 fix the credential, not the item), or not_committed (this item was fine but an all_or_nothing batch was aborted by a different item, so resubmitting with that one fixed writes this one unchanged).',
11098
+ inputSchema: inputSchema6,
11099
+ // Creates by default, and can overwrite existing records as a FULL replacement when
11100
+ // `upsert:true` is passed (destructive to whatever fields the old version carried and
11101
+ // this call omits). Idempotent ONLY when every item supplies `externalId` (optional,
11102
+ // per its own field doc above) — re-submitting then converges, with or without
11103
+ // `upsert:true`. `externalId` is not required, so annotated for the less-safe default:
11104
+ // an item with no `externalId` at all has no dedup key, and a resubmit creates a second
11105
+ // record for it regardless of `upsert`. Same standard applied to record_create/
11106
+ // document_ingest's identical optional-externalId shape.
11107
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
11108
+ handler: async (args) => {
11109
+ const items = args.items;
11110
+ const atomicity = args.atomicity;
11111
+ try {
11112
+ const body = {
11113
+ items: items.map((item) => ({
11114
+ typeName: item.type,
11115
+ payload: item.fields,
11116
+ externalId: item.externalId,
11117
+ indexMode: item.indexMode,
11118
+ status: item.status,
11119
+ folderId: item.folderId,
11120
+ userId: item.userId,
11121
+ scopes: item.scopes
11122
+ })),
11123
+ atomicity,
11124
+ upsert: args.upsert,
11125
+ allowClear: args.allowClear
11126
+ };
11127
+ const response = await client.records.batchWriteRecords(body, { maxRetries: 0 });
11128
+ log.debug(
11129
+ {
11130
+ tool: "record_batch_write",
11131
+ submitted: items.length,
11132
+ atomicity: atomicity ?? "best_effort",
11133
+ succeeded: response.succeeded,
11134
+ failed: response.failed
11135
+ },
11136
+ "record_batch_write ok"
11137
+ );
11138
+ return { content: [{ type: "text", text: JSON.stringify(response, null, 2) }] };
11139
+ } catch (err) {
11140
+ log.warn(
11141
+ { tool: "record_batch_write", itemCount: items?.length, err: String(err) },
11142
+ "record_batch_write failed"
11143
+ );
11144
+ return toolError("record_batch_write", err);
11145
+ }
11146
+ }
11147
+ });
11148
+ var record_batch_write_default = recordBatchWrite;
11149
+
11150
+ // src/tools/record_update.ts
11151
+ import { z as z7 } from "zod";
11152
+ var inputSchema7 = {
11153
+ id: z7.string().optional().describe("The Vectros record id to update. Provide this OR externalId+type."),
11154
+ externalId: z7.string().optional().describe(
10058
11155
  "Your caller-owned externalId \u2014 an alternative selector to `id` (requires `type`). Updates the record you created under that externalId without a manual record_query lookup first."
10059
11156
  ),
10060
- type: z6.string().optional().describe("Record type \u2014 REQUIRED when selecting by `externalId` (externalId is unique within a type)."),
10061
- fields: z6.record(z6.string(), z6.unknown()).describe(
11157
+ type: z7.string().optional().describe("Record type \u2014 REQUIRED when selecting by `externalId` (externalId is unique within a type)."),
11158
+ fields: z7.record(z7.string(), z7.unknown()).describe(
10062
11159
  "Field\u2192value changes DEEP-MERGED into the existing payload: keys you send overwrite (recursing into nested objects), a key set to `null` is deleted, and unspecified fields are preserved."
10063
11160
  ),
10064
- status: z6.string().optional().describe("Set the record lifecycle status (e.g. ARCHIVED) \u2014 archive/workflow without physical deletion."),
10065
- expectedVersion: z6.number().int().optional().describe(
11161
+ status: z7.string().optional().describe("Set the record lifecycle status (e.g. ARCHIVED) \u2014 archive/workflow without physical deletion."),
11162
+ expectedVersion: z7.number().int().optional().describe(
10066
11163
  "Optimistic concurrency: the version you last read. If the record changed since, the update is refused as a conflict (re-read and retry). Omit for last-write-wins."
10067
11164
  )
10068
11165
  };
@@ -10070,7 +11167,11 @@ var recordUpdate = ({ client, log }) => ({
10070
11167
  name: "record_update",
10071
11168
  title: "Update a record by id or externalId",
10072
11169
  description: "Update a record \u2014 select it by its Vectros `id` OR by your own `externalId` + `type` (the same key you passed to record_create, resolved for you). The provided `fields` are DEEP-MERGED into the existing payload (unspecified fields are preserved; a field set to `null` is deleted). Pass `expectedVersion` (the version you last read) for safe concurrent edits \u2014 a stale update is refused (409). Use `status` to archive without deleting. Requires the key to allow records:u.",
10073
- inputSchema: inputSchema6,
11170
+ inputSchema: inputSchema7,
11171
+ // A JSON Merge Patch — overwrites the fields it names, so it can destroy a prior field
11172
+ // value the caller did not mean to lose. Re-applying the same patch converges to the
11173
+ // same state, so it is idempotent.
11174
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
10074
11175
  handler: async (args) => {
10075
11176
  const id = args.id;
10076
11177
  const externalId = args.externalId;
@@ -10096,15 +11197,19 @@ var recordUpdate = ({ client, log }) => ({
10096
11197
  var record_update_default = recordUpdate;
10097
11198
 
10098
11199
  // src/tools/record_delete.ts
10099
- import { z as z7 } from "zod";
10100
- var inputSchema7 = {
10101
- id: z7.string().min(1, "id is required").describe("The Vectros record id to delete.")
11200
+ import { z as z8 } from "zod";
11201
+ var inputSchema8 = {
11202
+ id: z8.string().min(1, "id is required").describe("The Vectros record id to delete.")
10102
11203
  };
10103
11204
  var recordDelete = ({ client, log }) => ({
10104
11205
  name: "record_delete",
10105
11206
  title: "Delete a record",
10106
11207
  description: "Permanently delete a record by id (leaves a tombstone). Requires the key to allow records:d \u2014 a key without it gets a permission error. To archive without deleting, use record_update to set status instead.",
10107
- inputSchema: inputSchema7,
11208
+ inputSchema: inputSchema8,
11209
+ // Deletes (leaves a tombstone server-side, but the record is gone from every normal
11210
+ // read path). Idempotent in the standard REST sense: the end state ("this id no longer
11211
+ // resolves") is the same whether this is the first delete or a repeat of one.
11212
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
10108
11213
  handler: async (args) => {
10109
11214
  const id = args.id;
10110
11215
  try {
@@ -10120,49 +11225,72 @@ var recordDelete = ({ client, log }) => ({
10120
11225
  var record_delete_default = recordDelete;
10121
11226
 
10122
11227
  // src/tools/rag_ask.ts
10123
- import { z as z8 } from "zod";
11228
+ import { z as z9 } from "zod";
10124
11229
  var SEARCH_MCP_DEFAULT_LIMIT = 5;
10125
11230
  var SEARCH_MCP_MAX_LIMIT = 50;
10126
- var inputSchema8 = {
10127
- query: z8.string().min(1, "query must be non-empty").describe("Question to ground against retrieved content."),
10128
- instructions: z8.string().optional().describe(
11231
+ var inputSchema9 = {
11232
+ query: z9.string().min(1, "query must be non-empty").describe("Question to ground against retrieved content."),
11233
+ instructions: z9.string().optional().describe(
10129
11234
  'System prompt that overrides the default for the generation step \u2014 e.g. "answer only from the provided context, cite sources, be concise". Default: a generic answer-from-context instruction.'
10130
11235
  ),
10131
- model: z8.string().optional().describe(
11236
+ model: z9.string().optional().describe(
10132
11237
  "Inference model alias (e.g. claude-haiku-4-5, claude-sonnet-5, claude-opus-4-8). Default = tier-appropriate Haiku. See GET /v1/models for the catalog the calling key can reach."
10133
11238
  ),
10134
- search: z8.object({
10135
- mode: z8.enum(["HYBRID", "TEXT", "SEMANTIC"]).optional().describe("Retrieval mode. Default HYBRID."),
10136
- limit: z8.number().int().min(1).max(SEARCH_MCP_MAX_LIMIT).optional().describe(
11239
+ search: z9.object({
11240
+ mode: z9.enum(["HYBRID", "TEXT", "SEMANTIC"]).optional().describe("Retrieval mode. Default HYBRID."),
11241
+ limit: z9.number().int().min(1).max(SEARCH_MCP_MAX_LIMIT).optional().describe(
10137
11242
  `Passages to retrieve before generating (the grounding-corpus size). Default ${SEARCH_MCP_DEFAULT_LIMIT}; raise up to ${SEARCH_MCP_MAX_LIMIT} (the RAG search API max) for a broader corpus when the extra grounding is worth the larger prompt.`
10138
11243
  ),
10139
11244
  // Retrieval scoping — parity with hybrid_search so an agent can ground the
10140
11245
  // answer on a specific owner / folder / type / metadata subset, not just the
10141
11246
  // whole-tenant corpus.
10142
- userId: z8.string().optional().describe("Restrict retrieval to content owned by this user (Vectros UUID)."),
10143
- scope: z8.string().optional().describe(
10144
- 'Restrict retrieval to content carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "client:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself.'
11247
+ userId: z9.string().optional().describe("Restrict retrieval to content owned by this user (Vectros UUID)."),
11248
+ scope: z9.string().optional().describe(
11249
+ 'Restrict retrieval to content carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "client:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself. Mutually exclusive with `scopeFilters` \u2014 use this for ONE dimension.'
10145
11250
  ),
10146
- folderId: z8.string().optional().describe("Restrict retrieval to this exact folder."),
10147
- rootFolderId: z8.string().optional().describe("Restrict retrieval to this folder and all its descendants."),
10148
- typeName: z8.string().optional().describe("Restrict record retrieval to this schema type."),
10149
- contentTypes: z8.array(z8.enum(["documents", "records"])).optional().describe('Narrow retrieval to content types. ["documents"] or ["records"]; omit for both.'),
10150
- filters: z8.record(z8.unknown()).optional().describe(
11251
+ scopeFilters: z9.array(z9.string()).min(1, "scopeFilters must name at least one dimension when supplied").optional().describe(
11252
+ 'Restrict retrieval to content matching ALL of these scope values \u2014 one per namespace \u2014 for a credential whose access spans more than one ownership dimension. e.g. ["org:<uuid>", "client:<uuid>"] grounds the answer on one specific client WITHIN one specific org, which `scope` alone cannot express. Naming the same namespace twice is rejected. Mutually exclusive with `scope`.'
11253
+ ),
11254
+ folderId: z9.string().optional().describe("Restrict retrieval to this exact folder."),
11255
+ rootFolderId: z9.string().optional().describe("Restrict retrieval to this folder and all its descendants."),
11256
+ typeName: z9.string().optional().describe("Restrict record retrieval to this schema type."),
11257
+ contentTypes: z9.array(z9.enum(["documents", "records"])).optional().describe('Narrow retrieval to content types. ["documents"] or ["records"]; omit for both.'),
11258
+ filters: z9.record(z9.unknown()).optional().describe(
10151
11259
  'Field-level metadata filters (AND-combined). Value = scalar (equality), array (OR-set), or operator map ($eq/$ne/$gt/$gte/$lt/$lte, $in/$nin). e.g. {"status":"open"}.'
10152
11260
  ),
10153
- createdAfter: z8.string().optional().describe("Restrict to content created at/after this ISO 8601 UTC timestamp."),
10154
- createdBefore: z8.string().optional().describe("Restrict to content created at/before this ISO 8601 UTC timestamp."),
10155
- requireComplete: z8.boolean().optional().describe("Fail closed (503) on a degraded search backend instead of grounding on partial results. Default false.")
11261
+ createdAfter: z9.string().optional().describe(
11262
+ "Restrict retrieval to content CREATED at/after this ISO 8601 UTC timestamp \u2014 the item's own creation time, which does not move when it is re-indexed. An item matched on its FIRST index may be checked against its index time instead, a bounded clock-skew allowance."
11263
+ ),
11264
+ createdBefore: z9.string().optional().describe("Same creation-time basis as createdAfter, bounding at/before this ISO 8601 UTC value."),
11265
+ requireComplete: z9.boolean().optional().describe("Fail closed (503) on a degraded search backend instead of grounding on partial results. Default false.")
10156
11266
  }).optional().describe("Retrieval params + scoping. Default mode HYBRID, limit " + SEARCH_MCP_DEFAULT_LIMIT + "."),
10157
- maxTokens: z8.number().int().min(1).optional().describe("Max output tokens."),
10158
- temperature: z8.number().min(0).max(1).optional().describe("Sampling temperature (0.0\u20131.0). Default 0.3 \u2014 lower favors deterministic, retrieval-grounded answers.")
11267
+ maxTokens: z9.number().int().min(1).optional().describe("Max output tokens."),
11268
+ temperature: z9.number().min(0).max(1).optional().describe("Sampling temperature (0.0\u20131.0). Default 0.3 \u2014 lower favors deterministic, retrieval-grounded answers.")
10159
11269
  };
10160
11270
  var ragAsk = ({ client, log }) => ({
10161
11271
  name: "rag_ask",
10162
11272
  title: "RAG ask (corpus-wide)",
10163
- description: "Ask a question grounded against your tenant's indexed content. Vectros performs a hybrid search, injects the top-K passages into the prompt, and streams a model answer back. Scope retrieval with `search` (ownership, folder, type, metadata filters, date window) to ground on a subset \u2014 e.g. one patient or one folder \u2014 and steer generation with `instructions` / `temperature`. The full answer is returned as a single response; progress notifications keep the call alive during the 30-45s generation window. Inference runs in-perimeter against AWS Bedrock \u2014 PHI never leaves the BAA boundary.",
10164
- inputSchema: inputSchema8,
11273
+ description: "Ask a question grounded against your tenant's indexed content. Vectros performs a hybrid search, injects the top-K passages into the prompt, and streams a model answer back. Scope retrieval with `search` (ownership \u2014 `scope` for one ownership dimension or `scopeFilters` for several at once, e.g. one client within one org \u2014 folder, type, metadata filters, date window) to ground on a subset \u2014 e.g. one patient or one folder \u2014 and steer generation with `instructions` / `temperature`. The full answer is returned as a single response; progress notifications keep the call alive during the 30-45s generation window. Inference runs in-perimeter against AWS Bedrock \u2014 PHI never leaves the BAA boundary.",
11274
+ inputSchema: inputSchema9,
11275
+ // NOT a pure read: this call reserves an atomic hold against the caller's prepaid inference
11276
+ // balance before generation starts, then debits it on completion — a real financial side
11277
+ // effect that can trigger a configured auto-recharge against the tenant's card.
11278
+ // `readOnlyHint:true` would let a host
11279
+ // skip a confirmation prompt on a call with real, unbounded-under-retry spend; ordinary reads
11280
+ // that merely meter usage stay `readOnlyHint:true` (hybrid_search has no inference-cost leg),
11281
+ // but a call that can debit a balance and possibly charge a card is a different class. Not
11282
+ // idempotent either: every repeat charges again, and generation is non-deterministic.
11283
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
10165
11284
  handler: async (args, extra) => {
11285
+ const rawSearch = args.search ?? {};
11286
+ if (rawSearch.scope !== void 0 && rawSearch.scopeFilters !== void 0) {
11287
+ return toolError(
11288
+ "rag_ask",
11289
+ new Error(
11290
+ "search.scope and search.scopeFilters are mutually exclusive \u2014 pass 'scope' for a single ownership dimension, or 'scopeFilters' for more than one, not both."
11291
+ )
11292
+ );
11293
+ }
10166
11294
  try {
10167
11295
  const searchArg = args.search ?? {};
10168
11296
  const search = {
@@ -10170,6 +11298,7 @@ var ragAsk = ({ client, log }) => ({
10170
11298
  limit: searchArg.limit ?? SEARCH_MCP_DEFAULT_LIMIT,
10171
11299
  userId: searchArg.userId,
10172
11300
  scope: searchArg.scope,
11301
+ scopeFilters: searchArg.scopeFilters,
10173
11302
  folderId: searchArg.folderId,
10174
11303
  rootFolderId: searchArg.rootFolderId,
10175
11304
  typeName: searchArg.typeName,
@@ -10237,20 +11366,29 @@ var ragAsk = ({ client, log }) => ({
10237
11366
  var rag_ask_default = ragAsk;
10238
11367
 
10239
11368
  // src/tools/document_ask.ts
10240
- import { z as z9 } from "zod";
10241
- var inputSchema9 = {
10242
- documentId: z9.string().min(1, "documentId is required").describe("ID of the document to ask against."),
10243
- prompt: z9.string().min(1, "prompt is required").describe("Question to ask about the document."),
10244
- model: z9.string().optional().describe(
11369
+ import { z as z10 } from "zod";
11370
+ var inputSchema10 = {
11371
+ documentId: z10.string().min(1, "documentId is required").describe("ID of the document to ask against."),
11372
+ prompt: z10.string().min(1, "prompt is required").describe("Question to ask about the document."),
11373
+ model: z10.string().optional().describe(
10245
11374
  "Inference model alias. Default = tier-appropriate Haiku. See GET /v1/models for the catalog the calling key can reach."
10246
11375
  ),
10247
- maxTokens: z9.number().int().min(1).optional().describe("Max output tokens.")
11376
+ maxTokens: z10.number().int().min(1).optional().describe("Max output tokens.")
10248
11377
  };
10249
11378
  var documentAsk = ({ client, log }) => ({
10250
11379
  name: "document_ask",
10251
11380
  title: "Document ask (single-document)",
10252
11381
  description: "Ask a question against a single indexed document. Returns a grounded answer with the document context that informed it. For documents exceeding the input-token cap, the API returns a structured 413 with `estimatedTokens` and `limitTokens`. Inference runs in-perimeter against AWS Bedrock \u2014 PHI never leaves the BAA boundary.",
10253
- inputSchema: inputSchema9,
11382
+ inputSchema: inputSchema10,
11383
+ // NOT a pure read: this call reserves an atomic hold against the caller's prepaid inference
11384
+ // balance before generation starts, then debits it on completion — a real financial side
11385
+ // effect that can trigger a configured auto-recharge against the tenant's card.
11386
+ // `readOnlyHint:true` would let a host
11387
+ // skip a confirmation prompt on a call with real, unbounded-under-retry spend; ordinary reads
11388
+ // that merely meter usage stay `readOnlyHint:true` (hybrid_search has no inference-cost leg),
11389
+ // but a call that can debit a balance and possibly charge a card is a different class. Not
11390
+ // idempotent either: every repeat charges again, and generation is non-deterministic.
11391
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
10254
11392
  handler: async (args, extra) => {
10255
11393
  try {
10256
11394
  const stream = await client.inference.documentAsk({
@@ -10309,18 +11447,18 @@ var documentAsk = ({ client, log }) => ({
10309
11447
  var document_ask_default = documentAsk;
10310
11448
 
10311
11449
  // src/tools/list_schemas.ts
10312
- import { z as z10 } from "zod";
10313
- var inputSchema10 = {
10314
- userId: z10.string().optional().describe(
11450
+ import { z as z11 } from "zod";
11451
+ var inputSchema11 = {
11452
+ userId: z11.string().optional().describe(
10315
11453
  "Filter to schemas visible to a specific user. Optional; default returns all schemas the credential can see."
10316
11454
  ),
10317
- scope: z10.string().optional().describe(
11455
+ scope: z11.string().optional().describe(
10318
11456
  'Filter to schemas carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other. Optional; default returns all schemas the credential can see.'
10319
11457
  ),
10320
- surface: z10.enum(["record", "document", "user", "entity"]).optional().describe(
11458
+ surface: z11.enum(["record", "document", "user", "entity"]).optional().describe(
10321
11459
  "Filter to schemas bindable to this surface \u2014 e.g. `document` to list only document types, or `record` for record types. Identity entities in any namespace (org/client/one you registered) bind under the single `entity` surface; `user` and `entity` are account-wide. Optional."
10322
11460
  ),
10323
- recordType: z10.string().optional().describe(
11461
+ recordType: z11.string().optional().describe(
10324
11462
  'Resolve the single schema for this record type (its natural handle, e.g. "patient") instead of listing \u2014 returns a one-element result, or empty if none. Combine with `surface=user|entity` for an identity schema. Takes precedence over userId. Optional.'
10325
11463
  )
10326
11464
  };
@@ -10328,7 +11466,9 @@ var listSchemas = ({ client, log }) => ({
10328
11466
  name: "list_schemas",
10329
11467
  title: "List record schemas",
10330
11468
  description: 'List the structured-record schema catalog for your tenant. Each schema describes a record type (e.g. "patient", "clinical_note") \u2014 its fields, lookup-indexed fields, and capabilities. Use this to discover what record types exist before calling `record_query`. Filter with `surface` (record/document/user/entity \u2014 e.g. only document types), `recordType` (resolve one schema by its type name), or `userId`/`scope`; default returns everything the credential can see.',
10331
- inputSchema: inputSchema10,
11469
+ inputSchema: inputSchema11,
11470
+ // A pure read — never creates, modifies, or deletes anything server-side.
11471
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
10332
11472
  handler: async (args) => {
10333
11473
  const userId = args.userId;
10334
11474
  const scope = args.scope;
@@ -10354,18 +11494,18 @@ var listSchemas = ({ client, log }) => ({
10354
11494
  var list_schemas_default = listSchemas;
10355
11495
 
10356
11496
  // src/tools/document_get.ts
10357
- import { z as z11 } from "zod";
11497
+ import { z as z12 } from "zod";
10358
11498
  var MAX_TEXT_CHARS = 32e3;
10359
- var inputSchema11 = {
10360
- documentId: z11.string().optional().describe("The document ID returned by document_ingest or hybrid_search. Provide this OR externalId+type."),
10361
- externalId: z11.string().optional().describe(
11499
+ var inputSchema12 = {
11500
+ documentId: z12.string().optional().describe("The document ID returned by document_ingest or hybrid_search. Provide this OR externalId+type."),
11501
+ externalId: z12.string().optional().describe(
10362
11502
  "Your caller-owned externalId \u2014 an alternative selector to `documentId` (requires `type`). Fetches the document you ingested under that externalId without a manual lookup first."
10363
11503
  ),
10364
- type: z11.string().optional().describe("Document type \u2014 REQUIRED when selecting by `externalId` (externalId is unique within a type)."),
10365
- includeText: z11.boolean().optional().describe(
11504
+ type: z12.string().optional().describe("Document type \u2014 REQUIRED when selecting by `externalId` (externalId is unique within a type)."),
11505
+ includeText: z12.boolean().optional().describe(
10366
11506
  "If true, fetch and include the document text (capped at ~8K tokens, truncated: true flag if cut). Default false \u2014 metadata only. For larger documents, prefer `document_ask` over dumping text into context."
10367
11507
  ),
10368
- includeDownloadUrl: z11.boolean().optional().describe(
11508
+ includeDownloadUrl: z12.boolean().optional().describe(
10369
11509
  "If true, also return a short-lived presigned `downloadUrl` for the original file (file-backed documents only \u2014 the way to retrieve the raw bytes of a document ingested via file mode). Default false. Unavailable for text-only documents \u2014 `downloadAvailable: false` is set instead."
10370
11510
  )
10371
11511
  };
@@ -10382,7 +11522,9 @@ var documentGet = ({ client, log }) => ({
10382
11522
  name: "document_get",
10383
11523
  title: "Get document metadata (and optionally text)",
10384
11524
  description: "Fetch metadata for a single document \u2014 select it by its Vectros `documentId` OR by your own `externalId` + `type` (resolved for you). Pass `includeText: true` to also fetch the text body (capped at ~8K tokens; `truncated: true` flag if cut). Text is available for every text-ingested document and for file-ingested documents unless they were uploaded with `storeText: false` (extracted text discarded after indexing) \u2014 then `textAvailable: false` is set; the original file is still retrievable via `includeDownloadUrl`. Pass `includeDownloadUrl: true` to also get a short-lived presigned `downloadUrl` for the original file (file-backed documents only). Returns the full document metadata, including its lifecycle `status` (ACTIVE, or ARCHIVED when soft-retracted from search \u2014 restorable via document_update) and its processing `indexStatus`. When `indexStatus` is FAILED the response also carries `indexFailure` with a machine-readable `code` telling you whether the content is still findable \u2014 e.g. TEXT_INDEX_FAILED / VECTOR_LIMIT_EXCEEDED (one leg still serves it) vs INDEXING_FAILED (not findable by search at all). Branch on `code`, not on the message.",
10385
- inputSchema: inputSchema11,
11525
+ inputSchema: inputSchema12,
11526
+ // A pure read — never creates, modifies, or deletes anything server-side.
11527
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
10386
11528
  handler: async (args) => {
10387
11529
  const documentId = args.documentId;
10388
11530
  const externalId = args.externalId;
@@ -10447,28 +11589,28 @@ var documentGet = ({ client, log }) => ({
10447
11589
  var document_get_default = documentGet;
10448
11590
 
10449
11591
  // src/tools/document_query.ts
10450
- import { z as z12 } from "zod";
11592
+ import { z as z13 } from "zod";
10451
11593
  var MCP_DEFAULT_LIMIT3 = 3;
10452
11594
  var MCP_MAX_LIMIT3 = 100;
10453
- var inputSchema12 = {
11595
+ var inputSchema13 = {
10454
11596
  // Lookup-mode args — provide `field` plus EXACTLY ONE of: value | from+to | prefix.
10455
- field: z12.string().optional().describe("Lookup mode: name of the lookup-indexed field to query by."),
10456
- value: z12.string().optional().describe("Lookup mode (equality): exact-match value for `field`. Works on sensitive fields too."),
10457
- from: z12.string().optional().describe("Lookup mode (range): inclusive lower bound; requires `to`. Range-enabled, non-sensitive fields only."),
10458
- to: z12.string().optional().describe("Lookup mode (range): inclusive upper bound; requires `from`."),
10459
- prefix: z12.string().optional().describe("Lookup mode (prefix): match values starting with this. Range-enabled string fields only."),
10460
- order: z12.enum(["asc", "desc"]).optional().describe(
11597
+ field: z13.string().optional().describe("Lookup mode: name of the lookup-indexed field to query by."),
11598
+ value: z13.string().optional().describe("Lookup mode (equality): exact-match value for `field`. Works on sensitive fields too."),
11599
+ from: z13.string().optional().describe("Lookup mode (range): inclusive lower bound; requires `to`. Range-enabled, non-sensitive fields only."),
11600
+ to: z13.string().optional().describe("Lookup mode (range): inclusive upper bound; requires `from`."),
11601
+ prefix: z13.string().optional().describe("Lookup mode (prefix): match values starting with this. Range-enabled string fields only."),
11602
+ order: z13.enum(["asc", "desc"]).optional().describe(
10461
11603
  "Lookup mode: sort direction by the looked-up field. `asc` (default) or `desc` \u2014 use `desc` with a range/prefix lookup to get the most-recent / highest values first (e.g. latest-N). Ignored in list mode."
10462
11604
  ),
10463
- type: z12.string().optional().describe("Lookup mode: the document type (the bound schema's type). Required with `field`."),
11605
+ type: z13.string().optional().describe("Lookup mode: the document type (the bound schema's type). Required with `field`."),
10464
11606
  // List-mode args:
10465
- folderId: z12.string().optional().describe("List mode: only documents in this folder (Vectros folder id)."),
10466
- userId: z12.string().optional().describe("List mode: scope to documents owned by this user."),
10467
- scope: z12.string().optional().describe(
11607
+ folderId: z13.string().optional().describe("List mode: only documents in this folder (Vectros folder id)."),
11608
+ userId: z13.string().optional().describe("List mode: scope to documents owned by this user."),
11609
+ scope: z13.string().optional().describe(
10468
11610
  'List mode: filter to documents carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "client:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself.'
10469
11611
  ),
10470
- startFrom: z12.string().optional().describe("Pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch the next. Works in both list and lookup mode."),
10471
- limit: z12.number().int().min(1).max(MCP_MAX_LIMIT3).optional().describe(
11612
+ startFrom: z13.string().optional().describe("Pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch the next. Works in both list and lookup mode."),
11613
+ limit: z13.number().int().min(1).max(MCP_MAX_LIMIT3).optional().describe(
10472
11614
  `Max documents per page. Defaults to a low ${MCP_DEFAULT_LIMIT3} to protect the agent context window; raise up to ${MCP_MAX_LIMIT3} (the documents API max) in one call when you can accept the larger payload, or page with \`startFrom\` instead.`
10473
11615
  )
10474
11616
  };
@@ -10476,7 +11618,9 @@ var documentQuery = ({ client, log }) => ({
10476
11618
  name: "document_query",
10477
11619
  title: "Document query (list or lookup)",
10478
11620
  description: "Query document metadata. Two modes:\n \u2022 Lookup on a lookup-indexed field: pass `type` and `field` plus exactly one of `value` (exact), `from`+`to` (range), or `prefix`. Works on sensitive fields (equality only there); range/prefix need a range-enabled field.\n \u2022 List: omit `field`; optionally filter by `folderId`/`userId`/`scope` (`namespace:value`).\nReturns a `{ data, nextCursor }` page: `data` holds up to `limit` documents (default 3, max 100 \u2014 raise it in one call when you can accept the payload), and a non-null `nextCursor` means more remain \u2014 pass it back as `startFrom` to page. Mode is auto-detected. Use document_get for the full text/download URL of one document.",
10479
- inputSchema: inputSchema12,
11621
+ inputSchema: inputSchema13,
11622
+ // A pure read — never creates, modifies, or deletes anything server-side.
11623
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
10480
11624
  handler: async (args) => {
10481
11625
  const limit = args.limit ?? MCP_DEFAULT_LIMIT3;
10482
11626
  const field = args.field;
@@ -10556,29 +11700,29 @@ var documentQuery = ({ client, log }) => ({
10556
11700
  var document_query_default = documentQuery;
10557
11701
 
10558
11702
  // src/tools/document_update.ts
10559
- import { z as z13 } from "zod";
10560
- var inputSchema13 = {
10561
- documentId: z13.string().optional().describe("The Vectros document id to update. Provide this OR externalId+type."),
10562
- externalId: z13.string().optional().describe(
11703
+ import { z as z14 } from "zod";
11704
+ var inputSchema14 = {
11705
+ documentId: z14.string().optional().describe("The Vectros document id to update. Provide this OR externalId+type."),
11706
+ externalId: z14.string().optional().describe(
10563
11707
  "Your caller-owned externalId \u2014 an alternative selector to `documentId` (requires `type`). Updates the document you ingested under that externalId without a manual lookup first."
10564
11708
  ),
10565
- type: z13.string().optional().describe("Document type \u2014 REQUIRED when selecting by `externalId` (externalId is unique within a type)."),
10566
- title: z13.string().optional().describe("New title. Omit to keep the current title."),
10567
- fields: z13.record(z13.string(), z13.unknown()).optional().describe(
11709
+ type: z14.string().optional().describe("Document type \u2014 REQUIRED when selecting by `externalId` (externalId is unique within a type)."),
11710
+ title: z14.string().optional().describe("New title. Omit to keep the current title."),
11711
+ fields: z14.record(z14.string(), z14.unknown()).optional().describe(
10568
11712
  "Typed-payload field\u2192value changes DEEP-MERGED into the existing payload (a field set to `null` is deleted; unspecified fields preserved). Omit to leave the payload unchanged."
10569
11713
  ),
10570
- text: z13.string().optional().describe(
11714
+ text: z14.string().optional().describe(
10571
11715
  "New raw text body. Supplying it re-ingests the document body and re-queues it for indexing, so the search index reflects the edit (text-ingested documents only \u2014 not file-backed ones). Omit to leave the stored text unchanged. This is the in-place alternative to re-ingesting with upsert:true."
10572
11716
  ),
10573
- folderId: z13.string().optional().describe("Move the document into this folder (cannot be cleared once set)."),
10574
- status: z13.enum(["ACTIVE", "ARCHIVED"]).optional().describe(
11717
+ folderId: z14.string().optional().describe("Move the document into this folder (cannot be cleared once set)."),
11718
+ status: z14.enum(["ACTIVE", "ARCHIVED"]).optional().describe(
10575
11719
  "Lifecycle status. `ARCHIVED` soft-retracts the document \u2014 it is pulled from search and recall but kept and recoverable; set it back to `ACTIVE` to re-index and restore it. The way to retire superseded content when the credential has no delete authority. Omit to leave unchanged."
10576
11720
  ),
10577
- userId: z13.string().optional().describe("Reassign the owning user (Vectros UUID)."),
10578
- scopes: z13.array(z13.string()).optional().describe(
11721
+ userId: z14.string().optional().describe("Reassign the owning user (Vectros UUID)."),
11722
+ scopes: z14.array(z14.string()).optional().describe(
10579
11723
  'Reassign scope ownership as `namespace:value` entries, at most 2 (e.g. ["org:<uuid>", "group:eng-team"]) \u2014 the COMPLETE new parent set. `org`/`client` are reserved namespace names, registered like any other. Omit to leave ownership unchanged; `[]` clears it (private to the owning user).'
10580
11724
  ),
10581
- expectedVersion: z13.number().int().optional().describe(
11725
+ expectedVersion: z14.number().int().optional().describe(
10582
11726
  "Optimistic concurrency: the version you last read. If the document changed since, the update is refused as a conflict (re-read and retry). Omit for last-write-wins."
10583
11727
  )
10584
11728
  };
@@ -10586,7 +11730,11 @@ var documentUpdate = ({ client, log }) => ({
10586
11730
  name: "document_update",
10587
11731
  title: "Update a document",
10588
11732
  description: 'Update a document \u2014 select it by its Vectros `documentId` OR by your own `externalId` + `type` (resolved for you). `fields` are DEEP-MERGED into the existing typed payload (unspecified fields preserved; a field set to `null` is deleted); title/folderId/status/ownership are updated when provided and preserved otherwise. Supply `text` to re-ingest and re-index the document body in place (text documents only). Set `status: "ARCHIVED"` to soft-retract a document (pulled from search, kept and recoverable) and `status: "ACTIVE"` to restore it. Pass `expectedVersion` (the version you last read) for safe concurrent edits \u2014 a stale update is refused (409). Requires the key to allow documents:u.',
10589
- inputSchema: inputSchema13,
11733
+ inputSchema: inputSchema14,
11734
+ // A JSON Merge Patch — overwrites the fields it names, so it can destroy a prior field
11735
+ // value the caller did not mean to lose. Re-applying the same patch converges to the
11736
+ // same state, so it is idempotent.
11737
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
10590
11738
  handler: async (args) => {
10591
11739
  const documentId = args.documentId;
10592
11740
  const externalId = args.externalId;
@@ -10626,15 +11774,18 @@ var documentUpdate = ({ client, log }) => ({
10626
11774
  var document_update_default = documentUpdate;
10627
11775
 
10628
11776
  // src/tools/document_delete.ts
10629
- import { z as z14 } from "zod";
10630
- var inputSchema14 = {
10631
- documentId: z14.string().min(1, "documentId is required").describe("The Vectros document id to delete.")
11777
+ import { z as z15 } from "zod";
11778
+ var inputSchema15 = {
11779
+ documentId: z15.string().min(1, "documentId is required").describe("The Vectros document id to delete.")
10632
11780
  };
10633
11781
  var documentDelete = ({ client, log }) => ({
10634
11782
  name: "document_delete",
10635
11783
  title: "Delete a document",
10636
11784
  description: 'Permanently delete a document by id (removes it and its indexed content). Requires the key to allow documents:d \u2014 a key without it gets a permission error. To archive without deleting, use document_update to set status: "ARCHIVED" instead (recoverable, and needs no delete authority).',
10637
- inputSchema: inputSchema14,
11785
+ inputSchema: inputSchema15,
11786
+ // Deletes. Idempotent in the standard REST sense: the end state ("this id no longer
11787
+ // resolves") is the same whether this is the first delete or a repeat of one.
11788
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
10638
11789
  handler: async (args) => {
10639
11790
  const documentId = args.documentId;
10640
11791
  try {
@@ -10652,18 +11803,18 @@ var documentDelete = ({ client, log }) => ({
10652
11803
  var document_delete_default = documentDelete;
10653
11804
 
10654
11805
  // src/tools/folder_query.ts
10655
- import { z as z15 } from "zod";
11806
+ import { z as z16 } from "zod";
10656
11807
  var MCP_DEFAULT_LIMIT4 = 10;
10657
11808
  var MCP_MAX_LIMIT4 = 100;
10658
- var inputSchema15 = {
10659
- id: z15.string().optional().describe("Get mode: fetch this single folder by id."),
10660
- parentId: z15.string().optional().describe("List mode: direct children of this folder (tree navigation). Omit for a flat tenant list."),
10661
- userId: z15.string().optional().describe("List mode: scope to folders owned by this user."),
10662
- scope: z15.string().optional().describe(
11809
+ var inputSchema16 = {
11810
+ id: z16.string().optional().describe("Get mode: fetch this single folder by id."),
11811
+ parentId: z16.string().optional().describe("List mode: direct children of this folder (tree navigation). Omit for a flat tenant list."),
11812
+ userId: z16.string().optional().describe("List mode: scope to folders owned by this user."),
11813
+ scope: z16.string().optional().describe(
10663
11814
  'List mode: filter to folders carrying this scope value, in `namespace:value` form (e.g. "org:<uuid>", "client:<uuid>", "group:eng-team"). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself.'
10664
11815
  ),
10665
- startFrom: z15.string().optional().describe("List mode: pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch the next."),
10666
- limit: z15.number().int().min(1).max(MCP_MAX_LIMIT4).optional().describe(
11816
+ startFrom: z16.string().optional().describe("List mode: pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch the next."),
11817
+ limit: z16.number().int().min(1).max(MCP_MAX_LIMIT4).optional().describe(
10667
11818
  `List mode: max folders per page. Default 10; raise up to ${MCP_MAX_LIMIT4} (the folders API max) in one call when you can accept the larger page, or page with \`startFrom\`.`
10668
11819
  )
10669
11820
  };
@@ -10671,7 +11822,9 @@ var folderQuery = ({ client, log }) => ({
10671
11822
  name: "folder_query",
10672
11823
  title: "Folder query (list or get)",
10673
11824
  description: "Read folders. Two modes:\n \u2022 Get: pass `id` \u2192 returns the single folder.\n \u2022 List: omit `id`; pass `parentId` for a folder's direct children (tree navigation) or omit for a flat tenant list. Optionally filter by `userId` or `scope` (`namespace:value`).\nList mode returns `{ data, nextCursor }` (default 10, max 100 per page \u2014 raise it in one call when you can accept the larger page); a non-null `nextCursor` means more remain \u2014 pass it back as `startFrom` to page through all folders. Get mode returns the single folder object.",
10674
- inputSchema: inputSchema15,
11825
+ inputSchema: inputSchema16,
11826
+ // A pure read — never creates, modifies, or deletes anything server-side.
11827
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
10675
11828
  handler: async (args) => {
10676
11829
  const id = args.id;
10677
11830
  try {
@@ -10701,22 +11854,34 @@ var folderQuery = ({ client, log }) => ({
10701
11854
  var folder_query_default = folderQuery;
10702
11855
 
10703
11856
  // src/tools/folder_create.ts
10704
- import { z as z16 } from "zod";
10705
- var inputSchema16 = {
10706
- name: z16.string().min(1, "name is required").describe("Folder display name."),
10707
- description: z16.string().optional().describe("Optional description of the folder's purpose."),
10708
- parentId: z16.string().optional().describe("Parent folder id \u2014 places the folder under this parent. Omit for the context default root. Create-only."),
10709
- slug: z16.string().optional().describe("Optional stable slug (sibling-unique; idempotency key). Lowercase letters/digits/hyphens. Derived from name when omitted."),
10710
- userId: z16.string().optional().describe("Owning user (Vectros UUID)."),
10711
- scopes: z16.array(z16.string()).optional().describe(
11857
+ import { z as z17 } from "zod";
11858
+ var inputSchema17 = {
11859
+ name: z17.string().min(1, "name is required").describe("Folder display name."),
11860
+ description: z17.string().optional().describe("Optional description of the folder's purpose."),
11861
+ parentId: z17.string().optional().describe("Parent folder id \u2014 places the folder under this parent. Omit for the context default root. Create-only."),
11862
+ slug: z17.string().optional().describe(
11863
+ "Optional stable slug (sibling-unique; idempotency key). Lowercase letters/digits/hyphens. SUPPLY THIS to make a retry safe \u2014 if omitted, a derived slug is only ever a freshly-proved-free one, so a redelivered call creates a new sibling folder every time rather than matching the first."
11864
+ ),
11865
+ userId: z17.string().optional().describe("Owning user (Vectros UUID)."),
11866
+ scopes: z17.array(z17.string()).optional().describe(
10712
11867
  'Scope ownership as `namespace:value` entries, at most 2 (e.g. ["org:<uuid>", "group:eng-team"]). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself. This is the folder\'s COMPLETE scope declaration and values must come from the credential\'s own identity. An empty array `[]` creates a PRIVATE folder owned by the calling user alone. Omit to stamp the credential\'s full identity \u2014 the default.'
10713
11868
  )
10714
11869
  };
10715
11870
  var folderCreate = ({ client, log }) => ({
10716
11871
  name: "folder_create",
10717
11872
  title: "Create a folder",
10718
- description: "Create a folder to organize documents and records. Pass `parentId` to nest it (create-only \u2014 folders cannot be moved later). Idempotent by `slug` within the parent. Requires the key to allow folders:c (and folders:r to receive the existing folder on a collision).",
10719
- inputSchema: inputSchema16,
11873
+ description: "Create a folder to organize documents and records. Pass `parentId` to nest it (create-only \u2014 folders cannot be moved later). Idempotent by `slug` within the parent ONLY when you pass `slug` explicitly \u2014 omitting it derives a fresh, always-free slug on every call, so a retry creates a new sibling folder rather than matching the first. Requires the key to allow folders:c (and folders:r to receive the existing folder on a collision).",
11874
+ inputSchema: inputSchema17,
11875
+ // Idempotent ONLY when the caller supplies `slug` explicitly (see the doc comment above): an
11876
+ // omitted slug is derived through a collision-probing suffix loop that returns only a
11877
+ // freshly-proved-free value, so the idempotency check running after that derivation can never
11878
+ // match on the default path. `slug` is optional, so this is annotated for the less-safe default —
11879
+ // the same standard applied to record_create/document_ingest/record_batch_write's identical
11880
+ // optional-dedupe-key shape. (A prior version of this annotation claimed unconditional
11881
+ // idempotency, reasoning that the derived slug made this tool "genuinely structurally different"
11882
+ // from the optional-externalId tools — that reasoning was wrong: the derivation is unconditional,
11883
+ // but it is unconditionally NON-colliding by construction, which is the opposite property.)
11884
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
10720
11885
  handler: async (args) => {
10721
11886
  try {
10722
11887
  const folder = await client.folders.createFolder({
@@ -10740,16 +11905,16 @@ var folderCreate = ({ client, log }) => ({
10740
11905
  var folder_create_default = folderCreate;
10741
11906
 
10742
11907
  // src/tools/folder_update.ts
10743
- import { z as z17 } from "zod";
10744
- var inputSchema17 = {
10745
- id: z17.string().min(1, "id is required").describe("The Vectros folder id to update."),
10746
- name: z17.string().optional().describe("New folder name. Omit to keep the current name."),
10747
- description: z17.string().optional().describe("New description. Omit to leave unchanged."),
10748
- userId: z17.string().optional().describe("Reassign the owning user (Vectros UUID)."),
10749
- scopes: z17.array(z17.string()).optional().describe(
11908
+ import { z as z18 } from "zod";
11909
+ var inputSchema18 = {
11910
+ id: z18.string().min(1, "id is required").describe("The Vectros folder id to update."),
11911
+ name: z18.string().optional().describe("New folder name. Omit to keep the current name."),
11912
+ description: z18.string().optional().describe("New description. Omit to leave unchanged."),
11913
+ userId: z18.string().optional().describe("Reassign the owning user (Vectros UUID)."),
11914
+ scopes: z18.array(z18.string()).optional().describe(
10750
11915
  'Reassign scope ownership as `namespace:value` entries, at most 2 (e.g. ["org:<uuid>", "group:eng-team"]) \u2014 the COMPLETE new parent set. `org`/`client` are reserved namespace names, registered like any other. Omit to leave ownership unchanged; `[]` clears it (private to the owning user).'
10751
11916
  ),
10752
- expectedVersion: z17.number().int().optional().describe(
11917
+ expectedVersion: z18.number().int().optional().describe(
10753
11918
  "Optimistic concurrency: the version you last read. If the folder changed since, the update is refused as a conflict (re-read and retry). Omit for last-write-wins."
10754
11919
  )
10755
11920
  };
@@ -10757,7 +11922,11 @@ var folderUpdate = ({ client, log }) => ({
10757
11922
  name: "folder_update",
10758
11923
  title: "Update a folder",
10759
11924
  description: "Update a folder's name / description / ownership by id (RFC-7386 merge \u2014 omitted fields preserved). Pass `expectedVersion` (the version you last read) for safe concurrent edits \u2014 a stale update is refused (409). Folders cannot be moved (re-parenting is not supported by the API). Requires the key to allow folders:u.",
10760
- inputSchema: inputSchema17,
11925
+ inputSchema: inputSchema18,
11926
+ // A JSON Merge Patch — overwrites the fields it names, so it can destroy a prior field
11927
+ // value the caller did not mean to lose. Re-applying the same patch converges to the
11928
+ // same state, so it is idempotent.
11929
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
10761
11930
  handler: async (args) => {
10762
11931
  const id = args.id;
10763
11932
  const name = args.name;
@@ -10784,15 +11953,18 @@ var folderUpdate = ({ client, log }) => ({
10784
11953
  var folder_update_default = folderUpdate;
10785
11954
 
10786
11955
  // src/tools/folder_delete.ts
10787
- import { z as z18 } from "zod";
10788
- var inputSchema18 = {
10789
- id: z18.string().min(1, "id is required").describe("The Vectros folder id to delete.")
11956
+ import { z as z19 } from "zod";
11957
+ var inputSchema19 = {
11958
+ id: z19.string().min(1, "id is required").describe("The Vectros folder id to delete.")
10790
11959
  };
10791
11960
  var folderDelete = ({ client, log }) => ({
10792
11961
  name: "folder_delete",
10793
11962
  title: "Delete a folder",
10794
- description: "Permanently delete a folder by id. Requires the key to allow folders:d \u2014 a key without it gets a permission error. Protected folders (e.g. a context root) cannot be deleted.",
10795
- inputSchema: inputSchema18,
11963
+ description: 'Permanently delete a folder by id. The folder must be EMPTY first \u2014 it must contain no documents, no records, and no sub-folders \u2014 and a non-empty folder is refused, which is the most common way this call fails. Use record_query with this folderId, and document_query, to see what is in it. Clearing it differs by content type: a document can be moved out (document_update with a different folderId) or deleted. A RECORD can also be re-filed into another folder \u2014 the API supports it \u2014 but THIS SERVER does not expose that yet: record_update has no folderId argument, so from here your only option is record_delete (needs records:d). Do NOT read that as "the record cannot be moved" and delete partner data on that basis: if the record should be kept, move it with the Vectros API/SDK directly rather than deleting it here. A sub-folder cannot be re-parented at all, so nested folders have to be emptied and deleted innermost-first. Note the emptiness check counts everything in the folder, INCLUDING items your credential cannot read \u2014 so a refusal you cannot account for from what you can list is expected behaviour, not a bug, and retrying will not clear it. Requires the key to allow folders:d \u2014 a key without it gets a permission error. Protected folders (e.g. a context root) cannot be deleted at all, however empty.',
11964
+ inputSchema: inputSchema19,
11965
+ // Deletes. Idempotent in the standard REST sense: the end state ("this id no longer
11966
+ // resolves") is the same whether this is the first delete or a repeat of one.
11967
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
10796
11968
  handler: async (args) => {
10797
11969
  const id = args.id;
10798
11970
  try {
@@ -10808,14 +11980,16 @@ var folderDelete = ({ client, log }) => ({
10808
11980
  var folder_delete_default = folderDelete;
10809
11981
 
10810
11982
  // src/tools/current_identity.ts
10811
- var inputSchema19 = {
11983
+ var inputSchema20 = {
10812
11984
  // No args — current_identity describes the current credential.
10813
11985
  };
10814
11986
  var currentIdentity = ({ log, apiKey, environment }) => ({
10815
11987
  name: "current_identity",
10816
11988
  title: "Current identity (tenant + principal scope)",
10817
11989
  description: "Describe the credential the MCP server is operating under. Returns tenantId, environment (staging|production), principalType (root_key|scoped_key|token), principalKeyId, principalLabel, and (for scoped credentials) allowedActions plus dataScope \u2014 the credential's verb+ownership reach as { userId, scopes[] }, where each scope is a `namespace:value` string (e.g. \"org:<uuid>\"). Note: this does not yet include granted_capabilities (member-lifecycle / forensic-read / context-directory-read / delegate-mint, as of API 0.40.0, joined by delegate-principal-stamp in 0.42.0) \u2014 a separate reach dimension a scope clause can carry that /v1/ping does not report yet, so allowedActions+dataScope may understate a credential's true reach. Also reports mcpServerVersion (this server's own package version) and sdkVersion (the bundled @vectros-ai/sdk version) so a caller can tell what build it's talking to. Use this when the user asks 'what can you do here?', 'what tenant am I in?', or 'what version is this?'. Calls GET /v1/ping under the hood.",
10818
- inputSchema: inputSchema19,
11990
+ inputSchema: inputSchema20,
11991
+ // A pure read (/v1/ping) — never creates, modifies, or deletes anything server-side.
11992
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
10819
11993
  handler: async () => {
10820
11994
  try {
10821
11995
  const identity = await resolveIdentity({ log, apiKey, environment });
@@ -10831,7 +12005,7 @@ var currentIdentity = ({ log, apiKey, environment }) => ({
10831
12005
  var current_identity_default = currentIdentity;
10832
12006
 
10833
12007
  // src/tools/document_ingest.ts
10834
- import { z as z19 } from "zod";
12008
+ import { z as z20 } from "zod";
10835
12009
  import { readFile, realpath } from "fs/promises";
10836
12010
  import { basename, extname, resolve, relative, isAbsolute } from "path";
10837
12011
  var IngestPathError = class extends Error {
@@ -10906,37 +12080,37 @@ function inferMimeType(filePath) {
10906
12080
  const ext = extname(filePath).toLowerCase();
10907
12081
  return EXT_TO_MIME[ext] ?? "application/octet-stream";
10908
12082
  }
10909
- var inputSchema20 = {
10910
- title: z19.string().min(1, "title is required").describe("Human-readable document title \u2014 appears in search results and the UI."),
10911
- indexMode: z19.enum(["HYBRID", "SEMANTIC", "TEXT", "NONE"]).optional().describe(
12083
+ var inputSchema21 = {
12084
+ title: z20.string().min(1, "title is required").describe("Human-readable document title \u2014 appears in search results and the UI."),
12085
+ indexMode: z20.enum(["HYBRID", "SEMANTIC", "TEXT", "NONE"]).optional().describe(
10912
12086
  "Index strategy. HYBRID (BM25 + dense, default; best for general retrieval), SEMANTIC (dense only; concept-driven queries), TEXT (BM25 only; exact-match / keyword), NONE (store-only / archival \u2014 retrievable by id and structured-field lookup but never in search results). Omit to inherit the bound schema's default."
10913
12087
  ),
10914
- externalId: z19.string().optional().describe(
12088
+ externalId: z20.string().optional().describe(
10915
12089
  'Stable caller-supplied id. Immutable; unique per type within your context. Re-ingesting with the same externalId returns the existing document (idempotent) instead of creating a duplicate \u2014 use it to make ingests safely retryable and as the key other records reference. Mirrors record_create. Receiving the existing document back is a read of it and needs documents:r in addition to documents:c; a create-only key gets an "already exists" error instead of the document.'
10916
12090
  ),
10917
- upsert: z19.boolean().optional().describe(
12091
+ upsert: z20.boolean().optional().describe(
10918
12092
  "When true, re-ingesting an existing externalId OVERWRITES that document and re-indexes the new body (text mode) / re-uploads and re-indexes the new file (file mode), instead of returning the existing one unchanged. This is the curation/re-sync primitive: edit a source, re-ingest with upsert:true, and the search index reflects the new content. Requires the documents:u scope. IMPORTANT: pass the SAME schemaId (and type) you used originally \u2014 externalId is unique WITHIN a type, so omitting schemaId resolves in the untyped namespace and mints a duplicate instead of updating. The response `created` flag confirms which happened (created:true = a new document was minted)."
10919
12093
  ),
10920
- schemaId: z19.string().optional().describe(
12094
+ schemaId: z20.string().optional().describe(
10921
12095
  "Bind this document to a record schema. When set, `payload` is validated against the schema and its lookup fields become directly queryable via document_query (records parity). Resolve a schema id from its type via list_schemas. Omit for an untyped document."
10922
12096
  ),
10923
- payload: z19.record(z19.string(), z19.unknown()).optional().describe(
12097
+ payload: z20.record(z20.string(), z20.unknown()).optional().describe(
10924
12098
  "The document's structured data \u2014 a flat key/value object. With `schemaId`, declared fields are validated and lookup fields indexed; undeclared keys pass through as free-form and are searchable via the hybrid_search `filters` param. Without a schema it is stored as free-form metadata. Every number must fall within the signed 64-bit range \u2014 send a larger whole number as a STRING (stored exactly, exact-match lookup), else the ingest is refused with a 400 naming the field."
10925
12099
  ),
10926
12100
  // Inline text mode (mutually exclusive with filePath):
10927
- text: z19.string().min(1).optional().describe("Text body to ingest inline. Mutually exclusive with filePath. Either text or filePath is required."),
10928
- storeText: z19.boolean().optional().describe(
12101
+ text: z20.string().min(1).optional().describe("Text body to ingest inline. Mutually exclusive with filePath. Either text or filePath is required."),
12102
+ storeText: z20.boolean().optional().describe(
10929
12103
  "FILE MODE ONLY. Whether the uploaded file's EXTRACTED text is retained after indexing (default true), fixed at ingest. true keeps the extracted text retrievable via document_get(includeText:true) and usable by document_ask; false discards it once indexing completes \u2014 search still works and the original file remains downloadable, but includeText returns textAvailable:false and document_ask is unavailable. NOT accepted with `text`: a text-ingested body is the document itself and is ALWAYS retained, so the backend has no storeText knob on the text path \u2014 passing it with `text` is rejected rather than silently ignored."
10930
12104
  ),
10931
12105
  // File upload mode (mutually exclusive with text; stdio-transport-only):
10932
- filePath: z19.string().min(1).optional().describe(
12106
+ filePath: z20.string().min(1).optional().describe(
10933
12107
  "Local filesystem path to upload. Mutually exclusive with text. STDIO TRANSPORT ONLY \u2014 rejected on HTTP transport (remote MCP servers can't read your filesystem; use text mode or call the SDK's uploadDocument directly). Must resolve INSIDE the configured ingest root (VECTROS_MCP_INGEST_ROOT, else the server's working directory); paths that escape it (traversal/absolute/symlink) or match a sensitive pattern are rejected."
10934
12108
  ),
10935
- fileType: z19.string().optional().describe('MIME type of the file (e.g. "application/pdf"). Inferred from filePath extension if omitted.'),
12109
+ fileType: z20.string().optional().describe('MIME type of the file (e.g. "application/pdf"). Inferred from filePath extension if omitted.'),
10936
12110
  // Common (both modes):
10937
- folderId: z19.string().optional().describe("Optional folder to ingest into. Default: tenant root."),
10938
- userId: z19.string().optional().describe("Owning user ID. Optional."),
10939
- scopes: z19.array(z19.string()).optional().describe(
12111
+ folderId: z20.string().optional().describe("Optional folder to ingest into. Default: tenant root."),
12112
+ userId: z20.string().optional().describe("Owning user ID. Optional."),
12113
+ scopes: z20.array(z20.string()).optional().describe(
10940
12114
  "TEXT MODE ONLY. Scope ownership as `namespace:value` entries, at most 2 (e.g. [\"org:<uuid>\", \"group:eng-team\"]). `org` and `client` are reserved namespace names, registered like any other; others are namespaces you registered yourself. This is the document's COMPLETE scope declaration and values must come from the credential's own identity. An empty array `[]` creates a PRIVATE document owned by the calling user alone. Omit to stamp the credential's full identity \u2014 the default. Rejected with `filePath` (file uploads do not accept a scope declaration): a file-uploaded document is stamped with the credential's full identity."
10941
12115
  )
10942
12116
  };
@@ -10944,7 +12118,17 @@ var documentIngest = ({ client, log, transport, ingestRoot }) => ({
10944
12118
  name: "document_ingest",
10945
12119
  title: "Ingest a new document (text body or file upload)",
10946
12120
  description: "Create a new document in your Vectros tenant. Two modes:\n \u2022 Text mode: pass `text` (string body). Single-call. Use for crawled content, notes, generated text.\n \u2022 File mode: pass `filePath` (local path on the MCP server's host machine). STDIO-TRANSPORT ONLY \u2014 rejected on HTTP transport. MCP server reads the bytes, requests a presigned upload URL, and PUTs them. Returns when the upload is accepted (indexStatus: PENDING_INDEX); poll with `document_get` until indexStatus is INDEXED.\nEither `text` or `filePath` must be present; both is an error. Idempotent by `externalId` (re-ingest returns the existing document, not a duplicate \u2014 requires documents:r in addition to documents:c, since being handed the existing document is a read of it). To UPDATE an existing document instead \u2014 re-index an edited body \u2014 pass `upsert:true` with the same `externalId` (and the same `schemaId`); this is the re-sync primitive for keeping a knowledge base current. Pass `schemaId` + `payload` for a typed, lookup-queryable document (records parity). indexMode defaults to HYBRID for untyped documents (omit to inherit a bound schema's default). storeText is a FILE-MODE knob (default true): false discards the uploaded file's extracted text after indexing (search + file download keep working; text retrieval and document_ask do not). Text-mode bodies are always retained, so storeText is not accepted with `text`.",
10947
- inputSchema: inputSchema20,
12121
+ inputSchema: inputSchema21,
12122
+ // Creates by default, idempotent ONLY when the caller supplies `externalId` (optional,
12123
+ // per the doc comment above) — re-ingest then returns the existing document rather than
12124
+ // duplicating it. `externalId` is not required, so annotated for the less-safe default
12125
+ // (omit it, and every call creates a new document), same standard applied to
12126
+ // record_create/record_batch_write's identical optional-externalId shape. `upsert:true`
12127
+ // is a further, real, named capability of this tool that OVERWRITES an existing
12128
+ // document's content and re-indexes it — that path is destructive to the prior body, so
12129
+ // this is flagged destructive rather than claiming create-only safety a caller can
12130
+ // invoke past.
12131
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
10948
12132
  handler: async (args) => {
10949
12133
  const title = args.title;
10950
12134
  const text = args.text;
@@ -11055,7 +12239,7 @@ var documentIngest = ({ client, log, transport, ingestRoot }) => ({
11055
12239
  }
11056
12240
  const putRes = await fetch(uploadUrl, {
11057
12241
  method: "PUT",
11058
- headers: { "Content-Type": fileType },
12242
+ headers: { "Content-Type": fileType, ...presignedUploadHeaders(upload) },
11059
12243
  body: bytes
11060
12244
  });
11061
12245
  if (!putRes.ok) {
@@ -11094,31 +12278,38 @@ var documentIngest = ({ client, log, transport, ingestRoot }) => ({
11094
12278
  }
11095
12279
  });
11096
12280
  var document_ingest_default = documentIngest;
12281
+ function presignedUploadHeaders(response) {
12282
+ if (typeof response !== "object" || response === null) return {};
12283
+ const { requiredHeaderName, requiredHeaderValue } = response;
12284
+ if (typeof requiredHeaderName !== "string" || requiredHeaderName === "") return {};
12285
+ if (typeof requiredHeaderValue !== "string") return {};
12286
+ return { [requiredHeaderName]: requiredHeaderValue };
12287
+ }
11097
12288
 
11098
12289
  // src/tools/lookup_principal.ts
11099
- import { z as z20 } from "zod";
12290
+ import { z as z21 } from "zod";
11100
12291
  var MCP_DEFAULT_LIMIT5 = 10;
11101
12292
  var MCP_MAX_LIMIT5 = 100;
11102
- var inputSchema21 = {
11103
- kind: z20.string().describe(
12293
+ var inputSchema22 = {
12294
+ kind: z21.string().describe(
11104
12295
  'Which principal to look up: "user" (the fixed principal surface), or an entity namespace \u2014 "org", "client" (reserved, registered like any other), or a namespace you registered.'
11105
12296
  ),
11106
- externalId: z20.string().optional().describe(
12297
+ externalId: z21.string().optional().describe(
11107
12298
  "Resolve mode: your own stable identifier for the principal. Returns the single matching principal (with its Vectros UUID), or an empty array if none. The fastest path to the UUID the ownership filters need. Takes precedence if both this and a `field` lookup are supplied."
11108
12299
  ),
11109
- contextId: z20.string().optional().describe(
12300
+ contextId: z21.string().optional().describe(
11110
12301
  "Entity kinds only (not `user`, which is always tenant-wide): the app context to look up entities in, for a namespace registered as context-owned rather than tenant-wide. A context-confined credential's own context is used automatically without this; supply it to name a context explicitly (required for an unconfined/root credential to reach a context-owned namespace). Rejected if the namespace turns out to be tenant-wide."
11111
12302
  ),
11112
12303
  // Lookup-mode args — provide `field` plus EXACTLY ONE of: value | from+to | prefix.
11113
- type: z20.string().optional().describe('Lookup mode: the identity schema\'s record type (e.g. "person_v1"). Required with `field`.'),
11114
- field: z20.string().optional().describe('Lookup mode: name of the schema-declared lookup field to query by (e.g. "email").'),
11115
- value: z20.string().optional().describe("Lookup mode (equality): exact-match value for `field`. Works on sensitive fields."),
11116
- from: z20.string().optional().describe("Lookup mode (range): inclusive lower bound; requires `to`. Non-sensitive fields only."),
11117
- to: z20.string().optional().describe("Lookup mode (range): inclusive upper bound; requires `from`."),
11118
- prefix: z20.string().optional().describe("Lookup mode (prefix): match values starting with this. Range-enabled string fields only."),
11119
- order: z20.enum(["asc", "desc"]).optional().describe("Lookup mode: sort direction by the looked-up field. `asc` (default) or `desc`."),
11120
- startFrom: z20.string().optional().describe("Lookup mode: pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch the next."),
11121
- limit: z20.number().int().min(1).max(MCP_MAX_LIMIT5).optional().describe(
12304
+ type: z21.string().optional().describe('Lookup mode: the identity schema\'s record type (e.g. "person_v1"). Required with `field`.'),
12305
+ field: z21.string().optional().describe('Lookup mode: name of the schema-declared lookup field to query by (e.g. "email").'),
12306
+ value: z21.string().optional().describe("Lookup mode (equality): exact-match value for `field`. Works on sensitive fields."),
12307
+ from: z21.string().optional().describe("Lookup mode (range): inclusive lower bound; requires `to`. Non-sensitive fields only."),
12308
+ to: z21.string().optional().describe("Lookup mode (range): inclusive upper bound; requires `from`."),
12309
+ prefix: z21.string().optional().describe("Lookup mode (prefix): match values starting with this. Range-enabled string fields only."),
12310
+ order: z21.enum(["asc", "desc"]).optional().describe("Lookup mode: sort direction by the looked-up field. `asc` (default) or `desc`."),
12311
+ startFrom: z21.string().optional().describe("Lookup mode: pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch the next."),
12312
+ limit: z21.number().int().min(1).max(MCP_MAX_LIMIT5).optional().describe(
11122
12313
  `Max principals per page. Defaults to ${MCP_DEFAULT_LIMIT5}; raise up to ${MCP_MAX_LIMIT5} (the principals API max) in one call when you can accept the payload, or page with \`startFrom\`.`
11123
12314
  )
11124
12315
  };
@@ -11126,7 +12317,9 @@ var lookupPrincipal = ({ client, log }) => ({
11126
12317
  name: "lookup_principal",
11127
12318
  title: "Look up a user identity or a namespaced identity entity",
11128
12319
  description: "Resolve a user, or an identity entity in a namespace (org/client/one you registered). Two modes:\n \u2022 Resolve by your own id: pass `externalId` \u2192 the matching principal incl. its Vectros UUID (the id the ownership filters on record_query / hybrid_search / rag_ask expect).\n \u2022 Lookup by a schema field: pass `type` and `field` plus exactly one of `value` (exact), `from`+`to` (range), or `prefix`. Sensitive-field-safe. (If both `externalId` and a `field` lookup are given, `externalId` wins.) For an entity kind, `contextId` names a specific app context when the namespace is context-owned rather than tenant-wide; a context-confined credential's own context is used automatically without it. Returns a `{ data, nextCursor }` page (default 10, max 100 \u2014 raise it in one call when you can accept the payload); a non-null `nextCursor` means more remain \u2014 pass it back as `startFrom`. Read-only \u2014 does not create or modify identities.",
11129
- inputSchema: inputSchema21,
12320
+ inputSchema: inputSchema22,
12321
+ // A pure read — never creates, modifies, or deletes anything server-side.
12322
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
11130
12323
  handler: async (args) => {
11131
12324
  const kind = args.kind;
11132
12325
  const isUser = kind === "user";
@@ -11200,17 +12393,19 @@ var lookupPrincipal = ({ client, log }) => ({
11200
12393
  var lookup_principal_default = lookupPrincipal;
11201
12394
 
11202
12395
  // src/tools/version_history.ts
11203
- import { z as z21 } from "zod";
11204
- var inputSchema22 = {
11205
- resourceType: z21.enum(["record", "document"]).describe("Which kind of entity the id refers to: a record or a document."),
11206
- id: z21.string().min(1, "id is required").describe("The Vectros id of the record or document whose history you want."),
11207
- startFrom: z21.string().optional().describe("Pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch older entries.")
12396
+ import { z as z22 } from "zod";
12397
+ var inputSchema23 = {
12398
+ resourceType: z22.enum(["record", "document"]).describe("Which kind of entity the id refers to: a record or a document."),
12399
+ id: z22.string().min(1, "id is required").describe("The Vectros id of the record or document whose history you want."),
12400
+ startFrom: z22.string().optional().describe("Pagination cursor \u2014 pass the `nextCursor` from the previous page to fetch older entries.")
11208
12401
  };
11209
12402
  var versionHistory = ({ client, log }) => ({
11210
12403
  name: "version_history",
11211
12404
  title: "Version history (record or document)",
11212
12405
  description: "Read the audit/version trail (CREATE/UPDATE/DELETE, with actor, timestamp, and diff) for a single record or document. Pass `resourceType` (record|document) and `id`. Returns `{ data, nextCursor }`; pass `nextCursor` back as `startFrom` to page through older entries. Entities without audit history (untyped) return an empty trail. Read-only.",
11213
- inputSchema: inputSchema22,
12406
+ inputSchema: inputSchema23,
12407
+ // A pure read — never creates, modifies, or deletes anything server-side.
12408
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
11214
12409
  handler: async (args) => {
11215
12410
  const resourceType = args.resourceType;
11216
12411
  const id = args.id;
@@ -11239,6 +12434,7 @@ var TOOL_NAMES = [
11239
12434
  "record_get",
11240
12435
  "record_batch_get",
11241
12436
  "record_create",
12437
+ "record_batch_write",
11242
12438
  "record_update",
11243
12439
  "record_delete",
11244
12440
  "rag_ask",
@@ -11265,6 +12461,7 @@ var ALL_TOOL_FACTORIES = {
11265
12461
  record_get: record_get_default,
11266
12462
  record_batch_get: record_batch_get_default,
11267
12463
  record_create: record_create_default,
12464
+ record_batch_write: record_batch_write_default,
11268
12465
  record_update: record_update_default,
11269
12466
  record_delete: record_delete_default,
11270
12467
  rag_ask: rag_ask_default,
@@ -11324,7 +12521,7 @@ var ALL_RESOURCE_FACTORIES = {
11324
12521
  };
11325
12522
 
11326
12523
  // src/zod-to-json-schema.ts
11327
- import { z as z22 } from "zod";
12524
+ import { z as z23 } from "zod";
11328
12525
  function zodShapeToJsonSchema(shape) {
11329
12526
  const properties = {};
11330
12527
  const required = [];
@@ -11339,40 +12536,40 @@ function zodShapeToJsonSchema(shape) {
11339
12536
  function zodTypeToJsonSchema(schema) {
11340
12537
  const description = schema.description;
11341
12538
  let current = schema;
11342
- while (current instanceof z22.ZodOptional || current instanceof z22.ZodDefault || current instanceof z22.ZodNullable) {
12539
+ while (current instanceof z23.ZodOptional || current instanceof z23.ZodDefault || current instanceof z23.ZodNullable) {
11343
12540
  current = current._def.innerType;
11344
12541
  }
11345
12542
  const base = description ? { description } : {};
11346
- if (current instanceof z22.ZodString) {
12543
+ if (current instanceof z23.ZodString) {
11347
12544
  return { ...base, type: "string" };
11348
12545
  }
11349
- if (current instanceof z22.ZodNumber) {
12546
+ if (current instanceof z23.ZodNumber) {
11350
12547
  return { ...base, type: "number" };
11351
12548
  }
11352
- if (current instanceof z22.ZodBoolean) {
12549
+ if (current instanceof z23.ZodBoolean) {
11353
12550
  return { ...base, type: "boolean" };
11354
12551
  }
11355
- if (current instanceof z22.ZodEnum) {
12552
+ if (current instanceof z23.ZodEnum) {
11356
12553
  return {
11357
12554
  ...base,
11358
12555
  type: "string",
11359
12556
  enum: current.options
11360
12557
  };
11361
12558
  }
11362
- if (current instanceof z22.ZodArray) {
12559
+ if (current instanceof z23.ZodArray) {
11363
12560
  return {
11364
12561
  ...base,
11365
12562
  type: "array",
11366
12563
  items: zodTypeToJsonSchema(current.element)
11367
12564
  };
11368
12565
  }
11369
- if (current instanceof z22.ZodObject) {
12566
+ if (current instanceof z23.ZodObject) {
11370
12567
  return {
11371
12568
  ...base,
11372
12569
  ...zodShapeToJsonSchema(current.shape)
11373
12570
  };
11374
12571
  }
11375
- if (current instanceof z22.ZodRecord) {
12572
+ if (current instanceof z23.ZodRecord) {
11376
12573
  const valueType = current._def.valueType;
11377
12574
  return {
11378
12575
  ...base,
@@ -11486,7 +12683,12 @@ var VectrosMCPServer = class {
11486
12683
  // MCP client (a well-behaved client rejects an unknown key before the call).
11487
12684
  // The server enforces it too (z.object(...).strict() below) so a raw JSON-RPC
11488
12685
  // call that skips client validation is still rejected — belt and suspenders.
11489
- inputSchema: { ...zodShapeToJsonSchema(t.inputSchema), additionalProperties: false }
12686
+ inputSchema: { ...zodShapeToJsonSchema(t.inputSchema), additionalProperties: false },
12687
+ // Forwarded from the tool's own definition, not hand-copied here: adding an
12688
+ // annotation to a tool factory does nothing for a client unless it also reaches
12689
+ // this emitted list — the actual `tools/list` response a host reads, not the
12690
+ // source that builds it.
12691
+ ...t.annotations ? { annotations: t.annotations } : {}
11490
12692
  }))
11491
12693
  })
11492
12694
  );
@@ -11496,7 +12698,7 @@ var VectrosMCPServer = class {
11496
12698
  if (!tool) {
11497
12699
  result = toolError(req.params.name ?? "unknown", new Error("No such tool."));
11498
12700
  } else {
11499
- const parsed = z23.object(tool.inputSchema).strict().safeParse(req.params.arguments ?? {});
12701
+ const parsed = z24.object(tool.inputSchema).strict().safeParse(req.params.arguments ?? {});
11500
12702
  if (!parsed.success) {
11501
12703
  result = toolError(tool.name, new Error(formatArgError(tool, parsed.error)));
11502
12704
  } else {
@@ -11910,7 +13112,8 @@ async function main() {
11910
13112
  if (notice) log[notice.level]({ alias: notice.alias }, notice.message);
11911
13113
  if (!apiKey) {
11912
13114
  log.fatal({ reason: resolved.reason }, noKeyMessage(resolved));
11913
- process.exit(1);
13115
+ process.exitCode = 1;
13116
+ return;
11914
13117
  }
11915
13118
  const apiBaseUrl = process.env.VECTROS_API_BASE_URL;
11916
13119
  if (apiBaseUrl !== void 0) {
@@ -11919,7 +13122,8 @@ async function main() {
11919
13122
  } catch (err) {
11920
13123
  const msg = err instanceof InvalidBaseUrlError ? err.message : String(err);
11921
13124
  log.fatal({ err: msg }, "invalid VECTROS_API_BASE_URL");
11922
- process.exit(1);
13125
+ process.exitCode = 1;
13126
+ return;
11923
13127
  }
11924
13128
  }
11925
13129
  const port = process.env.VECTROS_MCP_HTTP_PORT ? Number.parseInt(process.env.VECTROS_MCP_HTTP_PORT, 10) : void 0;
@@ -11929,7 +13133,8 @@ async function main() {
11929
13133
  const allowedOrigins = process.env.VECTROS_MCP_HTTP_ALLOWED_ORIGINS ? [process.env.VECTROS_MCP_HTTP_ALLOWED_ORIGINS] : void 0;
11930
13134
  if (port !== void 0 && (!Number.isFinite(port) || port < 1 || port > 65535)) {
11931
13135
  log.fatal({ port: process.env.VECTROS_MCP_HTTP_PORT }, "invalid VECTROS_MCP_HTTP_PORT (must be 1-65535)");
11932
- process.exit(1);
13136
+ process.exitCode = 1;
13137
+ return;
11933
13138
  }
11934
13139
  const effectiveHost = host ?? "127.0.0.1";
11935
13140
  const allowInsecureHttp = ["1", "true", "yes"].includes(
@@ -11940,14 +13145,16 @@ async function main() {
11940
13145
  { host: effectiveHost },
11941
13146
  "refusing to bind a non-loopback host without VECTROS_MCP_HTTP_BEARER_TOKEN \u2014 anyone who can reach this port could call Vectros with your credentials. Set a bearer token, or set VECTROS_MCP_HTTP_ALLOW_INSECURE=1 to override (NOT recommended)."
11942
13147
  );
11943
- process.exit(1);
13148
+ process.exitCode = 1;
13149
+ return;
11944
13150
  }
11945
13151
  let tools;
11946
13152
  try {
11947
13153
  tools = parseToolsEnv(process.env.VECTROS_MCP_TOOLS);
11948
13154
  } catch (err) {
11949
13155
  log.fatal({ err: String(err) }, "invalid VECTROS_MCP_TOOLS");
11950
- process.exit(1);
13156
+ process.exitCode = 1;
13157
+ return;
11951
13158
  }
11952
13159
  const skipFlag = (process.env.VECTROS_MCP_SKIP_PING_VALIDATION ?? "").toLowerCase();
11953
13160
  const validateOnStart = !(skipFlag === "1" || skipFlag === "true");
@@ -11967,7 +13174,8 @@ async function main() {
11967
13174
  } else {
11968
13175
  log.fatal({ err: String(err) }, "startup failed");
11969
13176
  }
11970
- process.exit(1);
13177
+ process.exitCode = 1;
13178
+ return;
11971
13179
  }
11972
13180
  let handle;
11973
13181
  try {
@@ -11982,7 +13190,8 @@ async function main() {
11982
13190
  });
11983
13191
  } catch (err) {
11984
13192
  log.fatal({ err: String(err) }, "failed to start HTTP transport");
11985
- process.exit(2);
13193
+ process.exitCode = 2;
13194
+ return;
11986
13195
  }
11987
13196
  const shutdown = async (signal) => {
11988
13197
  log.info({ signal }, "shutdown requested");