@vectros-ai/mcp-server 0.18.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli-http.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // src/server.ts
4
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
5
 
6
- // ../../node_modules/@vectros-ai/sdk/dist/index.mjs
6
+ // node_modules/@vectros-ai/sdk/dist/index.mjs
7
7
  var __defProp = Object.defineProperty;
8
8
  var __export = (target, all) => {
9
9
  for (var name in all)
@@ -24,6 +24,7 @@ __export(api_exports, {
24
24
  ContentTooLargeError: () => ContentTooLargeError,
25
25
  DocumentAskRequest: () => DocumentAskRequest,
26
26
  DocumentContextEvent: () => DocumentContextEvent,
27
+ DocumentExtraction: () => DocumentExtraction,
27
28
  DocumentLookupRequest: () => DocumentLookupRequest,
28
29
  DocumentPatchRequest: () => DocumentPatchRequest,
29
30
  DocumentRequest: () => DocumentRequest,
@@ -76,6 +77,7 @@ __export(api_exports, {
76
77
  UserExistsResponse: () => UserExistsResponse,
77
78
  UserRequest: () => UserRequest,
78
79
  UserResponse: () => UserResponse,
80
+ agents: () => agents_exports,
79
81
  auth: () => auth_exports,
80
82
  compliance: () => compliance_exports,
81
83
  documents: () => documents_exports,
@@ -341,6 +343,7 @@ var UnprocessableEntityError = class extends VectrosError {
341
343
  this.name = this.constructor.name;
342
344
  }
343
345
  };
346
+ var agents_exports = {};
344
347
  var auth_exports = {};
345
348
  var ErasureRequest;
346
349
  ((ErasureRequest2) => {
@@ -545,6 +548,18 @@ var DocumentContextEvent;
545
548
  DocumentContext: "document_context"
546
549
  };
547
550
  })(DocumentContextEvent || (DocumentContextEvent = {}));
551
+ var DocumentExtraction;
552
+ ((DocumentExtraction2) => {
553
+ DocumentExtraction2.Outcome = {
554
+ Ok: "OK",
555
+ Truncated: "TRUNCATED",
556
+ NoText: "NO_TEXT",
557
+ Encrypted: "ENCRYPTED",
558
+ Unsupported: "UNSUPPORTED",
559
+ TooLarge: "TOO_LARGE",
560
+ Unreadable: "UNREADABLE"
561
+ };
562
+ })(DocumentExtraction || (DocumentExtraction = {}));
548
563
  var DocumentRequest;
549
564
  ((DocumentRequest2) => {
550
565
  DocumentRequest2.IndexMode = {
@@ -1850,13 +1865,13 @@ function joinPathSegments(left, right) {
1850
1865
  }
1851
1866
  return `${left}/${right}`;
1852
1867
  }
1853
- function trimSlashes(str) {
1854
- if (!str) return str;
1868
+ function trimSlashes(str2) {
1869
+ if (!str2) return str2;
1855
1870
  let start = 0;
1856
- let end = str.length;
1857
- if (str.startsWith("/")) start = 1;
1858
- if (str.endsWith("/")) end = str.length - 1;
1859
- return start === 0 && end === str.length ? str : str.slice(start, end);
1871
+ let end = str2.length;
1872
+ if (str2.startsWith("/")) start = 1;
1873
+ if (str2.endsWith("/")) end = str2.length - 1;
1874
+ return start === 0 && end === str2.length ? str2 : str2.slice(start, end);
1860
1875
  }
1861
1876
  var Supplier = {
1862
1877
  get: async (supplier) => {
@@ -2371,48 +2386,675 @@ function normalizeClientOptionsWithAuth(options) {
2371
2386
  normalized.authProvider = options.auth;
2372
2387
  return normalized;
2373
2388
  }
2374
- Object.assign(normalized, options.auth);
2375
- }
2376
- const normalizedWithNoOpAuthProvider = withNoOpAuthProvider(normalized);
2377
- normalized.authProvider ?? (normalized.authProvider = new BearerAuthProvider(normalizedWithNoOpAuthProvider));
2378
- return normalized;
2379
- }
2380
- function withNoOpAuthProvider(options) {
2381
- return {
2382
- ...options,
2383
- authProvider: new NoOpAuthProvider()
2384
- };
2385
- }
2386
- function handleNonStatusCodeError(error, rawResponse, method, path2) {
2387
- switch (error.reason) {
2388
- case "non-json":
2389
- throw new VectrosError({
2390
- statusCode: error.statusCode,
2391
- body: error.rawBody,
2392
- rawResponse
2393
- });
2394
- case "body-is-null":
2395
- throw new VectrosError({
2396
- statusCode: error.statusCode,
2397
- rawResponse
2398
- });
2399
- case "timeout":
2400
- throw new VectrosTimeoutError(`Timeout exceeded when calling ${method} ${path2}.`, {
2401
- cause: error.cause
2402
- });
2403
- case "unknown":
2404
- throw new VectrosError({
2405
- message: error.errorMessage,
2406
- rawResponse,
2407
- cause: error.cause
2408
- });
2409
- default:
2410
- throw new VectrosError({
2411
- message: "Unknown error",
2412
- rawResponse
2413
- });
2389
+ Object.assign(normalized, options.auth);
2390
+ }
2391
+ const normalizedWithNoOpAuthProvider = withNoOpAuthProvider(normalized);
2392
+ normalized.authProvider ?? (normalized.authProvider = new BearerAuthProvider(normalizedWithNoOpAuthProvider));
2393
+ return normalized;
2394
+ }
2395
+ function withNoOpAuthProvider(options) {
2396
+ return {
2397
+ ...options,
2398
+ authProvider: new NoOpAuthProvider()
2399
+ };
2400
+ }
2401
+ function handleNonStatusCodeError(error, rawResponse, method, path2) {
2402
+ switch (error.reason) {
2403
+ case "non-json":
2404
+ throw new VectrosError({
2405
+ statusCode: error.statusCode,
2406
+ body: error.rawBody,
2407
+ rawResponse
2408
+ });
2409
+ case "body-is-null":
2410
+ throw new VectrosError({
2411
+ statusCode: error.statusCode,
2412
+ rawResponse
2413
+ });
2414
+ case "timeout":
2415
+ throw new VectrosTimeoutError(`Timeout exceeded when calling ${method} ${path2}.`, {
2416
+ cause: error.cause
2417
+ });
2418
+ case "unknown":
2419
+ throw new VectrosError({
2420
+ message: error.errorMessage,
2421
+ rawResponse,
2422
+ cause: error.cause
2423
+ });
2424
+ default:
2425
+ throw new VectrosError({
2426
+ message: "Unknown error",
2427
+ rawResponse
2428
+ });
2429
+ }
2430
+ }
2431
+ var AgentsClient = class {
2432
+ constructor(options) {
2433
+ this._options = normalizeClientOptionsWithAuth(options);
2434
+ }
2435
+ /**
2436
+ * Returns a page of the agents in the app context, newest first, each at its latest version. A caller holding `runs:c` but not `agents:r` gets only each agent's `id`, `name`, `description`, `latestVersion` and `status`. Retired and purged agents are left out unless `includeRetired=true`. Requires `agents:r` or `runs:c`.
2437
+ *
2438
+ * @param {Vectros.ListAgentsRequest} request
2439
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2440
+ *
2441
+ * @throws {@link Vectros.ForbiddenError}
2442
+ *
2443
+ * @example
2444
+ * await client.agents.listAgents()
2445
+ */
2446
+ listAgents(request = {}, requestOptions) {
2447
+ return HttpResponsePromise.fromPromise(this.__listAgents(request, requestOptions));
2448
+ }
2449
+ async __listAgents(request = {}, requestOptions) {
2450
+ const { contextId, includeRetired, startFrom, limit } = request;
2451
+ const _queryParams = {
2452
+ contextId,
2453
+ includeRetired,
2454
+ startFrom,
2455
+ limit
2456
+ };
2457
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2458
+ const _headers = mergeHeaders(
2459
+ _authRequest.headers,
2460
+ this._options?.headers,
2461
+ requestOptions?.headers
2462
+ );
2463
+ const _response = await fetcher({
2464
+ url: url_exports.join(
2465
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2466
+ "v1/agents"
2467
+ ),
2468
+ method: "GET",
2469
+ headers: _headers,
2470
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2471
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2472
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2473
+ abortSignal: requestOptions?.abortSignal,
2474
+ fetchFn: this._options?.fetch,
2475
+ logging: this._options.logging
2476
+ });
2477
+ if (_response.ok) {
2478
+ return { data: _response.body, rawResponse: _response.rawResponse };
2479
+ }
2480
+ if (_response.error.reason === "status-code") {
2481
+ switch (_response.error.statusCode) {
2482
+ case 403:
2483
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2484
+ default:
2485
+ throw new VectrosError({
2486
+ statusCode: _response.error.statusCode,
2487
+ body: _response.error.body,
2488
+ rawResponse: _response.rawResponse
2489
+ });
2490
+ }
2491
+ }
2492
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/agents");
2493
+ }
2494
+ /**
2495
+ * Stores a new agent at version 1, or returns the existing agent of this name unchanged. With `?upsert=true` an existing agent whose definition differs gets a new version instead. Requires the `agents:c` scope (also `agents:u` with `?upsert=true`).
2496
+ *
2497
+ * @param {Vectros.CreateAgentRequest} request
2498
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2499
+ *
2500
+ * @throws {@link Vectros.BadRequestError}
2501
+ * @throws {@link Vectros.ForbiddenError}
2502
+ * @throws {@link Vectros.ConflictError}
2503
+ * @throws {@link Vectros.TooManyRequestsError}
2504
+ *
2505
+ * @example
2506
+ * await client.agents.createAgent({
2507
+ * body: {
2508
+ * model: "claude-sonnet-5-5"
2509
+ * }
2510
+ * })
2511
+ */
2512
+ createAgent(request, requestOptions) {
2513
+ return HttpResponsePromise.fromPromise(this.__createAgent(request, requestOptions));
2514
+ }
2515
+ async __createAgent(request, requestOptions) {
2516
+ const { upsert, contextId, body: _body } = request;
2517
+ const _queryParams = {
2518
+ upsert,
2519
+ contextId
2520
+ };
2521
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2522
+ const _headers = mergeHeaders(
2523
+ _authRequest.headers,
2524
+ this._options?.headers,
2525
+ requestOptions?.headers
2526
+ );
2527
+ const _response = await fetcher({
2528
+ url: url_exports.join(
2529
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2530
+ "v1/agents"
2531
+ ),
2532
+ method: "POST",
2533
+ headers: _headers,
2534
+ contentType: "application/json",
2535
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2536
+ requestType: "json",
2537
+ body: _body,
2538
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2539
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2540
+ abortSignal: requestOptions?.abortSignal,
2541
+ fetchFn: this._options?.fetch,
2542
+ logging: this._options.logging
2543
+ });
2544
+ if (_response.ok) {
2545
+ return { data: _response.body, rawResponse: _response.rawResponse };
2546
+ }
2547
+ if (_response.error.reason === "status-code") {
2548
+ switch (_response.error.statusCode) {
2549
+ case 400:
2550
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2551
+ case 403:
2552
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2553
+ case 409:
2554
+ throw new ConflictError(_response.error.body, _response.rawResponse);
2555
+ case 429:
2556
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
2557
+ default:
2558
+ throw new VectrosError({
2559
+ statusCode: _response.error.statusCode,
2560
+ body: _response.error.body,
2561
+ rawResponse: _response.rawResponse
2562
+ });
2563
+ }
2564
+ }
2565
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/agents");
2566
+ }
2567
+ /**
2568
+ * Returns the agent at its latest version, or at `version`. Requires the `agents:r` scope.
2569
+ *
2570
+ * @param {Vectros.GetAgentRequest} request
2571
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2572
+ *
2573
+ * @throws {@link Vectros.ForbiddenError}
2574
+ * @throws {@link Vectros.NotFoundError}
2575
+ *
2576
+ * @example
2577
+ * await client.agents.getAgent({
2578
+ * id: "id"
2579
+ * })
2580
+ */
2581
+ getAgent(request, requestOptions) {
2582
+ return HttpResponsePromise.fromPromise(this.__getAgent(request, requestOptions));
2583
+ }
2584
+ async __getAgent(request, requestOptions) {
2585
+ const { id, contextId, version } = request;
2586
+ const _queryParams = {
2587
+ contextId,
2588
+ version
2589
+ };
2590
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2591
+ const _headers = mergeHeaders(
2592
+ _authRequest.headers,
2593
+ this._options?.headers,
2594
+ requestOptions?.headers
2595
+ );
2596
+ const _response = await fetcher({
2597
+ url: url_exports.join(
2598
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2599
+ `v1/agents/${url_exports.encodePathParam(id)}`
2600
+ ),
2601
+ method: "GET",
2602
+ headers: _headers,
2603
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2604
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2605
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2606
+ abortSignal: requestOptions?.abortSignal,
2607
+ fetchFn: this._options?.fetch,
2608
+ logging: this._options.logging
2609
+ });
2610
+ if (_response.ok) {
2611
+ return { data: _response.body, rawResponse: _response.rawResponse };
2612
+ }
2613
+ if (_response.error.reason === "status-code") {
2614
+ switch (_response.error.statusCode) {
2615
+ case 403:
2616
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2617
+ case 404:
2618
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
2619
+ default:
2620
+ throw new VectrosError({
2621
+ statusCode: _response.error.statusCode,
2622
+ body: _response.error.body,
2623
+ rawResponse: _response.rawResponse
2624
+ });
2625
+ }
2626
+ }
2627
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/agents/{id}");
2628
+ }
2629
+ /**
2630
+ * Stores the body as the agent's next version. Earlier versions never change. Every optional field you leave out takes its default; `model` is required. With `?restore=true` a retired agent becomes active again with this version. Requires the `agents:u` scope.
2631
+ *
2632
+ * @param {Vectros.UpdateAgentRequest} request
2633
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2634
+ *
2635
+ * @throws {@link Vectros.BadRequestError}
2636
+ * @throws {@link Vectros.ForbiddenError}
2637
+ * @throws {@link Vectros.NotFoundError}
2638
+ * @throws {@link Vectros.ConflictError}
2639
+ * @throws {@link Vectros.TooManyRequestsError}
2640
+ *
2641
+ * @example
2642
+ * await client.agents.updateAgent({
2643
+ * id: "id",
2644
+ * body: {
2645
+ * model: "claude-sonnet-5-5"
2646
+ * }
2647
+ * })
2648
+ */
2649
+ updateAgent(request, requestOptions) {
2650
+ return HttpResponsePromise.fromPromise(this.__updateAgent(request, requestOptions));
2651
+ }
2652
+ async __updateAgent(request, requestOptions) {
2653
+ const { id, restore, contextId, body: _body } = request;
2654
+ const _queryParams = {
2655
+ restore,
2656
+ contextId
2657
+ };
2658
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2659
+ const _headers = mergeHeaders(
2660
+ _authRequest.headers,
2661
+ this._options?.headers,
2662
+ requestOptions?.headers
2663
+ );
2664
+ const _response = await fetcher({
2665
+ url: url_exports.join(
2666
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2667
+ `v1/agents/${url_exports.encodePathParam(id)}`
2668
+ ),
2669
+ method: "PUT",
2670
+ headers: _headers,
2671
+ contentType: "application/json",
2672
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2673
+ requestType: "json",
2674
+ body: _body,
2675
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2676
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2677
+ abortSignal: requestOptions?.abortSignal,
2678
+ fetchFn: this._options?.fetch,
2679
+ logging: this._options.logging
2680
+ });
2681
+ if (_response.ok) {
2682
+ return { data: _response.body, rawResponse: _response.rawResponse };
2683
+ }
2684
+ if (_response.error.reason === "status-code") {
2685
+ switch (_response.error.statusCode) {
2686
+ case 400:
2687
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2688
+ case 403:
2689
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2690
+ case 404:
2691
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
2692
+ case 409:
2693
+ throw new ConflictError(_response.error.body, _response.rawResponse);
2694
+ case 429:
2695
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
2696
+ default:
2697
+ throw new VectrosError({
2698
+ statusCode: _response.error.statusCode,
2699
+ body: _response.error.body,
2700
+ rawResponse: _response.rawResponse
2701
+ });
2702
+ }
2703
+ }
2704
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/agents/{id}");
2705
+ }
2706
+ /**
2707
+ * Retires the agent: its versions stay readable, it leaves the default listing, and it can be restored. With `?purge=true` a retired agent's content (every version's prompt, description, tools, model, limits and budget) is erased, leaving its id, name, version numbers and timestamps; its change history keeps only a one-way hash of the prompt, description and tools. If the agent is restored while a purge is running, the purge stops (409) and versions it already erased stay erased; purge it again after retiring it. With `?purge=true&version=N` one version that is not the latest is erased. The name of a purged agent stays reserved. Requires the `agents:d` scope.
2708
+ *
2709
+ * @param {Vectros.DeleteAgentRequest} request
2710
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2711
+ *
2712
+ * @throws {@link Vectros.BadRequestError}
2713
+ * @throws {@link Vectros.ForbiddenError}
2714
+ * @throws {@link Vectros.NotFoundError}
2715
+ * @throws {@link Vectros.ConflictError}
2716
+ * @throws {@link Vectros.TooManyRequestsError}
2717
+ *
2718
+ * @example
2719
+ * await client.agents.deleteAgent({
2720
+ * id: "id"
2721
+ * })
2722
+ */
2723
+ deleteAgent(request, requestOptions) {
2724
+ return HttpResponsePromise.fromPromise(this.__deleteAgent(request, requestOptions));
2725
+ }
2726
+ async __deleteAgent(request, requestOptions) {
2727
+ const { id, purge, version, contextId } = request;
2728
+ const _queryParams = {
2729
+ purge,
2730
+ version,
2731
+ contextId
2732
+ };
2733
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2734
+ const _headers = mergeHeaders(
2735
+ _authRequest.headers,
2736
+ this._options?.headers,
2737
+ requestOptions?.headers
2738
+ );
2739
+ const _response = await fetcher({
2740
+ url: url_exports.join(
2741
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2742
+ `v1/agents/${url_exports.encodePathParam(id)}`
2743
+ ),
2744
+ method: "DELETE",
2745
+ headers: _headers,
2746
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2747
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2748
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2749
+ abortSignal: requestOptions?.abortSignal,
2750
+ fetchFn: this._options?.fetch,
2751
+ logging: this._options.logging
2752
+ });
2753
+ if (_response.ok) {
2754
+ return { data: _response.body, rawResponse: _response.rawResponse };
2755
+ }
2756
+ if (_response.error.reason === "status-code") {
2757
+ switch (_response.error.statusCode) {
2758
+ case 400:
2759
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2760
+ case 403:
2761
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2762
+ case 404:
2763
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
2764
+ case 409:
2765
+ throw new ConflictError(_response.error.body, _response.rawResponse);
2766
+ case 429:
2767
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
2768
+ default:
2769
+ throw new VectrosError({
2770
+ statusCode: _response.error.statusCode,
2771
+ body: _response.error.body,
2772
+ rawResponse: _response.rawResponse
2773
+ });
2774
+ }
2775
+ }
2776
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "DELETE", "/v1/agents/{id}");
2777
+ }
2778
+ /**
2779
+ * Returns a page of the agent's versions, newest first: who wrote each and when, and whether it was purged. With `includeContent=true` each entry carries its full definition. Requires the `agents:r` scope.
2780
+ *
2781
+ * @param {Vectros.ListAgentVersionsRequest} request
2782
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2783
+ *
2784
+ * @throws {@link Vectros.ForbiddenError}
2785
+ * @throws {@link Vectros.NotFoundError}
2786
+ *
2787
+ * @example
2788
+ * await client.agents.listAgentVersions({
2789
+ * id: "id"
2790
+ * })
2791
+ */
2792
+ listAgentVersions(request, requestOptions) {
2793
+ return HttpResponsePromise.fromPromise(this.__listAgentVersions(request, requestOptions));
2794
+ }
2795
+ async __listAgentVersions(request, requestOptions) {
2796
+ const { id, contextId, includeContent, startFrom, limit } = request;
2797
+ const _queryParams = {
2798
+ contextId,
2799
+ includeContent,
2800
+ startFrom,
2801
+ limit
2802
+ };
2803
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2804
+ const _headers = mergeHeaders(
2805
+ _authRequest.headers,
2806
+ this._options?.headers,
2807
+ requestOptions?.headers
2808
+ );
2809
+ const _response = await fetcher({
2810
+ url: url_exports.join(
2811
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2812
+ `v1/agents/${url_exports.encodePathParam(id)}/versions`
2813
+ ),
2814
+ method: "GET",
2815
+ headers: _headers,
2816
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2817
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2818
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2819
+ abortSignal: requestOptions?.abortSignal,
2820
+ fetchFn: this._options?.fetch,
2821
+ logging: this._options.logging
2822
+ });
2823
+ if (_response.ok) {
2824
+ return { data: _response.body, rawResponse: _response.rawResponse };
2825
+ }
2826
+ if (_response.error.reason === "status-code") {
2827
+ switch (_response.error.statusCode) {
2828
+ case 403:
2829
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2830
+ case 404:
2831
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
2832
+ default:
2833
+ throw new VectrosError({
2834
+ statusCode: _response.error.statusCode,
2835
+ body: _response.error.body,
2836
+ rawResponse: _response.rawResponse
2837
+ });
2838
+ }
2839
+ }
2840
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/agents/{id}/versions");
2841
+ }
2842
+ /**
2843
+ * Stops a run. The answer is `202` with the run still `RUNNING`: read it with `GET /v1/runs/{id}` to see it end. A model call in progress is cut within a few seconds; a tool call in progress is first allowed to finish, for up to about 30 seconds, so its change is recorded and billed, and the run stops as soon as it has. The run then ends `CANCELLED` with `errorCode` `CANCELLED_BY_CALLER`, unless it had already completed, in which case it stays `COMPLETED`. Its reservation is settled once, like any run's: a model call in progress when it stopped is charged up to its maximum. A run that has ended (or that had not started, which this cancel ends) answers `200` with its final state, so a cancel can always be retried. A run can be cancelled by the credential that started it (for a token bound to a user, by that user) and by your root key. Requires the `runs:c` scope; with `runs:r` as well the answer is the whole run, otherwise only its `id`, `status`, `terminal`, `reason` and `errorCode`. Takes no body.
2844
+ *
2845
+ * @param {Vectros.CancelRunRequest} request
2846
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2847
+ *
2848
+ * @throws {@link Vectros.BadRequestError}
2849
+ * @throws {@link Vectros.UnauthorizedError}
2850
+ * @throws {@link Vectros.ForbiddenError}
2851
+ * @throws {@link Vectros.NotFoundError}
2852
+ * @throws {@link Vectros.TooManyRequestsError}
2853
+ *
2854
+ * @example
2855
+ * await client.agents.cancelRun({
2856
+ * id: "id"
2857
+ * })
2858
+ */
2859
+ cancelRun(request, requestOptions) {
2860
+ return HttpResponsePromise.fromPromise(this.__cancelRun(request, requestOptions));
2861
+ }
2862
+ async __cancelRun(request, requestOptions) {
2863
+ const { id, contextId } = request;
2864
+ const _queryParams = {
2865
+ contextId
2866
+ };
2867
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2868
+ const _headers = mergeHeaders(
2869
+ _authRequest.headers,
2870
+ this._options?.headers,
2871
+ requestOptions?.headers
2872
+ );
2873
+ const _response = await fetcher({
2874
+ url: url_exports.join(
2875
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2876
+ `v1/runs/${url_exports.encodePathParam(id)}/cancel`
2877
+ ),
2878
+ method: "POST",
2879
+ headers: _headers,
2880
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2881
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2882
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2883
+ abortSignal: requestOptions?.abortSignal,
2884
+ fetchFn: this._options?.fetch,
2885
+ logging: this._options.logging
2886
+ });
2887
+ if (_response.ok) {
2888
+ return { data: _response.body, rawResponse: _response.rawResponse };
2889
+ }
2890
+ if (_response.error.reason === "status-code") {
2891
+ switch (_response.error.statusCode) {
2892
+ case 400:
2893
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2894
+ case 401:
2895
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2896
+ case 403:
2897
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2898
+ case 404:
2899
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
2900
+ case 429:
2901
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
2902
+ default:
2903
+ throw new VectrosError({
2904
+ statusCode: _response.error.statusCode,
2905
+ body: _response.error.body,
2906
+ rawResponse: _response.rawResponse
2907
+ });
2908
+ }
2909
+ }
2910
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/runs/{id}/cancel");
2911
+ }
2912
+ /**
2913
+ * Returns the status and metadata of one run: the agent version that ran, how it ended, its tool calls (never their arguments or results) and what it was charged. It never returns text: the answer is delivered only in the run's stream. A run is visible to the credential that started it (for a token bound to a user, to that user) and to your root key, and is kept for 30 days after it ends. Requires the `runs:r` scope.
2914
+ *
2915
+ * @param {Vectros.GetRunRequest} request
2916
+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.
2917
+ *
2918
+ * @throws {@link Vectros.BadRequestError}
2919
+ * @throws {@link Vectros.UnauthorizedError}
2920
+ * @throws {@link Vectros.ForbiddenError}
2921
+ * @throws {@link Vectros.NotFoundError}
2922
+ *
2923
+ * @example
2924
+ * await client.agents.getRun({
2925
+ * id: "id"
2926
+ * })
2927
+ */
2928
+ getRun(request, requestOptions) {
2929
+ return HttpResponsePromise.fromPromise(this.__getRun(request, requestOptions));
2930
+ }
2931
+ async __getRun(request, requestOptions) {
2932
+ const { id, contextId } = request;
2933
+ const _queryParams = {
2934
+ contextId
2935
+ };
2936
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2937
+ const _headers = mergeHeaders(
2938
+ _authRequest.headers,
2939
+ this._options?.headers,
2940
+ requestOptions?.headers
2941
+ );
2942
+ const _response = await fetcher({
2943
+ url: url_exports.join(
2944
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2945
+ `v1/runs/${url_exports.encodePathParam(id)}`
2946
+ ),
2947
+ method: "GET",
2948
+ headers: _headers,
2949
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2950
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2951
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2952
+ abortSignal: requestOptions?.abortSignal,
2953
+ fetchFn: this._options?.fetch,
2954
+ logging: this._options.logging
2955
+ });
2956
+ if (_response.ok) {
2957
+ return { data: _response.body, rawResponse: _response.rawResponse };
2958
+ }
2959
+ if (_response.error.reason === "status-code") {
2960
+ switch (_response.error.statusCode) {
2961
+ case 400:
2962
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2963
+ case 401:
2964
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2965
+ case 403:
2966
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
2967
+ case 404:
2968
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
2969
+ default:
2970
+ throw new VectrosError({
2971
+ statusCode: _response.error.statusCode,
2972
+ body: _response.error.body,
2973
+ rawResponse: _response.rawResponse
2974
+ });
2975
+ }
2976
+ }
2977
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/runs/{id}");
2978
+ }
2979
+ /**
2980
+ * Starts a run of a stored agent and streams what it does as Server-Sent Events. The response is always `text/event-stream`, whatever `Accept` you send; its `X-Vectros-Run-Id` header names the run. The run's tool calls act as you, with your own permissions, and only through the tools the agent lists. On a prepaid account the run reserves its budget from your inference balance when it starts and returns what its model calls did not use when it ends; a fixed fee per run, tool calls and run time are billed separately, against your plan. Read each event's `type`; ignore types and fields you do not know; stop at the event with `terminal: true`. A stream that ends without one: read the run with `GET /v1/runs/{id}`. Closing the stream stops the run only on a best-effort basis. Requires the `runs:c` scope, and agent runs switched on for your tenant by an account owner.
2981
+ */
2982
+ createRun(request, requestOptions) {
2983
+ return HttpResponsePromise.fromPromise(this.__createRun(request, requestOptions));
2984
+ }
2985
+ async __createRun(request, requestOptions) {
2986
+ const { "Idempotency-Key": idempotencyKey, ..._body } = request;
2987
+ const _authRequest = await this._options.authProvider.getAuthRequest();
2988
+ const _headers = mergeHeaders(
2989
+ _authRequest.headers,
2990
+ this._options?.headers,
2991
+ mergeOnlyDefinedHeaders({ "Idempotency-Key": idempotencyKey }),
2992
+ requestOptions?.headers
2993
+ );
2994
+ const _response = await fetcher({
2995
+ url: url_exports.join(
2996
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment),
2997
+ "v1/runs"
2998
+ ),
2999
+ method: "POST",
3000
+ headers: _headers,
3001
+ contentType: "application/json",
3002
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
3003
+ requestType: "json",
3004
+ body: _body,
3005
+ responseType: "sse",
3006
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
3007
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
3008
+ abortSignal: requestOptions?.abortSignal,
3009
+ fetchFn: this._options?.fetch,
3010
+ logging: this._options.logging
3011
+ });
3012
+ if (_response.ok) {
3013
+ return {
3014
+ data: new Stream({
3015
+ stream: _response.body,
3016
+ parse: (data) => data,
3017
+ signal: requestOptions?.abortSignal,
3018
+ eventShape: {
3019
+ type: "sse"
3020
+ }
3021
+ }),
3022
+ rawResponse: _response.rawResponse
3023
+ };
3024
+ }
3025
+ if (_response.error.reason === "status-code") {
3026
+ switch (_response.error.statusCode) {
3027
+ case 400:
3028
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
3029
+ case 401:
3030
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
3031
+ case 402:
3032
+ throw new PaymentRequiredError(_response.error.body, _response.rawResponse);
3033
+ case 403:
3034
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
3035
+ case 404:
3036
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
3037
+ case 409:
3038
+ throw new ConflictError(_response.error.body, _response.rawResponse);
3039
+ case 413:
3040
+ throw new ContentTooLargeError(_response.error.body, _response.rawResponse);
3041
+ case 422:
3042
+ throw new UnprocessableEntityError(_response.error.body, _response.rawResponse);
3043
+ case 429:
3044
+ throw new TooManyRequestsError(_response.error.body, _response.rawResponse);
3045
+ case 503:
3046
+ throw new ServiceUnavailableError(_response.error.body, _response.rawResponse);
3047
+ default:
3048
+ throw new VectrosError({
3049
+ statusCode: _response.error.statusCode,
3050
+ body: _response.error.body,
3051
+ rawResponse: _response.rawResponse
3052
+ });
3053
+ }
3054
+ }
3055
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/runs");
2414
3056
  }
2415
- }
3057
+ };
2416
3058
  var AuthClient = class {
2417
3059
  constructor(options) {
2418
3060
  this._options = normalizeClientOptionsWithAuth(options);
@@ -2960,9 +3602,7 @@ var AuthClient = class {
2960
3602
  * @example
2961
3603
  * await client.auth.createAccessProfile({
2962
3604
  * contextId: "contextId",
2963
- * body: {
2964
- * principalId: "usr_6ba7b810-9dad-11d1-80b4-00c04fd430c8"
2965
- * }
3605
+ * body: {}
2966
3606
  * })
2967
3607
  */
2968
3608
  createAccessProfile(request, requestOptions) {
@@ -3098,10 +3738,7 @@ var AuthClient = class {
3098
3738
  *
3099
3739
  * @example
3100
3740
  * await client.auth.createAppContext({
3101
- * body: {
3102
- * contextId: "myapp",
3103
- * name: "My Internal App"
3104
- * }
3741
+ * body: {}
3105
3742
  * })
3106
3743
  */
3107
3744
  createAppContext(request, requestOptions) {
@@ -3244,13 +3881,7 @@ var AuthClient = class {
3244
3881
  * @example
3245
3882
  * await client.auth.createRole({
3246
3883
  * contextId: "contextId",
3247
- * body: {
3248
- * roleId: "engineering-member",
3249
- * name: "Engineering Team Member",
3250
- * scopes: [{
3251
- * allowed_actions: ["records:cru", "search:r"]
3252
- * }]
3253
- * }
3884
+ * body: {}
3254
3885
  * })
3255
3886
  */
3256
3887
  createRole(request, requestOptions) {
@@ -3394,9 +4025,7 @@ var AuthClient = class {
3394
4025
  * await client.auth.updateAccessProfile({
3395
4026
  * contextId: "contextId",
3396
4027
  * principalId: "principalId",
3397
- * body: {
3398
- * principalId: "usr_6ba7b810-9dad-11d1-80b4-00c04fd430c8"
3399
- * }
4028
+ * body: {}
3400
4029
  * })
3401
4030
  */
3402
4031
  updateAccessProfile(request, requestOptions) {
@@ -3599,10 +4228,7 @@ var AuthClient = class {
3599
4228
  * @example
3600
4229
  * await client.auth.updateAppContext({
3601
4230
  * contextId: "contextId",
3602
- * body: {
3603
- * contextId: "myapp",
3604
- * name: "My Internal App"
3605
- * }
4231
+ * body: {}
3606
4232
  * })
3607
4233
  */
3608
4234
  updateAppContext(request, requestOptions) {
@@ -3807,13 +4433,7 @@ var AuthClient = class {
3807
4433
  * await client.auth.updateRole({
3808
4434
  * contextId: "contextId",
3809
4435
  * roleId: "roleId",
3810
- * body: {
3811
- * roleId: "engineering-member",
3812
- * name: "Engineering Team Member",
3813
- * scopes: [{
3814
- * allowed_actions: ["records:cru", "search:r"]
3815
- * }]
3816
- * }
4436
+ * body: {}
3817
4437
  * })
3818
4438
  */
3819
4439
  updateRole(request, requestOptions) {
@@ -5265,7 +5885,7 @@ var DocumentsClient = class {
5265
5885
  this._options = normalizeClientOptionsWithAuth(options);
5266
5886
  }
5267
5887
  /**
5268
- * Returns a paginated list of your documents, optionally filtered by folder (`folderId`) and/or owner (`userId` or `scope`). The response is a `{data, nextCursor}` envelope; pass `nextCursor` back as `startFrom` to fetch the next page. Requires the `documents:r` scope.
5888
+ * Returns a paginated list of your documents, optionally filtered by folder (`folderId`), owner (`userId` or `scope`) and/or type (`type`). The response is a `{data, nextCursor}` envelope; pass `nextCursor` back as `startFrom` to fetch the next page. A page can hold fewer documents than `limit`, or none, while `nextCursor` is still set: keep paging until `nextCursor` is null. Requires the `documents:r` scope.
5269
5889
  *
5270
5890
  * @param {Vectros.ListDocumentsRequest} request
5271
5891
  * @param {DocumentsClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -5275,6 +5895,7 @@ var DocumentsClient = class {
5275
5895
  * userId: "550e8400-e29b-41d4-a716-446655440000",
5276
5896
  * scope: "group:eng-team",
5277
5897
  * folderId: "f47ac10b-58cc-4372-a567-0e02b2c3d479",
5898
+ * type: "investigation_report",
5278
5899
  * startFrom: "b3BhcXVlLWN1cnNvci1mcm9tLXRoZS1wcmV2aW91cy1wYWdl"
5279
5900
  * })
5280
5901
  */
@@ -5282,11 +5903,12 @@ var DocumentsClient = class {
5282
5903
  return HttpResponsePromise.fromPromise(this.__listDocuments(request, requestOptions));
5283
5904
  }
5284
5905
  async __listDocuments(request = {}, requestOptions) {
5285
- const { userId, scope, folderId, startFrom, limit } = request;
5906
+ const { userId, scope, folderId, type: type_, startFrom, limit } = request;
5286
5907
  const _queryParams = {
5287
5908
  userId,
5288
5909
  scope,
5289
5910
  folderId,
5911
+ type: type_,
5290
5912
  startFrom,
5291
5913
  limit
5292
5914
  };
@@ -5336,9 +5958,7 @@ var DocumentsClient = class {
5336
5958
  *
5337
5959
  * @example
5338
5960
  * await client.documents.ingestDocument({
5339
- * body: {
5340
- * title: "Patient Intake Form \u2014 Jane Doe"
5341
- * }
5961
+ * body: {}
5342
5962
  * })
5343
5963
  */
5344
5964
  ingestDocument(request, requestOptions) {
@@ -5468,9 +6088,7 @@ var DocumentsClient = class {
5468
6088
  * @example
5469
6089
  * await client.documents.updateDocument({
5470
6090
  * id: "id",
5471
- * body: {
5472
- * title: "Patient Intake Form \u2014 Jane Doe"
5473
- * }
6091
+ * body: {}
5474
6092
  * })
5475
6093
  */
5476
6094
  updateDocument(request, requestOptions) {
@@ -5868,11 +6486,12 @@ var DocumentsClient = class {
5868
6486
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/documents/{id}/download");
5869
6487
  }
5870
6488
  /**
5871
- * Returns the document's full text body when it is retained: retained for text-ingested documents, and for file-uploaded documents unless they were uploaded with `storeText=false` (which discards the extracted text once indexing completes — the original file remains available via `GET /v1/documents/{id}/download`). Returns 404 when the document does not exist, its text was not retained, or extraction has not yet completed. Requires the `documents:r` scope.
6489
+ * Returns the document's full text body when it is retained: retained for text-ingested documents, and for file-uploaded documents unless they were uploaded with `storeText=false` (which discards the extracted text once indexing completes — the original file remains available via `GET /v1/documents/{id}/download`). Returns 404 when the document does not exist, its text was not retained, extraction has not yet completed, or no text could be extracted from its file (see the document's `extraction`). To read a long text in parts, pass `limit` (and `offset` from the second part on): offsets and lengths count Unicode characters (code points), `totalLength` is the length of the whole text, and `nextOffset` is where the next part starts, absent once the end is reached. Requires the `documents:r` scope.
5872
6490
  *
5873
6491
  * @param {Vectros.GetDocumentTextRequest} request
5874
6492
  * @param {DocumentsClient.RequestOptions} requestOptions - Request-specific configuration.
5875
6493
  *
6494
+ * @throws {@link Vectros.BadRequestError}
5876
6495
  * @throws {@link Vectros.NotFoundError}
5877
6496
  *
5878
6497
  * @example
@@ -5884,7 +6503,11 @@ var DocumentsClient = class {
5884
6503
  return HttpResponsePromise.fromPromise(this.__getDocumentText(request, requestOptions));
5885
6504
  }
5886
6505
  async __getDocumentText(request, requestOptions) {
5887
- const { id } = request;
6506
+ const { id, offset, limit } = request;
6507
+ const _queryParams = {
6508
+ offset,
6509
+ limit
6510
+ };
5888
6511
  const _authRequest = await this._options.authProvider.getAuthRequest();
5889
6512
  const _headers = mergeHeaders(
5890
6513
  _authRequest.headers,
@@ -5898,7 +6521,7 @@ var DocumentsClient = class {
5898
6521
  ),
5899
6522
  method: "GET",
5900
6523
  headers: _headers,
5901
- queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
6524
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
5902
6525
  timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
5903
6526
  maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
5904
6527
  abortSignal: requestOptions?.abortSignal,
@@ -5910,6 +6533,8 @@ var DocumentsClient = class {
5910
6533
  }
5911
6534
  if (_response.error.reason === "status-code") {
5912
6535
  switch (_response.error.statusCode) {
6536
+ case 400:
6537
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
5913
6538
  case 404:
5914
6539
  throw new NotFoundError(_response.error.body, _response.rawResponse);
5915
6540
  default:
@@ -6129,9 +6754,7 @@ var FoldersClient = class {
6129
6754
  *
6130
6755
  * @example
6131
6756
  * await client.folders.createFolder({
6132
- * body: {
6133
- * name: "Patient Records 2024"
6134
- * }
6757
+ * body: {}
6135
6758
  * })
6136
6759
  */
6137
6760
  createFolder(request, requestOptions) {
@@ -6259,9 +6882,7 @@ var FoldersClient = class {
6259
6882
  * @example
6260
6883
  * await client.folders.updateFolder({
6261
6884
  * id: "id",
6262
- * body: {
6263
- * name: "Patient Records 2024"
6264
- * }
6885
+ * body: {}
6265
6886
  * })
6266
6887
  */
6267
6888
  updateFolder(request, requestOptions) {
@@ -6394,9 +7015,7 @@ var FoldersClient = class {
6394
7015
  * @example
6395
7016
  * await client.folders.patchFolder({
6396
7017
  * id: "id",
6397
- * body: {
6398
- * name: "Patient Records 2024"
6399
- * }
7018
+ * body: {}
6400
7019
  * })
6401
7020
  */
6402
7021
  patchFolder(request, requestOptions) {
@@ -6611,9 +7230,7 @@ var IdentityClient = class {
6611
7230
  * await client.identity.createEntity({
6612
7231
  * namespace: "team",
6613
7232
  * contextId: "myapp",
6614
- * body: {
6615
- * externalId: "team_eng_platform"
6616
- * }
7233
+ * body: {}
6617
7234
  * })
6618
7235
  */
6619
7236
  createEntity(request, requestOptions) {
@@ -6749,9 +7366,7 @@ var IdentityClient = class {
6749
7366
  * namespace: "team",
6750
7367
  * id: "id",
6751
7368
  * contextId: "myapp",
6752
- * body: {
6753
- * externalId: "team_eng_platform"
6754
- * }
7369
+ * body: {}
6755
7370
  * })
6756
7371
  */
6757
7372
  updateEntity(request, requestOptions) {
@@ -7091,10 +7706,7 @@ var IdentityClient = class {
7091
7706
  * @example
7092
7707
  * await client.identity.updateNamespace({
7093
7708
  * namespace: "team",
7094
- * body: {
7095
- * namespace: "team",
7096
- * specificityRank: 1500
7097
- * }
7709
+ * body: {}
7098
7710
  * })
7099
7711
  */
7100
7712
  updateNamespace(request, requestOptions) {
@@ -7281,10 +7893,7 @@ var IdentityClient = class {
7281
7893
  *
7282
7894
  * @example
7283
7895
  * await client.identity.registerNamespace({
7284
- * body: {
7285
- * namespace: "team",
7286
- * specificityRank: 1500
7287
- * }
7896
+ * body: {}
7288
7897
  * })
7289
7898
  */
7290
7899
  registerNamespace(request, requestOptions) {
@@ -7417,9 +8026,7 @@ var IdentityClient = class {
7417
8026
  *
7418
8027
  * @example
7419
8028
  * await client.identity.createUser({
7420
- * body: {
7421
- * externalId: "usr_12345"
7422
- * }
8029
+ * body: {}
7423
8030
  * })
7424
8031
  */
7425
8032
  createUser(request, requestOptions) {
@@ -7538,6 +8145,7 @@ var IdentityClient = class {
7538
8145
  * @param {IdentityClient.RequestOptions} requestOptions - Request-specific configuration.
7539
8146
  *
7540
8147
  * @throws {@link Vectros.BadRequestError}
8148
+ * @throws {@link Vectros.ForbiddenError}
7541
8149
  * @throws {@link Vectros.NotFoundError}
7542
8150
  * @throws {@link Vectros.ConflictError}
7543
8151
  * @throws {@link Vectros.TooManyRequestsError}
@@ -7545,9 +8153,7 @@ var IdentityClient = class {
7545
8153
  * @example
7546
8154
  * await client.identity.updateUser({
7547
8155
  * id: "550e8400-e29b-41d4-a716-446655440000",
7548
- * body: {
7549
- * externalId: "usr_12345"
7550
- * }
8156
+ * body: {}
7551
8157
  * })
7552
8158
  */
7553
8159
  updateUser(request, requestOptions) {
@@ -7585,6 +8191,8 @@ var IdentityClient = class {
7585
8191
  switch (_response.error.statusCode) {
7586
8192
  case 400:
7587
8193
  throw new BadRequestError(_response.error.body, _response.rawResponse);
8194
+ case 403:
8195
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
7588
8196
  case 404:
7589
8197
  throw new NotFoundError(_response.error.body, _response.rawResponse);
7590
8198
  case 409:
@@ -7607,6 +8215,7 @@ var IdentityClient = class {
7607
8215
  * @param {Vectros.DeleteUserRequest} request
7608
8216
  * @param {IdentityClient.RequestOptions} requestOptions - Request-specific configuration.
7609
8217
  *
8218
+ * @throws {@link Vectros.ForbiddenError}
7610
8219
  * @throws {@link Vectros.NotFoundError}
7611
8220
  * @throws {@link Vectros.ConflictError}
7612
8221
  * @throws {@link Vectros.TooManyRequestsError}
@@ -7646,6 +8255,8 @@ var IdentityClient = class {
7646
8255
  }
7647
8256
  if (_response.error.reason === "status-code") {
7648
8257
  switch (_response.error.statusCode) {
8258
+ case 403:
8259
+ throw new ForbiddenError(_response.error.body, _response.rawResponse);
7649
8260
  case 404:
7650
8261
  throw new NotFoundError(_response.error.body, _response.rawResponse);
7651
8262
  case 409:
@@ -7850,7 +8461,7 @@ var InferenceClient = class {
7850
8461
  this._options = normalizeClientOptionsWithAuth(options);
7851
8462
  }
7852
8463
  /**
7853
- * Returns the whole platform model catalog, whatever your plan: `availableOn` names each model's plan tiers. Each entry also carries the context window and the credit rates per 1K input and output tokens: `regionPricing.base` for global-region requests, `regionPricing.us` for default requests, and `longContext` for prompts over its threshold. A model reached through a `providerAlias` is not listed. Use this to populate model pickers and to validate a request before calling `/v1/chat`, `/v1/rag`, or `/v1/documents/{id}/ask`.
8464
+ * Returns the whole platform model catalog, whatever your plan: `availableOn` names each model's plan tiers. Each entry also carries the context window and the credit rates per 1K input and output tokens: `regionPricing.base` for global-region requests, `regionPricing.us` for default requests, `longContext` for prompts over its threshold, and `cachePricing` for prompt-cache tokens on a model that has cache prices. A model reached through a `providerAlias` is not listed. Use this to populate model pickers and to validate a request before calling `/v1/chat`, `/v1/rag`, or `/v1/documents/{id}/ask`.
7854
8465
  *
7855
8466
  * @param {InferenceClient.RequestOptions} requestOptions - Request-specific configuration.
7856
8467
  *
@@ -7894,7 +8505,7 @@ var InferenceClient = class {
7894
8505
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/v1/models");
7895
8506
  }
7896
8507
  /**
7897
- * Streams a model response as Server-Sent Events (SSE). Send the full conversation history in the `messages` array; a message with role `system` is extracted and used as the system prompt. On a pre-paid account, token cost is debited from your inference balance; usage-billed accounts accrue it for post-billing. A request routed through your own `providerAlias` incurs no Vectros token cost. A small per-call flat fee is charged to your monthly credit allowance, except when the call fails on the server side. Requires the `inference:r` scope.
8508
+ * Streams a model response as Server-Sent Events (SSE). Send the full conversation history in the `messages` array; a message with role `system` is extracted and used as the system prompt. On a pre-paid account, token cost is debited from your inference balance; usage-billed accounts accrue it for post-billing. A request routed through your own `providerAlias` incurs no Vectros token cost. A per-call platform fee is charged to your monthly credit allowance, except when the call fails on the server side: 0.2 credits for a call of up to 60 seconds, then 1 credit per 5 minutes of the call's duration. Requires the `inference:r` scope.
7898
8509
  */
7899
8510
  chatInference(request, requestOptions) {
7900
8511
  return HttpResponsePromise.fromPromise(this.__chatInference(request, requestOptions));
@@ -7966,7 +8577,7 @@ var InferenceClient = class {
7966
8577
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/v1/chat");
7967
8578
  }
7968
8579
  /**
7969
- * Loads a single document's extracted text, supplies it as context, and streams a model answer about it. The document must be fully indexed. If the document exceeds the 32K-token cap, the call returns 413 with no credits charged — use `POST /v1/rag` instead to answer over larger or multi-document collections. Requires the `inference:r` scope.
8580
+ * Loads a single document's extracted text, supplies it as context, and streams a model answer about it. The document must have finished processing and have text. If the document exceeds the 32K-token cap, the call returns 413 with no credits charged — use `POST /v1/rag` instead to answer over larger or multi-document collections. Requires the `inference:r` scope.
7970
8581
  */
7971
8582
  documentAsk(request, requestOptions) {
7972
8583
  return HttpResponsePromise.fromPromise(this.__documentAsk(request, requestOptions));
@@ -9101,8 +9712,7 @@ var SchemasClient = class {
9101
9712
  * }],
9102
9713
  * capabilities: {
9103
9714
  * "auditHistory": true
9104
- * },
9105
- * allowedSurfaces: ["record"]
9715
+ * }
9106
9716
  * }
9107
9717
  * })
9108
9718
  */
@@ -9232,11 +9842,7 @@ var SchemasClient = class {
9232
9842
  * @example
9233
9843
  * await client.schemas.updateSchema({
9234
9844
  * id: "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
9235
- * body: {
9236
- * typeName: "intake_form",
9237
- * displayName: "Client Intake Form",
9238
- * allowedSurfaces: ["record"]
9239
- * }
9845
+ * body: {}
9240
9846
  * })
9241
9847
  */
9242
9848
  updateSchema(request, requestOptions) {
@@ -9776,7 +10382,7 @@ var ScriptsClient = class {
9776
10382
  return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/v1/scripts/{id}");
9777
10383
  }
9778
10384
  /**
9779
- * 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.
10385
+ * 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. Also refused with a retryable 409, deleting nothing, when it cannot be told yet whether this is the newest version (for example just after several of this name's newest versions were deleted, or while its first version is gone and the listing has not caught up) and a `"latest"` rule depends on the script: try again shortly.
9780
10386
  *
9781
10387
  * @param {Vectros.DeleteScriptRequest} request
9782
10388
  * @param {ScriptsClient.RequestOptions} requestOptions - Request-specific configuration.
@@ -10040,17 +10646,7 @@ var TriggersClient = class {
10040
10646
  *
10041
10647
  * @example
10042
10648
  * await client.triggers.createTrigger({
10043
- * body: {
10044
- * name: "on-intake-create",
10045
- * firingSource: {
10046
- * schemaId: "sch_9f8e7d6c",
10047
- * event: "CREATE"
10048
- * },
10049
- * scriptRef: {
10050
- * name: "notify-assignee",
10051
- * version: "3"
10052
- * }
10053
- * }
10649
+ * body: {}
10054
10650
  * })
10055
10651
  */
10056
10652
  createTrigger(request, requestOptions) {
@@ -10179,17 +10775,7 @@ var TriggersClient = class {
10179
10775
  * @example
10180
10776
  * await client.triggers.updateTrigger({
10181
10777
  * id: "id",
10182
- * body: {
10183
- * name: "on-intake-create",
10184
- * firingSource: {
10185
- * schemaId: "sch_9f8e7d6c",
10186
- * event: "CREATE"
10187
- * },
10188
- * scriptRef: {
10189
- * name: "notify-assignee",
10190
- * version: "3"
10191
- * }
10192
- * }
10778
+ * body: {}
10193
10779
  * })
10194
10780
  */
10195
10781
  updateTrigger(request, requestOptions) {
@@ -10314,6 +10900,9 @@ var VectrosClient = class {
10314
10900
  get auth() {
10315
10901
  return this._auth ?? (this._auth = new AuthClient(this._options));
10316
10902
  }
10903
+ get agents() {
10904
+ return this._agents ?? (this._agents = new AgentsClient(this._options));
10905
+ }
10317
10906
  get documents() {
10318
10907
  return this._documents ?? (this._documents = new DocumentsClient(this._options));
10319
10908
  }
@@ -10384,7 +10973,7 @@ import {
10384
10973
  ListToolsRequestSchema,
10385
10974
  ReadResourceRequestSchema
10386
10975
  } from "@modelcontextprotocol/sdk/types.js";
10387
- import { z as z25 } from "zod";
10976
+ import { z as z28 } from "zod";
10388
10977
 
10389
10978
  // src/auth.ts
10390
10979
  var KEY_RE = /^(sk|ssk|st)_(live|test)_/;
@@ -10428,8 +11017,8 @@ function warnOnSuboptimalKey(key, log) {
10428
11017
 
10429
11018
  // src/build-info.ts
10430
11019
  var BUILD_INFO = {
10431
- mcpServer: true ? "0.18.2" : "dev",
10432
- sdk: true ? "0.48.0" : "dev"
11020
+ mcpServer: true ? "0.19.0" : "dev",
11021
+ sdk: true ? "0.49.0" : "dev"
10433
11022
  };
10434
11023
 
10435
11024
  // src/log.ts
@@ -10685,6 +11274,11 @@ ${detail}${trailer}`
10685
11274
  };
10686
11275
  }
10687
11276
 
11277
+ // src/tools/limits.ts
11278
+ var MAX_OWNERSHIP_SCOPES = 2;
11279
+ var MAX_SCOPE_FILTERS = 16;
11280
+ var MAX_CONTENT_TYPES = 2;
11281
+
10688
11282
  // src/tools/hybrid_search.ts
10689
11283
  var MCP_DEFAULT_LIMIT = 3;
10690
11284
  var MCP_MAX_LIMIT = 50;
@@ -10727,11 +11321,11 @@ var inputSchema = {
10727
11321
  folderId: z.string().optional().describe("Scope to content in this EXACT folder (Vectros folder id)."),
10728
11322
  rootFolderId: z.string().optional().describe("Scope to content under this folder AND all its descendants (subtree-root folder id)."),
10729
11323
  // Content narrowing.
10730
- contentTypes: z.array(z.enum(["documents", "records"])).optional().describe('Narrow to content types. ["documents"] or ["records"]; omit for unified (both).'),
11324
+ contentTypes: z.array(z.enum(["documents", "records"])).max(MAX_CONTENT_TYPES, `contentTypes accepts at most ${MAX_CONTENT_TYPES} entries`).optional().describe('Narrow to content types. ["documents"] or ["records"]; omit for unified (both).'),
10731
11325
  typeName: z.string().optional().describe(
10732
11326
  'Restrict hits to this schema type (e.g. "patient", "runbook"). Applies to BOTH documents and records \u2014 combine with contentTypes to scope within one content type. Untyped content never matches.'
10733
11327
  ),
10734
- filters: z.record(z.unknown()).optional().describe(
11328
+ filters: z.record(z.string(), z.unknown()).optional().describe(
10735
11329
  'Field-level metadata filters (AND-combined). Value = scalar (equality), array (OR-set), or operator map: $eq/$ne/$gt/$gte/$lt/$lte (scalar) or $in/$nin (array). e.g. {"status":"open"} or {"price":{"$gte":100,"$lte":500}}.'
10736
11330
  ),
10737
11331
  // Ownership.
@@ -10739,7 +11333,7 @@ var inputSchema = {
10739
11333
  scope: z.string().optional().describe(
10740
11334
  '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.'
10741
11335
  ),
10742
- scopeFilters: z.array(z.string()).min(1, "scopeFilters must name at least one dimension when supplied").optional().describe(
11336
+ scopeFilters: z.array(z.string()).min(1, "scopeFilters must name at least one dimension when supplied").max(MAX_SCOPE_FILTERS, `scopeFilters accepts at most ${MAX_SCOPE_FILTERS} entries`).optional().describe(
10743
11337
  '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.'
10744
11338
  ),
10745
11339
  // Date window.
@@ -11260,7 +11854,7 @@ var inputSchema5 = {
11260
11854
  status: z5.string().optional().describe("Record lifecycle status. Defaults to ACTIVE server-side."),
11261
11855
  folderId: z5.string().optional().describe("Group this record into a folder."),
11262
11856
  userId: z5.string().optional().describe("Owning user id."),
11263
- scopes: z5.array(z5.string()).optional().describe(
11857
+ scopes: z5.array(z5.string()).max(MAX_OWNERSHIP_SCOPES, `scopes accepts at most ${MAX_OWNERSHIP_SCOPES} entries`).optional().describe(
11264
11858
  '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.'
11265
11859
  )
11266
11860
  };
@@ -11318,7 +11912,7 @@ var itemSchema = z6.strictObject({
11318
11912
  status: z6.string().optional().describe("Record lifecycle status. Defaults to ACTIVE server-side."),
11319
11913
  folderId: z6.string().optional().describe("Group this record into a folder."),
11320
11914
  userId: z6.string().optional().describe("Owning user id."),
11321
- scopes: z6.array(z6.string()).optional().describe(
11915
+ scopes: z6.array(z6.string()).max(MAX_OWNERSHIP_SCOPES, `scopes accepts at most ${MAX_OWNERSHIP_SCOPES} entries`).optional().describe(
11322
11916
  "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."
11323
11917
  )
11324
11918
  });
@@ -11475,7 +12069,7 @@ import { z as z10 } from "zod";
11475
12069
  // src/tools/provider-alias.ts
11476
12070
  import { z as z9 } from "zod";
11477
12071
  var providerAliasInput = z9.string().min(1, "providerAlias must be non-empty when supplied").optional().describe(
11478
- "Route THIS call through your own model provider instead of the platform-hosted default, by the alias of a provider config your account has activated. It works only after your account has set up that provider and signed the platform's risk-acceptance waiver; without both, the platform refuses the call with a 403, which is returned to you as written. When the waiver is the cause, the 403 carries an `errorCode` that says which case it is: `WAIVER_NOT_SIGNED` (the waiver has not been signed), `WAIVER_TEXT_CHANGED` (it was signed, but its text changed afterwards, so the earlier signature no longer counts), or `WAIVER_REVOKED` (an owner revoked it). An account owner resolves each in the developer portal (Model Providers); retrying the call does not help. If your account has accepted the Business Associate Agreement with Vectros in the developer portal, an account owner must also have attested that provider config in the developer portal (Model Providers); until then the platform refuses the call with a 403 that says it needs a BAA-holder attestation. A call served by your own provider leaves the Vectros perimeter. Omit it (the default) to use the platform-hosted path. When set, `model` names the model on your provider's own id space, and falls back to that provider config's default model when omitted."
12072
+ "Route THIS call through your own model provider instead of the platform-hosted default, by the alias of a provider config your account has activated. It works only after your account has set up that provider and signed the platform's risk-acceptance waiver; without both, the platform refuses the call with a 403, which is returned to you as written. When the waiver is the cause, the 403 carries an `errorCode` that says which case it is: `WAIVER_NOT_SIGNED` (the waiver has not been signed), `WAIVER_TEXT_CHANGED` (Vectros now requires a newer version of the waiver than the one in force for your account), or `WAIVER_REVOKED` (an owner revoked it). An account owner resolves each in the developer portal (Model Providers); retrying the call does not help. If your account has accepted the Business Associate Agreement with Vectros in the developer portal, an account owner must also have attested that provider config in the developer portal (Model Providers); until then the platform refuses the call with a 403 that says it needs a BAA-holder attestation. A call served by your own provider leaves the Vectros perimeter. Omit it (the default) to use the platform-hosted path. When set, `model` names the model on your provider's own id space, and falls back to that provider config's default model when omitted."
11479
12073
  );
11480
12074
 
11481
12075
  // src/tools/rag_ask.ts
@@ -11502,14 +12096,14 @@ var inputSchema9 = {
11502
12096
  scope: z10.string().optional().describe(
11503
12097
  '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.'
11504
12098
  ),
11505
- scopeFilters: z10.array(z10.string()).min(1, "scopeFilters must name at least one dimension when supplied").optional().describe(
12099
+ scopeFilters: z10.array(z10.string()).min(1, "scopeFilters must name at least one dimension when supplied").max(MAX_SCOPE_FILTERS, `scopeFilters accepts at most ${MAX_SCOPE_FILTERS} entries`).optional().describe(
11506
12100
  '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`.'
11507
12101
  ),
11508
12102
  folderId: z10.string().optional().describe("Restrict retrieval to this exact folder."),
11509
12103
  rootFolderId: z10.string().optional().describe("Restrict retrieval to this folder and all its descendants."),
11510
12104
  typeName: z10.string().optional().describe("Restrict record retrieval to this schema type."),
11511
- contentTypes: z10.array(z10.enum(["documents", "records"])).optional().describe('Narrow retrieval to content types. ["documents"] or ["records"]; omit for both.'),
11512
- filters: z10.record(z10.unknown()).optional().describe(
12105
+ contentTypes: z10.array(z10.enum(["documents", "records"])).max(MAX_CONTENT_TYPES, `contentTypes accepts at most ${MAX_CONTENT_TYPES} entries`).optional().describe('Narrow retrieval to content types. ["documents"] or ["records"]; omit for both.'),
12106
+ filters: z10.record(z10.string(), z10.unknown()).optional().describe(
11513
12107
  '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"}.'
11514
12108
  ),
11515
12109
  createdAfter: z10.string().optional().describe(
@@ -11784,7 +12378,7 @@ function isNotAvailable(err) {
11784
12378
  var documentGet = ({ client, log }) => ({
11785
12379
  name: "document_get",
11786
12380
  title: "Get document metadata (and optionally text)",
11787
- 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.",
12381
+ 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) or no text could be extracted from the file (`extraction.outcome` other than OK/TRUNCATED, e.g. an image or a scanned page) \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.",
11788
12382
  inputSchema: inputSchema12,
11789
12383
  // A pure read — never creates, modifies, or deletes anything server-side.
11790
12384
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
@@ -11810,7 +12404,7 @@ var documentGet = ({ client, log }) => ({
11810
12404
  if (isNotAvailable(textErr)) {
11811
12405
  log.debug(
11812
12406
  { tool: "document_get", id },
11813
- "document_get text unavailable (not retained \u2014 storeText:false upload)"
12407
+ "document_get text unavailable (not retained, or no text could be extracted from the file)"
11814
12408
  );
11815
12409
  extra = { ...extra, textAvailable: false };
11816
12410
  } else {
@@ -11863,10 +12457,12 @@ var inputSchema13 = {
11863
12457
  to: z14.string().optional().describe("Lookup mode (range): inclusive upper bound; requires `from`."),
11864
12458
  prefix: z14.string().optional().describe("Lookup mode (prefix): match values starting with this. Range-enabled string fields only."),
11865
12459
  order: z14.enum(["asc", "desc"]).optional().describe(
11866
- "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."
12460
+ "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). Refused without `field`."
11867
12461
  ),
11868
- type: z14.string().optional().describe("Lookup mode: the document type (the bound schema's type). Required with `field`."),
11869
- // List-mode args:
12462
+ type: z14.string().min(1, "type must be non-empty: omit it to list every type").optional().describe(
12463
+ "The document type (the bound schema's type). Required with `field` (lookup mode); in list mode it narrows the list to documents of this type. The list filter applies page by page: a page can hold fewer documents than `limit`, or none, while `nextCursor` is set, so keep paging until `nextCursor` is null before concluding there are none. For a large collection, hybrid_search with `typeName` finds documents of one type directly."
12464
+ ),
12465
+ // List-mode args (`type` above applies to both modes):
11870
12466
  folderId: z14.string().optional().describe("List mode: only documents in this folder (Vectros folder id)."),
11871
12467
  userId: z14.string().optional().describe("List mode: scope to documents owned by this user."),
11872
12468
  scope: z14.string().optional().describe(
@@ -11880,7 +12476,7 @@ var inputSchema13 = {
11880
12476
  var documentQuery = ({ client, log }) => ({
11881
12477
  name: "document_query",
11882
12478
  title: "Document query (list or lookup)",
11883
- 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.",
12479
+ 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 `type`/`folderId`/`userId`/`scope` (`namespace:value`). The `type` filter is applied page by page, so a page can be short or empty while `nextCursor` is set: keep paging before concluding there are none.\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.",
11884
12480
  inputSchema: inputSchema13,
11885
12481
  // A pure read — never creates, modifies, or deletes anything server-side.
11886
12482
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
@@ -11939,7 +12535,19 @@ var documentQuery = ({ client, log }) => ({
11939
12535
  "document_query lookup ok"
11940
12536
  );
11941
12537
  } else {
12538
+ const strayLookupArgs = ["value", "from", "to", "prefix", "order"].filter(
12539
+ (k) => args[k] !== void 0
12540
+ );
12541
+ if (strayLookupArgs.length > 0) {
12542
+ return toolError(
12543
+ "document_query",
12544
+ new Error(
12545
+ `Lookup arguments need 'field' (and 'type'): ${strayLookupArgs.map((k) => `'${k}'`).join(", ")}. Without 'field' the call lists documents: filter the list with 'type', 'folderId', 'userId' or 'scope'.`
12546
+ )
12547
+ );
12548
+ }
11942
12549
  page = await client.documents.listDocuments({
12550
+ type,
11943
12551
  folderId: args.folderId,
11944
12552
  userId: args.userId,
11945
12553
  scope: args.scope,
@@ -11947,7 +12555,7 @@ var documentQuery = ({ client, log }) => ({
11947
12555
  limit
11948
12556
  });
11949
12557
  log.debug(
11950
- { tool: "document_query", mode: "list", limit, returned: pageItems(page).length },
12558
+ { tool: "document_query", mode: "list", type, limit, returned: pageItems(page).length },
11951
12559
  "document_query list ok"
11952
12560
  );
11953
12561
  }
@@ -11982,7 +12590,7 @@ var inputSchema14 = {
11982
12590
  "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."
11983
12591
  ),
11984
12592
  userId: z15.string().optional().describe("Reassign the owning user (Vectros UUID)."),
11985
- scopes: z15.array(z15.string()).optional().describe(
12593
+ scopes: z15.array(z15.string()).max(MAX_OWNERSHIP_SCOPES, `scopes accepts at most ${MAX_OWNERSHIP_SCOPES} entries`).optional().describe(
11986
12594
  '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).'
11987
12595
  ),
11988
12596
  expectedVersion: z15.number().int().optional().describe(
@@ -12126,7 +12734,7 @@ var inputSchema17 = {
12126
12734
  "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."
12127
12735
  ),
12128
12736
  userId: z18.string().optional().describe("Owning user (Vectros UUID)."),
12129
- scopes: z18.array(z18.string()).optional().describe(
12737
+ scopes: z18.array(z18.string()).max(MAX_OWNERSHIP_SCOPES, `scopes accepts at most ${MAX_OWNERSHIP_SCOPES} entries`).optional().describe(
12130
12738
  '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.'
12131
12739
  )
12132
12740
  };
@@ -12172,7 +12780,7 @@ var inputSchema18 = {
12172
12780
  name: z19.string().optional().describe("New folder name. Omit to keep the current name."),
12173
12781
  description: z19.string().optional().describe("New description. Omit to leave unchanged."),
12174
12782
  userId: z19.string().optional().describe("Reassign the owning user (Vectros UUID)."),
12175
- scopes: z19.array(z19.string()).optional().describe(
12783
+ scopes: z19.array(z19.string()).max(MAX_OWNERSHIP_SCOPES, `scopes accepts at most ${MAX_OWNERSHIP_SCOPES} entries`).optional().describe(
12176
12784
  '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).'
12177
12785
  ),
12178
12786
  expectedVersion: z19.number().int().optional().describe(
@@ -12221,7 +12829,7 @@ var inputSchema19 = {
12221
12829
  var folderDelete = ({ client, log }) => ({
12222
12830
  name: "folder_delete",
12223
12831
  title: "Delete a folder",
12224
- 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 the record on that basis: if the record should be kept, tell the user to 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.',
12832
+ 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: 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 the record on that basis: if the record should be kept, tell the user to 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.',
12225
12833
  inputSchema: inputSchema19,
12226
12834
  // Deletes. Idempotent in the standard REST sense: the end state ("this id no longer
12227
12835
  // resolves") is the same whether this is the first delete or a repeat of one.
@@ -12374,14 +12982,14 @@ var inputSchema21 = {
12374
12982
  // Common (both modes):
12375
12983
  folderId: z21.string().optional().describe("Optional folder to ingest into. Default: tenant root."),
12376
12984
  userId: z21.string().optional().describe("Owning user ID. Optional."),
12377
- scopes: z21.array(z21.string()).optional().describe(
12985
+ scopes: z21.array(z21.string()).max(MAX_OWNERSHIP_SCOPES, `scopes accepts at most ${MAX_OWNERSHIP_SCOPES} entries`).optional().describe(
12378
12986
  "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."
12379
12987
  )
12380
12988
  };
12381
12989
  var documentIngest = ({ client, log, transport, ingestRoot }) => ({
12382
12990
  name: "document_ingest",
12383
12991
  title: "Ingest a new document (text body or file upload)",
12384
- 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 `document_get` until indexStatus is INDEXED. EXCEPTION \u2014 re-ingesting file mode against an externalId that already has a document (response `created:false`): the file body is replaced by ANY such re-ingest, whether or not `upsert` was set (`upsert` there only additionally applies `payload`/`title` to the matched document). The document keeps serving the OLD file's bytes until the new one is adopted, and indexStatus already reads INDEXED left over from that old file, so polling it returns immediately without waiting for the new content. Poll `document_get` and watch `fileItemId` instead \u2014 once it differs from the value it held before this call, the new file has been adopted. Re-request any download URL after that: one minted before adoption can stop working even within its stated `downloadExpires`.\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; in FILE MODE a re-ingest against an existing externalId needs documents:u). TEXT MODE: without `upsert`, the existing document's content is genuinely unchanged. FILE MODE: as noted above, a re-ingest against an existing externalId always replaces the file body regardless of `upsert` \u2014 only the `payload`/`title` metadata overwrite is gated by 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). An `externalId` with no `schemaId` is refused (400) unless you also pass `confirmUntyped:true` to confirm that an untyped document is intended. 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`.",
12992
+ 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 `document_get` until indexStatus is terminal: INDEXED, SKIPPED (no indexable text: `extraction.outcome` says why, e.g. NO_TEXT for an image or a scanned page), STORED (indexMode NONE) or FAILED. EXCEPTION \u2014 re-ingesting file mode against an externalId that already has a document (response `created:false`): the file body is replaced by ANY such re-ingest, whether or not `upsert` was set (`upsert` there only additionally applies `payload`/`title` to the matched document). The document keeps serving the OLD file's bytes until the new one is adopted, and indexStatus already reads INDEXED left over from that old file, so polling it returns immediately without waiting for the new content. Poll `document_get` and watch `fileItemId` instead \u2014 once it differs from the value it held before this call, the new file has been adopted. Re-request any download URL after that: one minted before adoption can stop working even within its stated `downloadExpires`.\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; in FILE MODE a re-ingest against an existing externalId needs documents:u). TEXT MODE: without `upsert`, the existing document's content is genuinely unchanged. FILE MODE: as noted above, a re-ingest against an existing externalId always replaces the file body regardless of `upsert` \u2014 only the `payload`/`title` metadata overwrite is gated by 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). An `externalId` with no `schemaId` is refused (400) unless you also pass `confirmUntyped:true` to confirm that an untyped document is intended. 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`.",
12385
12993
  inputSchema: inputSchema21,
12386
12994
  // Creates by default, idempotent ONLY when the caller supplies `externalId` (optional,
12387
12995
  // per the doc comment above) — re-ingest then returns the existing document rather than
@@ -12523,7 +13131,7 @@ var documentIngest = ({ client, log, transport, ingestRoot }) => ({
12523
13131
  "document_ingest file ok"
12524
13132
  );
12525
13133
  const uploadCreated = upload?.created;
12526
- const note = uploadCreated === false ? "File replaced: this re-ingest matched an existing externalId, which always replaces that document's file body (upsert or not \u2014 upsert only additionally applies payload/title to it). The next document_get call may already show indexStatus: INDEXED \u2014 that is left over from the PREVIOUS file, not confirmation the new one is ready, and the document keeps serving the old file's bytes until adoption completes. Poll document_get(id) and watch fileItemId instead: once it differs from the value it held before this call, the new file has been adopted. Any download URL already held for this document was minted for the old file and can stop working before its stated downloadExpires once adoption happens \u2014 request a fresh one after fileItemId changes." : "File uploaded; indexing is asynchronous. Poll document_get(id) until indexStatus is INDEXED.";
13134
+ const note = uploadCreated === false ? "File replaced: this re-ingest matched an existing externalId, which always replaces that document's file body (upsert or not \u2014 upsert only additionally applies payload/title to it). The next document_get call may already show indexStatus: INDEXED \u2014 that is left over from the PREVIOUS file, not confirmation the new one is ready, and the document keeps serving the old file's bytes until adoption completes. Poll document_get(id) and watch fileItemId instead: once it differs from the value it held before this call, the new file has been adopted. Any download URL already held for this document was minted for the old file and can stop working before its stated downloadExpires once adoption happens \u2014 request a fresh one after fileItemId changes." : "File uploaded; indexing is asynchronous. Poll document_get(id) until indexStatus is INDEXED, SKIPPED (no indexable text; see extraction.outcome), STORED or FAILED.";
12527
13135
  return {
12528
13136
  content: [
12529
13137
  {
@@ -12696,6 +13304,365 @@ var versionHistory = ({ client, log }) => ({
12696
13304
  });
12697
13305
  var version_history_default = versionHistory;
12698
13306
 
13307
+ // src/tools/agent_list.ts
13308
+ import { z as z24 } from "zod";
13309
+ var MCP_DEFAULT_LIMIT6 = 10;
13310
+ var MCP_MAX_LIMIT6 = 100;
13311
+ function toAgentSummary(agent) {
13312
+ return {
13313
+ id: agent.id,
13314
+ name: agent.name,
13315
+ description: agent.description,
13316
+ latestVersion: agent.latestVersion,
13317
+ status: agent.status
13318
+ };
13319
+ }
13320
+ var inputSchema24 = {
13321
+ includeRetired: z24.boolean().optional().describe("Also list retired and purged agents (neither can be run). Default false."),
13322
+ startFrom: z24.string().optional().describe("Pagination cursor: pass the `nextCursor` from the previous page to fetch the next."),
13323
+ limit: z24.number().int().min(1).max(MCP_MAX_LIMIT6).optional().describe(`Max agents per page. Default ${MCP_DEFAULT_LIMIT6}, max ${MCP_MAX_LIMIT6}.`)
13324
+ };
13325
+ var agentList = ({ client, log }) => ({
13326
+ name: "agent_list",
13327
+ title: "List agents",
13328
+ description: "List the stored agents you can run with agent_run, newest first. Each is returned as its `id`, `name`, `description`, `latestVersion` and `status`; only an `ACTIVE` agent can be run. Retired and purged agents are left out unless `includeRetired` is true. Returns a `{ data, nextCursor }` page: a non-null `nextCursor` means more remain, pass it back as `startFrom`. Needs the `runs:c` or `agents:r` scope; running a listed agent needs `runs:c`, so a credential with only `agents:r` can list agents but not run them.",
13329
+ inputSchema: inputSchema24,
13330
+ // A pure read: it lists definitions and changes nothing.
13331
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
13332
+ handler: async (args) => {
13333
+ const limit = args.limit ?? MCP_DEFAULT_LIMIT6;
13334
+ try {
13335
+ const page = await client.agents.listAgents({
13336
+ includeRetired: args.includeRetired,
13337
+ startFrom: args.startFrom,
13338
+ limit
13339
+ });
13340
+ const data = (page.data ?? []).map(toAgentSummary);
13341
+ const nextCursor = page.nextCursor ?? null;
13342
+ log.debug({ tool: "agent_list", limit, returned: data.length }, "agent_list ok");
13343
+ return { content: [{ type: "text", text: JSON.stringify({ data, nextCursor }, null, 2) }] };
13344
+ } catch (err) {
13345
+ log.warn({ tool: "agent_list", err: String(err) }, "agent_list failed");
13346
+ return toolError("agent_list", err);
13347
+ }
13348
+ }
13349
+ });
13350
+ var agent_list_default = agentList;
13351
+
13352
+ // src/tools/agent_run.ts
13353
+ import { randomUUID } from "crypto";
13354
+ import { z as z25 } from "zod";
13355
+
13356
+ // src/run-stream.ts
13357
+ var TEXT_PROGRESS_CHARS = 256;
13358
+ var HEARTBEAT_MS = 15e3;
13359
+ var TERMINAL_STATUS = {
13360
+ "run.completed": "COMPLETED",
13361
+ "run.failed": "FAILED",
13362
+ "run.cancelled": "CANCELLED"
13363
+ };
13364
+ function str(v) {
13365
+ return typeof v === "string" && v.length > 0 ? v : void 0;
13366
+ }
13367
+ function num(v) {
13368
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
13369
+ }
13370
+ async function consumeRunStream(stream, initialRunId, onProgress, heartbeatMs = HEARTBEAT_MS) {
13371
+ const result = {
13372
+ runId: initialRunId,
13373
+ terminal: false,
13374
+ status: "UNKNOWN",
13375
+ text: "",
13376
+ toolCalls: []
13377
+ };
13378
+ const blocks = [];
13379
+ let pending = "";
13380
+ let unsentChars = 0;
13381
+ const emit = async (message) => {
13382
+ if (!onProgress) return;
13383
+ try {
13384
+ await onProgress(message);
13385
+ } catch {
13386
+ }
13387
+ };
13388
+ let heartbeat;
13389
+ let lastEventAt = Date.now();
13390
+ if (onProgress) {
13391
+ heartbeat = setInterval(() => {
13392
+ if (Date.now() - lastEventAt >= heartbeatMs) {
13393
+ lastEventAt = Date.now();
13394
+ void emit("run still working");
13395
+ }
13396
+ }, Math.max(1, Math.floor(heartbeatMs / 3)));
13397
+ heartbeat.unref?.();
13398
+ }
13399
+ try {
13400
+ for await (const raw of stream) {
13401
+ lastEventAt = Date.now();
13402
+ if (!raw || typeof raw !== "object") continue;
13403
+ const ev = raw;
13404
+ result.runId ??= str(ev.runId);
13405
+ const type = typeof ev.type === "string" ? ev.type : "";
13406
+ switch (type) {
13407
+ case "run.started":
13408
+ result.agentId = str(ev.agentId) ?? result.agentId;
13409
+ result.agentVersion = num(ev.agentVersion) ?? result.agentVersion;
13410
+ await emit("run started");
13411
+ break;
13412
+ case "message.delta": {
13413
+ const piece = typeof ev.text === "string" ? ev.text : "";
13414
+ pending += piece;
13415
+ unsentChars += piece.length;
13416
+ if (unsentChars >= TEXT_PROGRESS_CHARS) {
13417
+ unsentChars = 0;
13418
+ await emit(`answer: ${blocks.join("\n\n").length + pending.length} characters so far`);
13419
+ }
13420
+ break;
13421
+ }
13422
+ case "message.completed": {
13423
+ const full = str(ev.text) ?? pending;
13424
+ if (full.length > 0) blocks.push(full);
13425
+ pending = "";
13426
+ unsentChars = 0;
13427
+ await emit("model call completed");
13428
+ break;
13429
+ }
13430
+ case "tool.completed": {
13431
+ const call = {
13432
+ tool: str(ev.tool),
13433
+ outcome: str(ev.outcome),
13434
+ code: str(ev.code)
13435
+ };
13436
+ result.toolCalls.push(call);
13437
+ await emit(`tool ${call.tool ?? "call"}: ${call.outcome ?? "ended"}`);
13438
+ break;
13439
+ }
13440
+ default:
13441
+ break;
13442
+ }
13443
+ if (ev.terminal === true || Object.hasOwn(TERMINAL_STATUS, type)) {
13444
+ result.terminal = true;
13445
+ result.status = str(ev.status) ?? TERMINAL_STATUS[type] ?? "ENDED";
13446
+ result.reason = str(ev.reason);
13447
+ result.errorCode = str(ev.errorCode);
13448
+ if (typeof ev.settled === "boolean" || ev.inferenceBalanceCentsChargedMilli !== void 0 || ev.inferenceBalanceCentsRefundedMilli !== void 0) {
13449
+ result.charged = {
13450
+ settled: typeof ev.settled === "boolean" ? ev.settled : void 0,
13451
+ inferenceBalanceCentsChargedMilli: num(ev.inferenceBalanceCentsChargedMilli),
13452
+ inferenceBalanceCentsRefundedMilli: num(ev.inferenceBalanceCentsRefundedMilli)
13453
+ };
13454
+ }
13455
+ break;
13456
+ }
13457
+ }
13458
+ } catch (err) {
13459
+ result.streamError = err instanceof Error ? err.message : String(err);
13460
+ } finally {
13461
+ if (heartbeat) clearInterval(heartbeat);
13462
+ }
13463
+ if (pending.length > 0) blocks.push(pending);
13464
+ result.text = blocks.join("\n\n");
13465
+ return result;
13466
+ }
13467
+
13468
+ // src/tools/agent_run.ts
13469
+ var RUN_ID_HEADER = "x-vectros-run-id";
13470
+ var MAX_INPUT_CHARS = 1e5;
13471
+ var MAX_INPUT_BYTES = 24e4;
13472
+ function encodedInputBytes(v) {
13473
+ return Buffer.byteLength(JSON.stringify(v), "utf8");
13474
+ }
13475
+ var TERMINAL_EVENT_TYPES = /* @__PURE__ */ new Set(["run.completed", "run.failed", "run.cancelled"]);
13476
+ var ENDED_STATUSES = /* @__PURE__ */ new Set(["COMPLETED", "FAILED", "CANCELLED", "EXPIRED"]);
13477
+ var inputSchema25 = {
13478
+ agentId: z25.string().min(1, "agentId must be non-empty").describe("The agent to run: an `id` from agent_list."),
13479
+ input: z25.string().min(1, "input must be non-empty").max(MAX_INPUT_CHARS, `input accepts at most ${MAX_INPUT_CHARS} characters`).refine(
13480
+ (v) => encodedInputBytes(v) <= MAX_INPUT_BYTES,
13481
+ `input accepts at most ${MAX_INPUT_BYTES} bytes as sent (a JSON string in UTF-8)`
13482
+ ).describe(
13483
+ `What the agent is asked, 1 to ${MAX_INPUT_CHARS} characters and at most ${MAX_INPUT_BYTES} bytes as sent (a JSON string in UTF-8; most control characters other than newline and tab count six bytes).`
13484
+ ),
13485
+ agentVersion: z25.number().int().min(1).optional().describe("The agent version to run. Default: its latest version."),
13486
+ maxInferenceCents: z25.number().int().min(1).optional().describe(
13487
+ "The most this run's model calls may cost, in US cents. It can only lower the agent's own budget (a higher value is refused); a value below the platform minimum is refused with errorCode `BUDGET_TOO_LOW`, whose message names the minimum. Default: the agent's budget. A run that reaches it ends `FAILED` with errorCode `BUDGET_EXCEEDED`."
13488
+ ),
13489
+ readOnly: z25.boolean().optional().describe("When true, every tool call that would change data is refused in this run. Default false."),
13490
+ idempotencyKey: z25.string().regex(/^[A-Za-z0-9._:-]{1,128}$/, "idempotencyKey is 1 to 128 letters, digits, `.`, `_`, `:` or `-`").optional().describe(
13491
+ "Makes a retried call safe: the same key with the same arguments never starts a second run; the retry returns that run's id and status (`alreadyStarted: true`) instead. Its answer text is not returned again; read how it ended with run_get. Default: a new key per call."
13492
+ )
13493
+ };
13494
+ var agentRun = ({ client, log }) => ({
13495
+ name: "agent_run",
13496
+ title: "Run an agent",
13497
+ description: "Run a stored agent (from agent_list) on one `input` and return its answer. The agent's tool calls act as you, with your own permissions, and only through the tools the agent lists; set `readOnly` to refuse every tool call that would change data. Cap the run's model cost with `maxInferenceCents` (it can only lower the agent's own budget). The run is billed: model calls against your inference balance, and a fee per run, tool calls and run time against your plan. An agent can search the web or fetch a page when its definition lists that web tool (web fetch also needs your tenant's owner to switch it on, and a run of an agent that lists `web_search` is refused while the platform has web search disabled). Returns `{ runId, agentId, agentVersion, status, terminal, reason, errorCode, text, toolCalls, charged }`; `charged` carries the run's charge and refund in milli-cents (1 cent = 1000). Progress notifications keep the call alive while the run works for a client that resets its timeout on progress; cancelling the call cancels the run once the run is named (almost at once). If `terminal` is false the result arrived before the run ended: read it with run_get, which needs `runs:r` as well. Calling again without `idempotencyKey` starts a new, billed run. Needs the `runs:c` scope.",
13498
+ inputSchema: inputSchema25,
13499
+ // Not a read: a run is billed, and its tool calls may create, change or delete data with the
13500
+ // caller's permissions, so a host should confirm it. Not idempotent: each call is a new paid run
13501
+ // unless the same idempotencyKey is passed again.
13502
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
13503
+ handler: async (args, extra) => {
13504
+ const agentId = args.agentId;
13505
+ const maxInferenceCents = args.maxInferenceCents;
13506
+ const idempotencyKey = args.idempotencyKey ?? randomUUID();
13507
+ const request = {
13508
+ "Idempotency-Key": idempotencyKey,
13509
+ agentId,
13510
+ agentVersion: args.agentVersion,
13511
+ input: { text: args.input },
13512
+ budget: maxInferenceCents !== void 0 ? { maxInferenceCents } : void 0,
13513
+ readOnly: args.readOnly
13514
+ };
13515
+ const progressToken = extra._meta?.progressToken;
13516
+ let progressCount = 0;
13517
+ const onProgress = progressToken !== void 0 && extra.sendNotification ? async (message) => {
13518
+ progressCount += 1;
13519
+ await extra.sendNotification({
13520
+ method: "notifications/progress",
13521
+ params: { progressToken, progress: progressCount, message }
13522
+ });
13523
+ } : void 0;
13524
+ const streamAbort = new AbortController();
13525
+ const callSignal = extra.signal;
13526
+ let knownRunId;
13527
+ let headersReceived = false;
13528
+ let cancelRequested = false;
13529
+ let cancelSent = false;
13530
+ let runEnded = false;
13531
+ const sendCancel = () => {
13532
+ if (!cancelRequested || cancelSent || !knownRunId || runEnded) return;
13533
+ cancelSent = true;
13534
+ const id = knownRunId;
13535
+ client.agents.cancelRun({ id }).then(
13536
+ () => log.info({ tool: "agent_run", runId: id }, "agent_run cancelled by the client"),
13537
+ (err) => log.warn({ tool: "agent_run", runId: id, err: String(err) }, "agent_run cancel failed")
13538
+ );
13539
+ };
13540
+ const cancelIfNamed = () => {
13541
+ if (!cancelRequested || !headersReceived || !knownRunId) return;
13542
+ sendCancel();
13543
+ streamAbort.abort();
13544
+ };
13545
+ const onCancel = () => {
13546
+ cancelRequested = true;
13547
+ cancelIfNamed();
13548
+ };
13549
+ if (callSignal?.aborted) {
13550
+ return toolError("agent_run", new Error("The call was cancelled before the run started."));
13551
+ }
13552
+ callSignal?.addEventListener("abort", onCancel, { once: true });
13553
+ try {
13554
+ const { data: stream, rawResponse } = await client.agents.createRun(request, { abortSignal: streamAbort.signal }).withRawResponse();
13555
+ headersReceived = true;
13556
+ knownRunId = rawResponse.headers.get(RUN_ID_HEADER) ?? void 0;
13557
+ cancelIfNamed();
13558
+ const naming = async function* () {
13559
+ for await (const ev of stream) {
13560
+ if (!knownRunId && ev && typeof ev === "object") {
13561
+ const id = ev.runId;
13562
+ if (typeof id === "string" && id.length > 0) {
13563
+ knownRunId = id;
13564
+ cancelIfNamed();
13565
+ }
13566
+ }
13567
+ if (ev && typeof ev === "object") {
13568
+ const e = ev;
13569
+ if (e.terminal === true || typeof e.type === "string" && TERMINAL_EVENT_TYPES.has(e.type)) runEnded = true;
13570
+ }
13571
+ yield ev;
13572
+ }
13573
+ };
13574
+ const run = await consumeRunStream(naming(), knownRunId, onProgress);
13575
+ knownRunId ??= run.runId;
13576
+ if (run.terminal) runEnded = true;
13577
+ sendCancel();
13578
+ log.debug(
13579
+ {
13580
+ tool: "agent_run",
13581
+ runId: run.runId,
13582
+ status: run.status,
13583
+ terminal: run.terminal,
13584
+ toolCalls: run.toolCalls.length,
13585
+ textLength: run.text.length
13586
+ },
13587
+ "agent_run ok"
13588
+ );
13589
+ const body = {
13590
+ runId: run.runId,
13591
+ agentId: run.agentId ?? agentId,
13592
+ agentVersion: run.agentVersion,
13593
+ status: run.status,
13594
+ terminal: run.terminal,
13595
+ reason: run.reason,
13596
+ errorCode: run.errorCode,
13597
+ text: run.text,
13598
+ toolCalls: run.toolCalls,
13599
+ charged: run.charged
13600
+ };
13601
+ if (!run.terminal) {
13602
+ body.note = cancelRequested ? "The call was cancelled and the run was asked to stop. Read it with run_get (needs the `runs:r` scope) to see how it ended." : "The stream ended before the run did" + (run.streamError ? ` (${run.streamError})` : "") + ". The run may still be working: read it with run_get until `terminal` is true (run_get needs the `runs:r` scope).";
13603
+ }
13604
+ return { content: [{ type: "text", text: JSON.stringify(body, null, 2) }] };
13605
+ } catch (err) {
13606
+ const e = err;
13607
+ if (e?.body?.errorCode === "IDEMPOTENCY_IN_PROGRESS") {
13608
+ const runId = (typeof e.body.runId === "string" ? e.body.runId : void 0) ?? e.rawResponse?.headers?.get?.(RUN_ID_HEADER) ?? void 0;
13609
+ if (runId) {
13610
+ const status = typeof e.body.status === "string" ? e.body.status : void 0;
13611
+ log.info({ tool: "agent_run", runId }, "agent_run: the idempotency key already started a run");
13612
+ const body = {
13613
+ runId,
13614
+ agentId,
13615
+ status,
13616
+ // The 409 names the run's status at the time; an ended status is final.
13617
+ terminal: status !== void 0 && ENDED_STATUSES.has(status),
13618
+ alreadyStarted: true,
13619
+ note: "This idempotency key already started this run, so no new run was started. Its answer text is not returned again and cannot be read back: run_get (needs the `runs:r` scope) shows how the run ended and what it was charged, never its text. To start another run, pass a new idempotencyKey."
13620
+ };
13621
+ return { content: [{ type: "text", text: JSON.stringify(body, null, 2) }] };
13622
+ }
13623
+ }
13624
+ log.warn({ tool: "agent_run", agentId, err: String(err) }, "agent_run failed");
13625
+ const result = toolError("agent_run", err);
13626
+ const statusCode = err?.statusCode;
13627
+ if (typeof statusCode !== "number" || statusCode === 408 || statusCode >= 500) {
13628
+ result.content[0].text += `
13629
+ idempotencyKey: ${idempotencyKey}
13630
+ A run may have started before this error. Call agent_run again with the same arguments and this idempotencyKey: if a run started, the call names it; if not, it starts one.` + (cancelRequested ? " (The call was cancelled; a run that started could not be cancelled.)" : "");
13631
+ }
13632
+ return result;
13633
+ } finally {
13634
+ callSignal?.removeEventListener("abort", onCancel);
13635
+ }
13636
+ }
13637
+ });
13638
+ var agent_run_default = agentRun;
13639
+
13640
+ // src/tools/run_get.ts
13641
+ import { z as z26 } from "zod";
13642
+ var inputSchema26 = {
13643
+ runId: z26.string().min(1, "runId must be non-empty").describe("The run id agent_run returned (`runId`).")
13644
+ };
13645
+ var runGet = ({ client, log }) => ({
13646
+ name: "run_get",
13647
+ title: "Get an agent run",
13648
+ description: "Read one agent run by id: `status` (`RUNNING`, `COMPLETED`, `FAILED`, `CANCELLED` or `EXPIRED`), `terminal` (whether it has ended; poll until true), `reason`, `errorCode`, `steps`, its `toolCalls` (each tool and how it ended, never its arguments or result) and `usage` (what it was charged, in milli-cents). It does not return the answer text: agent_run returns that. Use it when agent_run returned `terminal: false`. Needs the `runs:r` scope, which starting a run (`runs:c`) does not include: a credential with only `runs:c` gets `403` here, and learns how its runs end only from agent_run's own result.",
13649
+ inputSchema: inputSchema26,
13650
+ // A pure read: polling a run does not change it.
13651
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
13652
+ handler: async (args) => {
13653
+ const runId = args.runId;
13654
+ try {
13655
+ const run = await client.agents.getRun({ id: runId });
13656
+ log.debug({ tool: "run_get", runId, status: run.status, terminal: run.terminal }, "run_get ok");
13657
+ return { content: [{ type: "text", text: JSON.stringify(run, null, 2) }] };
13658
+ } catch (err) {
13659
+ log.warn({ tool: "run_get", runId, err: String(err) }, "run_get failed");
13660
+ return toolError("run_get", err);
13661
+ }
13662
+ }
13663
+ });
13664
+ var run_get_default = runGet;
13665
+
12699
13666
  // src/tools/types.ts
12700
13667
  var TOOL_NAMES = [
12701
13668
  "hybrid_search",
@@ -12720,7 +13687,10 @@ var TOOL_NAMES = [
12720
13687
  "current_identity",
12721
13688
  "document_ingest",
12722
13689
  "lookup_principal",
12723
- "version_history"
13690
+ "version_history",
13691
+ "agent_list",
13692
+ "agent_run",
13693
+ "run_get"
12724
13694
  ];
12725
13695
 
12726
13696
  // src/tools/index.ts
@@ -12747,7 +13717,10 @@ var ALL_TOOL_FACTORIES = {
12747
13717
  current_identity: current_identity_default,
12748
13718
  document_ingest: document_ingest_default,
12749
13719
  lookup_principal: lookup_principal_default,
12750
- version_history: version_history_default
13720
+ version_history: version_history_default,
13721
+ agent_list: agent_list_default,
13722
+ agent_run: agent_run_default,
13723
+ run_get: run_get_default
12751
13724
  };
12752
13725
 
12753
13726
  // src/resources/schemas.ts
@@ -12790,11 +13763,12 @@ var ALL_RESOURCE_FACTORIES = {
12790
13763
  };
12791
13764
 
12792
13765
  // src/zod-to-json-schema.ts
12793
- import { z as z24 } from "zod";
13766
+ import { z as z27 } from "zod";
12794
13767
  function zodShapeToJsonSchema(shape) {
12795
13768
  const properties = {};
12796
13769
  const required = [];
12797
- for (const [name, schema] of Object.entries(shape)) {
13770
+ for (const [name, entry] of Object.entries(shape)) {
13771
+ const schema = entry;
12798
13772
  properties[name] = zodTypeToJsonSchema(schema);
12799
13773
  if (!schema.isOptional()) required.push(name);
12800
13774
  }
@@ -12803,43 +13777,45 @@ function zodShapeToJsonSchema(shape) {
12803
13777
  return out;
12804
13778
  }
12805
13779
  function zodTypeToJsonSchema(schema) {
12806
- const description = schema.description;
13780
+ const descriptionOf = (s) => s.description;
13781
+ let description = descriptionOf(schema);
12807
13782
  let current = schema;
12808
- while (current instanceof z24.ZodOptional || current instanceof z24.ZodDefault || current instanceof z24.ZodNullable) {
13783
+ while (current instanceof z27.ZodOptional || current instanceof z27.ZodDefault || current instanceof z27.ZodNullable) {
12809
13784
  current = current._def.innerType;
13785
+ description ??= descriptionOf(current);
12810
13786
  }
12811
13787
  const base = description ? { description } : {};
12812
- if (current instanceof z24.ZodString) {
13788
+ if (current instanceof z27.ZodString) {
12813
13789
  return { ...base, type: "string" };
12814
13790
  }
12815
- if (current instanceof z24.ZodNumber) {
13791
+ if (current instanceof z27.ZodNumber) {
12816
13792
  return { ...base, type: "number" };
12817
13793
  }
12818
- if (current instanceof z24.ZodBoolean) {
13794
+ if (current instanceof z27.ZodBoolean) {
12819
13795
  return { ...base, type: "boolean" };
12820
13796
  }
12821
- if (current instanceof z24.ZodEnum) {
13797
+ if (current instanceof z27.ZodEnum) {
12822
13798
  return {
12823
13799
  ...base,
12824
13800
  type: "string",
12825
13801
  enum: current.options
12826
13802
  };
12827
13803
  }
12828
- if (current instanceof z24.ZodArray) {
13804
+ if (current instanceof z27.ZodArray) {
12829
13805
  return {
12830
13806
  ...base,
12831
13807
  type: "array",
12832
13808
  items: zodTypeToJsonSchema(current.element)
12833
13809
  };
12834
13810
  }
12835
- if (current instanceof z24.ZodObject) {
13811
+ if (current instanceof z27.ZodObject) {
12836
13812
  return {
12837
13813
  ...base,
12838
13814
  ...zodShapeToJsonSchema(current.shape)
12839
13815
  };
12840
13816
  }
12841
- if (current instanceof z24.ZodRecord) {
12842
- const valueType = current._def.valueType;
13817
+ if (current instanceof z27.ZodRecord) {
13818
+ const valueType = current.valueType;
12843
13819
  return {
12844
13820
  ...base,
12845
13821
  type: "object",
@@ -12967,7 +13943,7 @@ var VectrosMCPServer = class {
12967
13943
  if (!tool) {
12968
13944
  result = toolError(req.params.name ?? "unknown", new Error("No such tool."));
12969
13945
  } else {
12970
- const parsed = z25.object(tool.inputSchema).strict().safeParse(req.params.arguments ?? {});
13946
+ const parsed = z28.object(tool.inputSchema).strict().safeParse(req.params.arguments ?? {});
12971
13947
  if (!parsed.success) {
12972
13948
  result = toolError(tool.name, new Error(formatArgError(tool, parsed.error)));
12973
13949
  } else {
@@ -13030,7 +14006,7 @@ var VectrosMCPServer = class {
13030
14006
  *
13031
14007
  * If `validateOnStart` (default true) is enabled, performs a
13032
14008
  * GET /v1/ping check BEFORE wiring the transport. On failure,
13033
- * throws — the partner's MCP client sees a startup error instead
14009
+ * throws — your MCP client sees a startup error instead
13034
14010
  * of a confusing "tools work but the first call 401s" experience.
13035
14011
  */
13036
14012
  async connect(transport) {
@@ -13091,7 +14067,7 @@ var VectrosMCPServer = class {
13091
14067
 
13092
14068
  // src/transport/http.ts
13093
14069
  import { createServer } from "http";
13094
- import { randomUUID } from "crypto";
14070
+ import { randomUUID as randomUUID2 } from "crypto";
13095
14071
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
13096
14072
  function constantTimeEqual(a, b) {
13097
14073
  if (a.length !== b.length) return false;
@@ -13154,7 +14130,7 @@ async function startHttpTransport(opts) {
13154
14130
  let allowedHosts = /* @__PURE__ */ new Set();
13155
14131
  let allowedOrigins = /* @__PURE__ */ new Set();
13156
14132
  const mcpTransport = new StreamableHTTPServerTransport({
13157
- sessionIdGenerator: () => randomUUID()
14133
+ sessionIdGenerator: () => randomUUID2()
13158
14134
  });
13159
14135
  await mcpServer.connect(mcpTransport);
13160
14136
  const httpServer = createServer(async (req, res) => {