portkey-admin-mcp 0.16.3 → 0.16.5

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/build/index.js CHANGED
@@ -3,6 +3,120 @@
3
3
  // src/index.ts
4
4
  import { serveStdio } from "@modelcontextprotocol/server/stdio";
5
5
 
6
+ // src/lib/fetch.ts
7
+ var FetchError = class extends Error {
8
+ constructor(message, status, response) {
9
+ super(message);
10
+ this.status = status;
11
+ this.response = response;
12
+ this.name = "FetchError";
13
+ }
14
+ status;
15
+ response;
16
+ };
17
+ var DEFAULT_MAX_UPSTREAM_BODY_BYTES = 8 * 1024 * 1024;
18
+ var DEFAULT_MAX_TOOL_RESULT_BYTES = 4 * 1024 * 1024;
19
+ var MAX_CONFIGURABLE_BYTES = 1024 * 1024 * 1024;
20
+ var MAX_UPSTREAM_BODY_BYTES_ENV = "PORTKEY_MAX_UPSTREAM_BODY_BYTES";
21
+ var MAX_TOOL_RESULT_BYTES_ENV = "PORTKEY_MAX_TOOL_RESULT_BYTES";
22
+ function resolveByteLimit(envName, fallback) {
23
+ const raw = process.env[envName]?.trim();
24
+ if (!raw) return fallback;
25
+ const parsed = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
26
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_CONFIGURABLE_BYTES) {
27
+ throw new Error(
28
+ `Invalid ${envName} value: ${raw}. Must be a positive integer number of bytes (1-${MAX_CONFIGURABLE_BYTES})`
29
+ );
30
+ }
31
+ return parsed;
32
+ }
33
+ function getMaxUpstreamBodyBytes() {
34
+ return resolveByteLimit(
35
+ MAX_UPSTREAM_BODY_BYTES_ENV,
36
+ DEFAULT_MAX_UPSTREAM_BODY_BYTES
37
+ );
38
+ }
39
+ function getMaxToolResultBytes() {
40
+ return resolveByteLimit(
41
+ MAX_TOOL_RESULT_BYTES_ENV,
42
+ DEFAULT_MAX_TOOL_RESULT_BYTES
43
+ );
44
+ }
45
+ function assertByteLimitsConfigured() {
46
+ getMaxUpstreamBodyBytes();
47
+ getMaxToolResultBytes();
48
+ }
49
+ var ResponseBodyTooLargeError = class extends Error {
50
+ constructor(limit) {
51
+ super(`Response body is larger than the ${limit}-byte limit`);
52
+ this.limit = limit;
53
+ this.name = "ResponseBodyTooLargeError";
54
+ }
55
+ limit;
56
+ };
57
+ async function readBoundedText(response, maxBytes) {
58
+ if (!response.body) return "";
59
+ const reader = response.body.getReader();
60
+ const chunks = [];
61
+ let received = 0;
62
+ try {
63
+ for (; ; ) {
64
+ const { done, value } = await reader.read();
65
+ if (done) break;
66
+ received += value.byteLength;
67
+ if (received > maxBytes) {
68
+ await reader.cancel().catch(() => void 0);
69
+ throw new ResponseBodyTooLargeError(maxBytes);
70
+ }
71
+ chunks.push(value);
72
+ }
73
+ } finally {
74
+ reader.releaseLock();
75
+ }
76
+ return new TextDecoder().decode(Buffer.concat(chunks));
77
+ }
78
+ async function readBoundedJson(response, maxBytes) {
79
+ return JSON.parse(await readBoundedText(response, maxBytes));
80
+ }
81
+ async function fetchWithTimeout(url, options = {}) {
82
+ const { timeout = 3e4, ...fetchOptions } = options;
83
+ return fetch(url, {
84
+ ...fetchOptions,
85
+ signal: AbortSignal.timeout(timeout)
86
+ });
87
+ }
88
+ function buildQueryString(params) {
89
+ if (!params) return "";
90
+ const entries = Object.entries(params).flatMap(([key, value]) => {
91
+ if (value === void 0 || value === null) return [];
92
+ if (Array.isArray(value)) {
93
+ return value.map((item) => [key, String(item)]);
94
+ }
95
+ return [[key, String(value)]];
96
+ });
97
+ if (entries.length === 0) return "";
98
+ return `?${new URLSearchParams(entries).toString()}`;
99
+ }
100
+ async function parseErrorResponse(response, maxBytes = DEFAULT_MAX_UPSTREAM_BODY_BYTES) {
101
+ try {
102
+ const body = await readBoundedJson(response, maxBytes);
103
+ const err = body.error ?? body.data ?? body ?? {};
104
+ const code = err?.errorCode ?? err?.code;
105
+ return {
106
+ status_code: body?.status_code ?? response.status,
107
+ message: err?.message ?? `HTTP error! status: ${response.status}${code ? ` (${code})` : ""}`,
108
+ slug: err?.slug,
109
+ code,
110
+ type: err?.type
111
+ };
112
+ } catch (error) {
113
+ return {
114
+ status_code: response.status,
115
+ message: error instanceof ResponseBodyTooLargeError ? `HTTP error! status: ${response.status} (error body over the ${maxBytes}-byte limit)` : `HTTP error! status: ${response.status}`
116
+ };
117
+ }
118
+ }
119
+
6
120
  // src/lib/logger.ts
7
121
  var LOG_LEVELS = {
8
122
  debug: 0,
@@ -186,56 +300,6 @@ var CreateAccessPolicyResponseSchema = z.object({
186
300
  // src/services/base.service.ts
187
301
  import crypto from "node:crypto";
188
302
 
189
- // src/lib/fetch.ts
190
- var FetchError = class extends Error {
191
- constructor(message, status, response) {
192
- super(message);
193
- this.status = status;
194
- this.response = response;
195
- this.name = "FetchError";
196
- }
197
- status;
198
- response;
199
- };
200
- async function fetchWithTimeout(url, options = {}) {
201
- const { timeout = 3e4, ...fetchOptions } = options;
202
- return fetch(url, {
203
- ...fetchOptions,
204
- signal: AbortSignal.timeout(timeout)
205
- });
206
- }
207
- function buildQueryString(params) {
208
- if (!params) return "";
209
- const entries = Object.entries(params).flatMap(([key, value]) => {
210
- if (value === void 0 || value === null) return [];
211
- if (Array.isArray(value)) {
212
- return value.map((item) => [key, String(item)]);
213
- }
214
- return [[key, String(value)]];
215
- });
216
- if (entries.length === 0) return "";
217
- return `?${new URLSearchParams(entries).toString()}`;
218
- }
219
- async function parseErrorResponse(response) {
220
- try {
221
- const body = await response.json();
222
- const err = body.error ?? body.data ?? body ?? {};
223
- const code = err?.errorCode ?? err?.code;
224
- return {
225
- status_code: body?.status_code ?? response.status,
226
- message: err?.message ?? `HTTP error! status: ${response.status}${code ? ` (${code})` : ""}`,
227
- slug: err?.slug,
228
- code,
229
- type: err?.type
230
- };
231
- } catch {
232
- return {
233
- status_code: response.status,
234
- message: `HTTP error! status: ${response.status}`
235
- };
236
- }
237
- }
238
-
239
303
  // src/lib/path-segment.ts
240
304
  function isDotPathSegment(value) {
241
305
  let decoded = value;
@@ -450,6 +514,7 @@ var BaseService = class {
450
514
  paramKeys: options.params ? Object.keys(options.params) : []
451
515
  }
452
516
  });
517
+ const maxBodyBytes = getMaxUpstreamBodyBytes();
453
518
  try {
454
519
  const response = await fetchWithTimeout(url, {
455
520
  method,
@@ -460,7 +525,7 @@ var BaseService = class {
460
525
  });
461
526
  const duration_ms = Date.now() - startTime;
462
527
  if (!response.ok) {
463
- const apiError = await parseErrorResponse(response);
528
+ const apiError = await parseErrorResponse(response, maxBodyBytes);
464
529
  Logger.error("HTTP request failed", {
465
530
  requestId,
466
531
  method,
@@ -481,7 +546,16 @@ var BaseService = class {
481
546
  if (options.allowNoContent && response.status === 204) {
482
547
  return NO_CONTENT;
483
548
  }
484
- return await response.json();
549
+ try {
550
+ return await readBoundedJson(response, maxBodyBytes);
551
+ } catch (error) {
552
+ if (error instanceof ResponseBodyTooLargeError) {
553
+ throw new Error(
554
+ `Portkey ${method} ${path} returned a response larger than ${maxBodyBytes} bytes (${MAX_UPSTREAM_BODY_BYTES_ENV}). Narrow the request with filters or a smaller page_size, or raise the limit.`
555
+ );
556
+ }
557
+ throw error;
558
+ }
485
559
  } catch (error) {
486
560
  const duration_ms = Date.now() - startTime;
487
561
  if (!(error instanceof FetchError)) {
@@ -557,9 +631,9 @@ var BaseService = class {
557
631
  })
558
632
  );
559
633
  }
560
- async put(path, body) {
634
+ async put(path, body, params) {
561
635
  return this.rejectNoContent(
562
- await this.executeRequest("PUT", path, { body })
636
+ await this.executeRequest("PUT", path, { body, params })
563
637
  );
564
638
  }
565
639
  /**
@@ -631,7 +705,7 @@ var AnalyticsService = class extends BaseService {
631
705
  * Helper method to build query params from analytics parameters
632
706
  */
633
707
  buildAnalyticsParams(params) {
634
- const baseParams = {
708
+ return {
635
709
  time_of_generation_min: params.time_of_generation_min,
636
710
  time_of_generation_max: params.time_of_generation_max,
637
711
  total_units_min: params.total_units_min,
@@ -648,7 +722,7 @@ var AnalyticsService = class extends BaseService {
648
722
  virtual_keys: params.virtual_keys,
649
723
  configs: params.configs,
650
724
  workspace_slug: params.workspace_slug,
651
- include_all_workspaces: params.include_all_workspaces === void 0 ? void 0 : String(params.include_all_workspaces),
725
+ include_all_workspaces: params.include_all_workspaces,
652
726
  exclude_workspace_slugs: params.exclude_workspace_slugs,
653
727
  api_key_ids: params.api_key_ids,
654
728
  metadata: params.metadata,
@@ -656,21 +730,14 @@ var AnalyticsService = class extends BaseService {
656
730
  deployment_id: params.deployment_id,
657
731
  trace_id: params.trace_id,
658
732
  span_id: params.span_id,
659
- prompt_slug: params.prompt_slug
733
+ prompt_slug: params.prompt_slug,
734
+ current_page: params.current_page,
735
+ page_size: params.page_size,
736
+ order_by: params.order_by,
737
+ order_by_type: params.order_by_type,
738
+ columns: params.columns,
739
+ include_total: params.include_total
660
740
  };
661
- if ("current_page" in params) {
662
- baseParams.current_page = params.current_page;
663
- }
664
- if ("page_size" in params) {
665
- baseParams.page_size = params.page_size;
666
- }
667
- if ("order_by" in params) baseParams.order_by = params.order_by;
668
- if ("order_by_type" in params)
669
- baseParams.order_by_type = params.order_by_type;
670
- if ("columns" in params) baseParams.columns = params.columns;
671
- if ("include_total" in params)
672
- baseParams.include_total = params.include_total;
673
- return baseParams;
674
741
  }
675
742
  // ==================== Cost Analytics ====================
676
743
  async getCostAnalytics(params) {
@@ -1557,6 +1624,7 @@ var McpIntegrationsService = class extends BaseService {
1557
1624
  organisation_id: params?.organisation_id,
1558
1625
  type: params?.type,
1559
1626
  workspace_id: params?.workspace_id,
1627
+ tags: params?.tags === void 0 ? void 0 : JSON.stringify(params.tags),
1560
1628
  search: params?.search
1561
1629
  });
1562
1630
  }
@@ -1581,9 +1649,10 @@ var McpIntegrationsService = class extends BaseService {
1581
1649
  `/mcp-integrations/${this.encodePathSegment(id)}/metadata`
1582
1650
  );
1583
1651
  }
1584
- async listMcpIntegrationCapabilities(id) {
1652
+ async listMcpIntegrationCapabilities(id, params) {
1585
1653
  return this.get(
1586
- `/mcp-integrations/${this.encodePathSegment(id)}/capabilities`
1654
+ `/mcp-integrations/${this.encodePathSegment(id)}/capabilities`,
1655
+ { type: params?.type }
1587
1656
  );
1588
1657
  }
1589
1658
  async updateMcpIntegrationCapabilities(id, data) {
@@ -1626,7 +1695,10 @@ var McpServersService = class extends BaseService {
1626
1695
  return this.get("/mcp-servers", {
1627
1696
  current_page: params?.current_page,
1628
1697
  page_size: params?.page_size,
1629
- workspace_id: params?.workspace_id
1698
+ workspace_id: params?.workspace_id,
1699
+ id: params?.id,
1700
+ search: params?.search,
1701
+ tags: params?.tags === void 0 ? void 0 : JSON.stringify(params.tags)
1630
1702
  });
1631
1703
  }
1632
1704
  async createMcpServer(data) {
@@ -1654,7 +1726,8 @@ var McpServersService = class extends BaseService {
1654
1726
  `/mcp-servers/${this.encodePathSegment(id)}/capabilities`,
1655
1727
  {
1656
1728
  current_page: params?.current_page,
1657
- page_size: params?.page_size
1729
+ page_size: params?.page_size,
1730
+ type: params?.type
1658
1731
  }
1659
1732
  );
1660
1733
  }
@@ -1670,7 +1743,8 @@ var McpServersService = class extends BaseService {
1670
1743
  `/mcp-servers/${this.encodePathSegment(id)}/user-access`,
1671
1744
  {
1672
1745
  current_page: params?.current_page,
1673
- page_size: params?.page_size
1746
+ page_size: params?.page_size,
1747
+ search: params?.search
1674
1748
  }
1675
1749
  );
1676
1750
  }
@@ -1769,6 +1843,8 @@ var PromptsService = class extends BaseService {
1769
1843
  string: raw.string ?? "",
1770
1844
  parameters: raw.parameters ?? {},
1771
1845
  model: raw.model,
1846
+ ai_model_id: raw.ai_model_id,
1847
+ finetune_id: raw.finetune_id,
1772
1848
  virtual_key: raw.virtual_key,
1773
1849
  functions: raw.functions ?? void 0,
1774
1850
  tools: raw.tools ?? void 0,
@@ -1780,12 +1856,14 @@ var PromptsService = class extends BaseService {
1780
1856
  object: "prompt"
1781
1857
  };
1782
1858
  }
1783
- async updatePrompt(promptId, data) {
1859
+ async updatePrompt(promptId, data, options = {}) {
1784
1860
  const { template_metadata, is_raw_template, ...rest } = data;
1785
1861
  const body = {
1786
1862
  ...rest,
1787
- // Enable partial updates so missing version fields are backfilled from latest version
1788
- patch: true
1863
+ // Partial updates backfill missing version fields from the latest
1864
+ // version. Callers that send a complete version turn this off so absent
1865
+ // fields are cleared instead of inherited.
1866
+ patch: options.patch ?? true
1789
1867
  };
1790
1868
  if (template_metadata !== void 0) {
1791
1869
  body.prompt_metadata = template_metadata;
@@ -2012,24 +2090,42 @@ var PromptsService = class extends BaseService {
2012
2090
  data.target_collection_id
2013
2091
  );
2014
2092
  if (existingTarget) {
2015
- const updateResult = await this.updatePrompt(existingTarget.id, {
2016
- string: sourceVersion.string,
2017
- parameters: sourceVersion.parameters,
2018
- model: sourceVersion.model,
2019
- virtual_key: data.virtual_key || sourceVersion.virtual_key,
2020
- functions: sourceVersion.functions,
2021
- tools: sourceVersion.tools,
2022
- tool_choice: sourceVersion.tool_choice,
2023
- is_raw_template: sourceVersion.is_raw_template,
2024
- version_description: `Promoted from ${sourcePrompt.slug} v${sourceVersion.version_number}`,
2025
- template_metadata: {
2026
- ...sourceVersion.template_metadata,
2027
- env: data.target_env,
2028
- promoted_from: sourcePrompt.slug,
2029
- promoted_from_version: sourceVersion.version_number.toString(),
2030
- promoted_at: (/* @__PURE__ */ new Date()).toISOString()
2031
- }
2032
- });
2093
+ const virtualKey2 = data.virtual_key || sourceVersion.virtual_key;
2094
+ if (!sourceVersion.string || !(sourceVersion.model || sourceVersion.ai_model_id || sourceVersion.finetune_id) || !virtualKey2) {
2095
+ throw new Error(
2096
+ "Cannot promote prompt: source version needs a string, a model (model, ai_model_id or finetune_id) and a virtual_key (or a virtual_key override)"
2097
+ );
2098
+ }
2099
+ const updateResult = await this.updatePrompt(
2100
+ existingTarget.id,
2101
+ {
2102
+ string: sourceVersion.string,
2103
+ parameters: sourceVersion.parameters ?? {},
2104
+ ...sourceVersion.model && { model: sourceVersion.model },
2105
+ ...sourceVersion.ai_model_id && {
2106
+ ai_model_id: sourceVersion.ai_model_id
2107
+ },
2108
+ ...sourceVersion.finetune_id && {
2109
+ finetune_id: sourceVersion.finetune_id
2110
+ },
2111
+ virtual_key: virtualKey2,
2112
+ functions: sourceVersion.functions ?? [],
2113
+ tools: sourceVersion.tools ?? [],
2114
+ ...sourceVersion.tool_choice !== void 0 && {
2115
+ tool_choice: sourceVersion.tool_choice
2116
+ },
2117
+ is_raw_template: sourceVersion.is_raw_template ?? false,
2118
+ version_description: `Promoted from ${sourcePrompt.slug} v${sourceVersion.version_number}`,
2119
+ template_metadata: {
2120
+ ...sourceVersion.template_metadata,
2121
+ env: data.target_env,
2122
+ promoted_from: sourcePrompt.slug,
2123
+ promoted_from_version: sourceVersion.version_number.toString(),
2124
+ promoted_at: (/* @__PURE__ */ new Date()).toISOString()
2125
+ }
2126
+ },
2127
+ { patch: false }
2128
+ );
2033
2129
  return {
2034
2130
  source_prompt_id: data.source_prompt_id,
2035
2131
  source_version_id: sourceVersion.id,
@@ -2113,12 +2209,17 @@ var ProvidersService = class extends BaseService {
2113
2209
  });
2114
2210
  }
2115
2211
  async updateProvider(slug, data, workspaceId) {
2116
- const path = workspaceId ? `/providers/${this.encodePathSegment(slug)}?workspace_id=${encodeURIComponent(workspaceId)}` : `/providers/${this.encodePathSegment(slug)}`;
2117
- return this.put(path, data);
2212
+ return this.put(
2213
+ `/providers/${this.encodePathSegment(slug)}`,
2214
+ data,
2215
+ { workspace_id: workspaceId || void 0 }
2216
+ );
2118
2217
  }
2119
2218
  async deleteProvider(slug, workspaceId) {
2120
- const path = workspaceId ? `/providers/${this.encodePathSegment(slug)}?workspace_id=${encodeURIComponent(workspaceId)}` : `/providers/${this.encodePathSegment(slug)}`;
2121
- const result = await this.delete(path);
2219
+ const result = await this.delete(
2220
+ `/providers/${this.encodePathSegment(slug)}`,
2221
+ { workspace_id: workspaceId || void 0 }
2222
+ );
2122
2223
  return isNoContent(result) ? {} : result;
2123
2224
  }
2124
2225
  };
@@ -2345,7 +2446,7 @@ function getSharedServiceCacheKey(apiKey) {
2345
2446
  const keyDigest = createHmac("sha256", SERVICE_CACHE_HMAC_KEY).update(apiKey).digest("hex");
2346
2447
  return JSON.stringify({
2347
2448
  apiKey: keyDigest,
2348
- baseUrl: process.env.PORTKEY_BASE_URL?.trim() || ""
2449
+ baseUrl: process.env.PORTKEY_BASE_URL ?? DEFAULT_BASE_URL
2349
2450
  });
2350
2451
  }
2351
2452
  var sharedPortkeyServices = /* @__PURE__ */ new Map();
@@ -2375,8 +2476,7 @@ var PortkeyService = class {
2375
2476
  health;
2376
2477
  constructor(apiKey) {
2377
2478
  const resolvedApiKey = resolvePortkeyApiKey(apiKey);
2378
- const resolvedBaseUrl = process.env.PORTKEY_BASE_URL ?? "https://api.portkey.ai/v1";
2379
- validateUrl(resolvedBaseUrl);
2479
+ const resolvedBaseUrl = process.env.PORTKEY_BASE_URL ?? DEFAULT_BASE_URL;
2380
2480
  this.accessPolicies = new AccessPoliciesService(
2381
2481
  resolvedApiKey,
2382
2482
  resolvedBaseUrl
@@ -2450,8 +2550,8 @@ var SecretReferenceListItemSchema = z3.object({
2450
2550
  slug: z3.string(),
2451
2551
  manager_type: SecretManagerTypeSchema,
2452
2552
  status: z3.literal("ACTIVE"),
2453
- created_at: z3.iso.datetime(),
2454
- last_updated_at: z3.iso.datetime(),
2553
+ created_at: z3.iso.datetime({ offset: true }),
2554
+ last_updated_at: z3.iso.datetime({ offset: true }),
2455
2555
  object: z3.literal("secret-reference")
2456
2556
  });
2457
2557
  var ListSecretReferencesResponseSchema = z3.object({
@@ -2794,7 +2894,7 @@ var GENERIC_GRAPH_ANALYTICS_TOOLS = [
2794
2894
  },
2795
2895
  {
2796
2896
  name: "get_user_requests_analytics",
2797
- description: "Get per-user request-count time-series data with counts grouped by user. Use this to find heavy users and traffic concentration; use get_users_analytics for aggregate active and new user trends instead.",
2897
+ description: "Get per-user request-count time-series data with counts grouped by user. Use this to find heavy users and traffic concentration; use get_users_analytics for aggregate unique-user trends instead.",
2798
2898
  method: (analytics, params) => analytics.getUserRequestsAnalytics(params)
2799
2899
  },
2800
2900
  {
@@ -2854,57 +2954,27 @@ function normalizeMetadataFilter(value) {
2854
2954
  }
2855
2955
  return void 0;
2856
2956
  }
2957
+ var ANALYTICS_PARAM_ALIASES = [
2958
+ ["status_codes", "status_code", normalizeCommaSeparatedParam],
2959
+ ["virtual_key_slugs", "virtual_keys", normalizeCommaSeparatedParam],
2960
+ ["config_slugs", "configs", normalizeCommaSeparatedParam],
2961
+ ["api_key_ids", "api_key_ids", normalizeCommaSeparatedParam],
2962
+ ["metadata_filter", "metadata", normalizeMetadataFilter],
2963
+ ["provider_models", "ai_org_model", normalizeCommaSeparatedParam],
2964
+ ["deployment_ids", "deployment_id", normalizeCommaSeparatedParam],
2965
+ ["trace_ids", "trace_id", normalizeCommaSeparatedParam],
2966
+ ["span_ids", "span_id", normalizeCommaSeparatedParam]
2967
+ ];
2857
2968
  function normalizeAnalyticsParams(params) {
2858
- const {
2859
- status_codes,
2860
- virtual_key_slugs,
2861
- config_slugs,
2862
- api_key_ids,
2863
- trace_ids,
2864
- span_ids,
2865
- provider_models,
2866
- deployment_ids,
2867
- metadata_filter,
2868
- ...legacyParams
2869
- } = params;
2870
- const normalizedParams = {
2871
- ...legacyParams
2872
- };
2873
- const statusCode = normalizeCommaSeparatedParam(status_codes) ?? normalizeCommaSeparatedParam(legacyParams.status_code);
2874
- if (statusCode !== void 0) {
2875
- normalizedParams.status_code = statusCode;
2876
- }
2877
- const virtualKeys = normalizeCommaSeparatedParam(virtual_key_slugs) ?? normalizeCommaSeparatedParam(legacyParams.virtual_keys);
2878
- if (virtualKeys !== void 0) {
2879
- normalizedParams.virtual_keys = virtualKeys;
2880
- }
2881
- const configs = normalizeCommaSeparatedParam(config_slugs) ?? normalizeCommaSeparatedParam(legacyParams.configs);
2882
- if (configs !== void 0) {
2883
- normalizedParams.configs = configs;
2884
- }
2885
- const apiKeyIds = normalizeCommaSeparatedParam(api_key_ids) ?? normalizeCommaSeparatedParam(legacyParams.api_key_ids);
2886
- if (apiKeyIds !== void 0) {
2887
- normalizedParams.api_key_ids = apiKeyIds;
2888
- }
2889
- const metadata = normalizeMetadataFilter(metadata_filter) ?? normalizeMetadataFilter(legacyParams.metadata);
2890
- if (metadata !== void 0) {
2891
- normalizedParams.metadata = metadata;
2969
+ const normalizedParams = { ...params };
2970
+ for (const [alias] of ANALYTICS_PARAM_ALIASES) {
2971
+ delete normalizedParams[alias];
2892
2972
  }
2893
- const providerModels = normalizeCommaSeparatedParam(provider_models) ?? normalizeCommaSeparatedParam(legacyParams.ai_org_model);
2894
- if (providerModels !== void 0) {
2895
- normalizedParams.ai_org_model = providerModels;
2896
- }
2897
- const deploymentId = normalizeCommaSeparatedParam(deployment_ids) ?? normalizeCommaSeparatedParam(legacyParams.deployment_id);
2898
- if (deploymentId !== void 0) {
2899
- normalizedParams.deployment_id = deploymentId;
2900
- }
2901
- const traceId = normalizeCommaSeparatedParam(trace_ids) ?? normalizeCommaSeparatedParam(legacyParams.trace_id);
2902
- if (traceId !== void 0) {
2903
- normalizedParams.trace_id = traceId;
2904
- }
2905
- const spanId = normalizeCommaSeparatedParam(span_ids) ?? normalizeCommaSeparatedParam(legacyParams.span_id);
2906
- if (spanId !== void 0) {
2907
- normalizedParams.span_id = spanId;
2973
+ for (const [alias, legacy, normalize] of ANALYTICS_PARAM_ALIASES) {
2974
+ const value = normalize(params[alias]) ?? normalize(params[legacy]);
2975
+ if (value !== void 0) {
2976
+ normalizedParams[legacy] = value;
2977
+ }
2908
2978
  }
2909
2979
  return normalizedParams;
2910
2980
  }
@@ -2966,7 +3036,7 @@ function registerAnalyticsTools(server, service) {
2966
3036
  server.registerTool(
2967
3037
  "get_token_analytics",
2968
3038
  {
2969
- description: "Get token-usage time-series data with summary.total_tokens, summary.prompt_tokens, summary.completion_tokens, and per-bucket total/prompt/completion counts. Use this for consumption trends; use get_cost_analytics when you need spend instead of token volume.",
3039
+ description: "Get token-usage time-series data with summary.total and summary.avg (average tokens per request), and per-bucket total and avg. Portkey doesn't split prompt and completion tokens in this graph. Use this for consumption trends; use get_cost_analytics when you need spend instead of token volume.",
2970
3040
  inputSchema: baseAnalyticsSchema
2971
3041
  },
2972
3042
  async (params) => {
@@ -2976,15 +3046,13 @@ function registerAnalyticsTools(server, service) {
2976
3046
  const dataPoints = analytics.data_points.map((point) => ({
2977
3047
  timestamp: point.timestamp,
2978
3048
  total: point.total,
2979
- prompt: point.prompt,
2980
- completion: point.completion
3049
+ avg: point.avg
2981
3050
  }));
2982
3051
  return jsonResult(
2983
3052
  formatGraphAnalytics(
2984
3053
  {
2985
- total_tokens: analytics.summary.total,
2986
- prompt_tokens: analytics.summary.prompt,
2987
- completion_tokens: analytics.summary.completion
3054
+ total: analytics.summary.total,
3055
+ avg: analytics.summary.avg
2988
3056
  },
2989
3057
  dataPoints
2990
3058
  )
@@ -3098,7 +3166,7 @@ function registerAnalyticsTools(server, service) {
3098
3166
  server.registerTool(
3099
3167
  "get_cache_hit_rate",
3100
3168
  {
3101
- description: "Get cache-effectiveness time-series data with summary.hit_rate, summary.total_hits, summary.total_misses, and per-bucket hits/misses/rate. Use this to measure cache effectiveness; use get_cache_hit_latency for speed rather than hit/miss ratio.",
3169
+ description: "Get cache-effectiveness time-series data with summary.hit_rate and summary.total_hits, and per-bucket simple_hits, semantic_hits, rate, and cumulative simple and semantic cache savings. Use this to measure cache effectiveness; use get_cache_hit_latency for speed rather than hit/miss ratio.",
3102
3170
  inputSchema: baseAnalyticsSchema
3103
3171
  },
3104
3172
  async (params) => {
@@ -3107,16 +3175,17 @@ function registerAnalyticsTools(server, service) {
3107
3175
  );
3108
3176
  const dataPoints = analytics.data_points.map((point) => ({
3109
3177
  timestamp: point.timestamp,
3178
+ simple_hits: point.simple_hits,
3179
+ semantic_hits: point.semantic_hits,
3110
3180
  rate: point.rate,
3111
- hits: point.hits,
3112
- misses: point.misses
3181
+ cumulative_simple_cache_savings: point.cumulative_simple_cache_savings,
3182
+ cumulative_semantic_cache_savings: point.cumulative_semantic_cache_savings
3113
3183
  }));
3114
3184
  return jsonResult(
3115
3185
  formatGraphAnalytics(
3116
3186
  {
3117
3187
  hit_rate: analytics.summary.rate,
3118
- total_hits: analytics.summary.total_hits,
3119
- total_misses: analytics.summary.total_misses
3188
+ total_hits: analytics.summary.total
3120
3189
  },
3121
3190
  dataPoints
3122
3191
  )
@@ -3140,7 +3209,7 @@ function registerAnalyticsTools(server, service) {
3140
3209
  server.registerTool(
3141
3210
  "get_users_analytics",
3142
3211
  {
3143
- description: "Get user-growth time-series data with summary.total_active_users, summary.total_new_users, and per-bucket active/new user counts. Use this for growth and adoption trends; use get_user_requests_analytics for per-user traffic or get_analytics_group_users for per-user cost and token detail.",
3212
+ description: "Get unique-user time-series data with summary.total and per-bucket total unique users. Use this for adoption trends; use get_user_requests_analytics for per-user traffic or get_analytics_group_users for per-user cost and token detail.",
3144
3213
  inputSchema: baseAnalyticsSchema
3145
3214
  },
3146
3215
  async (params) => {
@@ -3149,14 +3218,12 @@ function registerAnalyticsTools(server, service) {
3149
3218
  );
3150
3219
  const dataPoints = analytics.data_points.map((point) => ({
3151
3220
  timestamp: point.timestamp,
3152
- active_users: point.active_users,
3153
- new_users: point.new_users
3221
+ total: point.total
3154
3222
  }));
3155
3223
  return jsonResult(
3156
3224
  formatGraphAnalytics(
3157
3225
  {
3158
- total_active_users: analytics.summary.total_active_users,
3159
- total_new_users: analytics.summary.total_new_users
3226
+ total: analytics.summary.total
3160
3227
  },
3161
3228
  dataPoints
3162
3229
  )
@@ -3179,7 +3246,7 @@ function registerAnalyticsTools(server, service) {
3179
3246
  server.registerTool(
3180
3247
  "get_analytics_group_users",
3181
3248
  {
3182
- description: "Get a paginated per-user breakdown with total_groups, group_count, and a users array containing request count, cost, and token usage. Use this for billing, audits, or top-consumer analysis; use get_users_analytics for aggregate active and new user trends.",
3249
+ description: "Get a paginated per-user breakdown with total_groups, group_count, and a users array containing request count, cost, and token usage. Use this for billing, audits, or top-consumer analysis; use get_users_analytics for aggregate unique-user trends.",
3183
3250
  inputSchema: paginatedAnalyticsSchema
3184
3251
  },
3185
3252
  async (params) => {
@@ -3497,8 +3564,12 @@ var configTargetSchema = z9.object({
3497
3564
  });
3498
3565
  var CONFIGS_TOOL_SCHEMAS = {
3499
3566
  listConfigs: {
3500
- current_page: CurrentPageSchema,
3501
- page_size: PageSizeSchema.describe("Number of results per page (max 100)")
3567
+ current_page: CurrentPageSchema.describe(
3568
+ "Accepted for compatibility; Portkey ignores it for configs and GET /configs returns the full list"
3569
+ ),
3570
+ page_size: PageSizeSchema.describe(
3571
+ "Accepted for compatibility; Portkey ignores it for configs and GET /configs returns the full list"
3572
+ )
3502
3573
  },
3503
3574
  getConfig: {
3504
3575
  slug: z9.string().describe(
@@ -3506,6 +3577,9 @@ var CONFIGS_TOOL_SCHEMAS = {
3506
3577
  )
3507
3578
  },
3508
3579
  createConfig: {
3580
+ auto_caching: z9.boolean().optional().describe(
3581
+ "Automatically add Anthropic prompt caching. Set false to disable"
3582
+ ),
3509
3583
  name: z9.string().describe("Name for the new configuration"),
3510
3584
  workspace_id: z9.string().optional().describe("Workspace ID to create config in"),
3511
3585
  cache_mode: z9.enum(["simple", "semantic"]).optional().describe("Cache mode: 'simple' or 'semantic'"),
@@ -3516,6 +3590,9 @@ var CONFIGS_TOOL_SCHEMAS = {
3516
3590
  targets: z9.array(configTargetSchema).optional().describe("Array of target providers with virtual keys")
3517
3591
  },
3518
3592
  updateConfig: {
3593
+ auto_caching: z9.boolean().optional().describe(
3594
+ "Automatically add Anthropic prompt caching. Set false to disable"
3595
+ ),
3519
3596
  slug: z9.string().describe("Configuration slug to update"),
3520
3597
  name: z9.string().optional().describe("New name for the configuration"),
3521
3598
  status: z9.enum(["active", "inactive"]).optional().describe("Configuration status"),
@@ -3534,6 +3611,7 @@ var CONFIGS_TOOL_SCHEMAS = {
3534
3611
  }
3535
3612
  };
3536
3613
  var configPayloadSchema = z9.object({
3614
+ auto_caching: z9.boolean().optional(),
3537
3615
  cache_mode: z9.enum(["simple", "semantic"]).optional(),
3538
3616
  cache_max_age: z9.coerce.number().positive().optional(),
3539
3617
  retry_attempts: z9.coerce.number().positive().max(5).optional(),
@@ -3551,6 +3629,7 @@ function buildConfigPayload(params) {
3551
3629
  ...params.retry_on_status_codes !== void 0 ? { on_status_codes: params.retry_on_status_codes } : {}
3552
3630
  } : void 0;
3553
3631
  return {
3632
+ ...params.auto_caching !== void 0 ? { auto_caching: params.auto_caching } : {},
3554
3633
  cache,
3555
3634
  retry,
3556
3635
  strategy: params.strategy_mode !== void 0 ? { mode: params.strategy_mode } : void 0,
@@ -3558,13 +3637,13 @@ function buildConfigPayload(params) {
3558
3637
  };
3559
3638
  }
3560
3639
  function hasConfigSettings(config) {
3561
- return config.cache !== void 0 || config.retry !== void 0 || config.strategy !== void 0 || config.targets !== void 0;
3640
+ return config.auto_caching !== void 0 || config.cache !== void 0 || config.retry !== void 0 || config.strategy !== void 0 || config.targets !== void 0;
3562
3641
  }
3563
3642
  var createConfigSchema = z9.object(CONFIGS_TOOL_SCHEMAS.createConfig).superRefine((value, ctx) => {
3564
3643
  if (!hasConfigSettings(buildConfigPayload(value))) {
3565
3644
  ctx.addIssue({
3566
3645
  code: z9.ZodIssueCode.custom,
3567
- message: "At least one config setting (cache_mode, retry_attempts, strategy_mode, or targets) must be provided"
3646
+ message: "At least one config setting (auto_caching, cache_mode, retry_attempts, strategy_mode, or targets) must be provided"
3568
3647
  });
3569
3648
  }
3570
3649
  });
@@ -3611,6 +3690,7 @@ function registerConfigsTools(server, service) {
3611
3690
  name: response.name,
3612
3691
  status: response.status,
3613
3692
  config: {
3693
+ auto_caching: response.config.auto_caching,
3614
3694
  cache: response.config.cache && {
3615
3695
  mode: response.config.cache.mode,
3616
3696
  max_age: response.config.cache.max_age
@@ -3656,11 +3736,10 @@ function registerConfigsTools(server, service) {
3656
3736
  server.registerTool(
3657
3737
  "update_config",
3658
3738
  {
3659
- description: "Update a config by slug; every call creates a new config version rather than overwriting, so earlier versions stay recoverable via list_config_versions. Only provided fields change: name, status, and all routing/cache/retry settings (cache_mode, cache_max_age, retry_attempts, retry_on_status_codes, strategy_mode, targets) are editable, while the slug stays fixed. Changes apply immediately to every API key and prompt referencing the config. Returns the update acknowledgement and new version_id.",
3739
+ description: "Update a config by slug; every call creates a new config version rather than overwriting, so earlier versions stay recoverable via list_config_versions. Only provided fields change: name, status, and all routing/cache/retry settings (auto_caching, cache_mode, cache_max_age, retry_attempts, retry_on_status_codes, strategy_mode, targets) are editable, while the slug stays fixed. Changes apply immediately to every API key and prompt referencing the config. Returns the update acknowledgement and new version_id.",
3660
3740
  inputSchema: CONFIGS_TOOL_SCHEMAS.updateConfig,
3661
3741
  annotations: {
3662
3742
  readOnlyHint: false,
3663
- destructiveHint: false,
3664
3743
  idempotentHint: false,
3665
3744
  openWorldHint: false
3666
3745
  }
@@ -4105,7 +4184,6 @@ function registerGuardrailsTools(server, service) {
4105
4184
  annotations: {
4106
4185
  title: "Update Organisation Guardrail Defaults",
4107
4186
  readOnlyHint: false,
4108
- destructiveHint: false,
4109
4187
  idempotentHint: true,
4110
4188
  openWorldHint: true
4111
4189
  }
@@ -4374,31 +4452,68 @@ import { z as z15 } from "zod";
4374
4452
 
4375
4453
  // src/lib/limits.ts
4376
4454
  var PERIODIC_RESET_DEFAULT = "monthly";
4455
+ function hasUsageLimitInput(params) {
4456
+ return params.credit_limit !== void 0 || params.alert_threshold !== void 0 || params.type !== void 0 || params.periodic_reset !== void 0;
4457
+ }
4458
+ function copyDefinedUsageLimitFields(params, limits) {
4459
+ if (params.type !== void 0) {
4460
+ limits.type = params.type;
4461
+ }
4462
+ if (params.periodic_reset !== void 0) {
4463
+ limits.periodic_reset = params.periodic_reset;
4464
+ }
4465
+ if (params.credit_limit !== void 0) {
4466
+ limits.credit_limit = params.credit_limit;
4467
+ }
4468
+ if (params.alert_threshold !== void 0) {
4469
+ limits.alert_threshold = params.alert_threshold;
4470
+ }
4471
+ return limits;
4472
+ }
4377
4473
  function buildUsageLimits(params) {
4378
- if (params.credit_limit !== void 0 || params.alert_threshold !== void 0) {
4379
- const limits = {
4380
- type: params.type ?? "cost",
4381
- periodic_reset: params.periodic_reset ?? PERIODIC_RESET_DEFAULT
4382
- };
4383
- if (params.credit_limit !== void 0) {
4384
- limits.credit_limit = params.credit_limit;
4474
+ if (!hasUsageLimitInput(params)) {
4475
+ return void 0;
4476
+ }
4477
+ return copyDefinedUsageLimitFields(params, {
4478
+ type: "cost",
4479
+ periodic_reset: PERIODIC_RESET_DEFAULT
4480
+ });
4481
+ }
4482
+ function buildUsageLimitsUpdate(params) {
4483
+ if (!hasUsageLimitInput(params)) {
4484
+ return void 0;
4485
+ }
4486
+ return copyDefinedUsageLimitFields(params, {});
4487
+ }
4488
+ async function mergeUsageLimitsUpdate(supplied, readExisting) {
4489
+ if (supplied === void 0) {
4490
+ return void 0;
4491
+ }
4492
+ const existing = await readExisting();
4493
+ const base = existing ? {} : { type: "cost", periodic_reset: PERIODIC_RESET_DEFAULT };
4494
+ if (existing) {
4495
+ for (const key of [
4496
+ "type",
4497
+ "credit_limit",
4498
+ "alert_threshold",
4499
+ "periodic_reset",
4500
+ "periodic_reset_days"
4501
+ ]) {
4502
+ if (existing[key] !== void 0) {
4503
+ Object.assign(base, { [key]: existing[key] });
4504
+ }
4385
4505
  }
4386
- if (params.alert_threshold !== void 0) {
4387
- limits.alert_threshold = params.alert_threshold;
4506
+ if (supplied.periodic_reset !== void 0) {
4507
+ delete base.periodic_reset_days;
4508
+ } else if (base.periodic_reset_days !== void 0 && base.periodic_reset_days !== null) {
4509
+ delete base.periodic_reset;
4388
4510
  }
4389
- return limits;
4390
4511
  }
4391
- return void 0;
4512
+ return { ...base, ...supplied };
4392
4513
  }
4393
4514
  function buildRateLimitsRpm(rpmValue) {
4394
4515
  if (rpmValue !== void 0) {
4395
- return [
4396
- {
4397
- type: "requests",
4398
- unit: "rpm",
4399
- value: rpmValue
4400
- }
4401
- ];
4516
+ return buildRateLimits({ value: rpmValue, unit: "rpm" });
4402
4517
  }
4403
4518
  return void 0;
4404
4519
  }
@@ -5152,7 +5267,9 @@ var KEYS_TOOL_SCHEMAS = {
5152
5267
  alert_threshold: z16.coerce.number().min(0).max(100).optional().describe("New alert threshold percentage (0-100)"),
5153
5268
  rate_limit_rpm: z16.coerce.number().positive().optional().describe("New rate limit in requests per minute"),
5154
5269
  rate_limits: z16.array(apiKeyRateLimitSchema).nullable().optional().describe("Replacement request or token rate limits, or null to clear"),
5155
- reset_usage: z16.coerce.number().nonnegative().optional().describe("Set to a nonnegative acknowledgement value to reset usage"),
5270
+ reset_usage: z16.boolean().optional().describe(
5271
+ "Set to true to reset current usage; an exhausted key returns to active"
5272
+ ),
5156
5273
  default_config_id: z16.string().optional().describe("New default configuration ID"),
5157
5274
  default_metadata: z16.record(z16.string(), z16.string()).optional().describe("New default metadata key-value pairs"),
5158
5275
  default_allow_config_override: z16.boolean().optional().describe("Whether callers may override the key's default config"),
@@ -5199,6 +5316,7 @@ var createApiKeySchema = z16.object(KEYS_TOOL_SCHEMAS.createApiKey).superRefine(
5199
5316
  });
5200
5317
  function formatKeyUsageLimits(limits) {
5201
5318
  return limits ? {
5319
+ type: limits.type,
5202
5320
  credit_limit: limits.credit_limit,
5203
5321
  alert_threshold: limits.alert_threshold,
5204
5322
  periodic_reset: limits.periodic_reset
@@ -5244,6 +5362,7 @@ function formatApiKeySummary(apiKey) {
5244
5362
  expires_at: apiKey.expires_at,
5245
5363
  created_at: apiKey.created_at,
5246
5364
  last_updated_at: apiKey.last_updated_at,
5365
+ last_rotated_at: apiKey.last_rotated_at,
5247
5366
  creation_mode: apiKey.creation_mode
5248
5367
  };
5249
5368
  }
@@ -5266,6 +5385,7 @@ function formatApiKey(apiKey) {
5266
5385
  reset_usage: apiKey.reset_usage,
5267
5386
  created_at: apiKey.created_at,
5268
5387
  last_updated_at: apiKey.last_updated_at,
5388
+ last_rotated_at: apiKey.last_rotated_at,
5269
5389
  creation_mode: apiKey.creation_mode
5270
5390
  };
5271
5391
  }
@@ -5342,18 +5462,22 @@ function registerKeysTools(server, service) {
5342
5462
  server.registerTool(
5343
5463
  "update_virtual_key",
5344
5464
  {
5345
- description: "Update a virtual key's name, secret, note, or limits. Rotating the key takes effect immediately, and limit changes apply to downstream prompts and configs using this slug. Returns success when Portkey accepts the update.",
5465
+ description: "Update a virtual key's name, secret, note, or limits. Rotating the key takes effect immediately, and limit changes apply to downstream prompts and configs using this slug. Returns success when Portkey accepts the update. Limit updates read the current limits and write them back, and Portkey has no conditional writes, so concurrent limit updates to the same resource can overwrite each other. Serialize them.",
5346
5466
  inputSchema: KEYS_TOOL_SCHEMAS.updateVirtualKey
5347
5467
  },
5348
5468
  async (params) => {
5469
+ const usageLimits = await mergeUsageLimitsUpdate(
5470
+ buildUsageLimitsUpdate({
5471
+ credit_limit: params.credit_limit,
5472
+ alert_threshold: params.alert_threshold
5473
+ }),
5474
+ async () => (await service.keys.getVirtualKey(params.slug)).usage_limits
5475
+ );
5349
5476
  const result = await service.keys.updateVirtualKey(params.slug, {
5350
5477
  name: params.name,
5351
5478
  key: params.key,
5352
5479
  note: params.note,
5353
- usage_limits: buildUsageLimits({
5354
- credit_limit: params.credit_limit,
5355
- alert_threshold: params.alert_threshold
5356
- }),
5480
+ usage_limits: usageLimits,
5357
5481
  rate_limits: buildRateLimitsRpm(params.rate_limit_rpm),
5358
5482
  deploymentConfig: params.deployment_configurations?.map(
5359
5483
  (configuration) => ({
@@ -5433,7 +5557,7 @@ function registerKeysTools(server, service) {
5433
5557
  server.registerTool(
5434
5558
  "list_api_keys",
5435
5559
  {
5436
- description: "List Portkey API keys for auditing access, scopes, defaults, limits, and expiration. Use this for API keys only; use list_virtual_keys for provider keys. Returns total plus id, type, status, workspace/user scope, limits, defaults, alert emails, and creation mode.",
5560
+ description: "List Portkey API keys for auditing access, scopes, defaults, limits, and expiration. Use this for API keys only; use list_virtual_keys for provider keys. Returns total plus id, type, status, workspace/user scope, limits, defaults, alert emails, creation mode, and the last rotation timestamp when available.",
5437
5561
  inputSchema: KEYS_TOOL_SCHEMAS.listApiKeys
5438
5562
  },
5439
5563
  async (params) => {
@@ -5451,7 +5575,7 @@ function registerKeysTools(server, service) {
5451
5575
  server.registerTool(
5452
5576
  "get_api_key",
5453
5577
  {
5454
- description: "Fetch one API key by UUID without revealing the secret. Use this to inspect scopes, defaults, limits, expiration, and reset state before changing access.",
5578
+ description: "Fetch one API key by UUID without revealing the secret. Use this to inspect scopes, defaults, limits, expiration, reset state, and the last rotation timestamp when available before changing access.",
5455
5579
  inputSchema: KEYS_TOOL_SCHEMAS.getApiKey
5456
5580
  },
5457
5581
  async (params) => {
@@ -5462,18 +5586,22 @@ function registerKeysTools(server, service) {
5462
5586
  server.registerTool(
5463
5587
  "update_api_key",
5464
5588
  {
5465
- description: "Update an API key's name, description, scopes, defaults, or limits, unlike delete_api_key which revokes it or create_api_key which issues a new one. Changes take effect immediately for downstream callers, type and sub-type stay fixed after creation, and the call returns success without rotating the secret.",
5589
+ description: "Update an API key's name, description, scopes, defaults, or limits, unlike delete_api_key which revokes it or create_api_key which issues a new one. Changes take effect immediately for downstream callers, type and sub-type stay fixed after creation, and the call returns success without rotating the secret. Limit updates read the current limits and write them back, and Portkey has no conditional writes, so concurrent limit updates to the same resource can overwrite each other. Serialize them.",
5466
5590
  inputSchema: KEYS_TOOL_SCHEMAS.updateApiKey
5467
5591
  },
5468
5592
  async (params) => {
5593
+ const usageLimits = await mergeUsageLimitsUpdate(
5594
+ buildUsageLimitsUpdate({
5595
+ credit_limit: params.credit_limit,
5596
+ alert_threshold: params.alert_threshold
5597
+ }),
5598
+ async () => (await service.keys.getApiKey(params.id)).usage_limits
5599
+ );
5469
5600
  const result = await service.keys.updateApiKey(params.id, {
5470
5601
  name: params.name,
5471
5602
  description: params.description,
5472
5603
  scopes: params.scopes,
5473
- usage_limits: buildUsageLimits({
5474
- credit_limit: params.credit_limit,
5475
- alert_threshold: params.alert_threshold
5476
- }),
5604
+ usage_limits: usageLimits,
5477
5605
  rate_limits: params.rate_limits === void 0 ? buildRateLimitsRpm(params.rate_limit_rpm) : params.rate_limits,
5478
5606
  ...params.reset_usage !== void 0 ? { reset_usage: params.reset_usage } : {},
5479
5607
  defaults: params.default_config_id !== void 0 || params.default_metadata !== void 0 || params.default_allow_config_override !== void 0 ? {
@@ -6314,6 +6442,7 @@ var mcpConfigurationsSchema = z20.record(z20.string(), z20.unknown()).superRefin
6314
6442
  });
6315
6443
  var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6316
6444
  listMcpIntegrations: {
6445
+ tags: resourceTagsSchema.optional().describe("Match resources carrying all supplied tags"),
6317
6446
  current_page: CurrentPageSchema,
6318
6447
  page_size: pageSizeSchema(1e3).describe(
6319
6448
  "Number of results per page (max 1000)"
@@ -6326,6 +6455,9 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6326
6455
  search: z20.string().optional().describe("Search integrations by name")
6327
6456
  },
6328
6457
  createMcpIntegration: {
6458
+ tags: resourceTagsSchema.nullable().optional().describe(
6459
+ "Key-value tags. Replaces existing tags; pass null to clear. Keys allow letters, numbers, underscores, and hyphens"
6460
+ ),
6329
6461
  name: z20.string().describe("Display name for the MCP integration"),
6330
6462
  url: z20.string().describe("URL endpoint of the MCP server to integrate"),
6331
6463
  auth_type: z20.string().min(1).describe(
@@ -6343,7 +6475,10 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6343
6475
  "Additional documented or forward-compatible configuration fields. For headers auth, configurations.custom_headers is a string-to-string header map."
6344
6476
  ),
6345
6477
  workspace_id: z20.string().optional().describe(
6346
- "Workspace ID \u2014 required when using organization admin API keys"
6478
+ "Workspace ID; set it to create the integration at workspace level. With an organisation admin key, give this or organisation_id."
6479
+ ),
6480
+ organisation_id: z20.string().optional().describe(
6481
+ "Organisation ID; required with an organisation admin API key when workspace_id is omitted"
6347
6482
  ),
6348
6483
  secret_mappings: mcpSecretMappingsSchema.optional().describe(
6349
6484
  "Runtime Secret Reference mappings; every configurations.<field> target must be unique"
@@ -6353,6 +6488,9 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6353
6488
  id: z20.string().describe("The MCP integration ID or slug to retrieve")
6354
6489
  },
6355
6490
  updateMcpIntegration: {
6491
+ tags: resourceTagsSchema.nullable().optional().describe(
6492
+ "Key-value tags. Replaces existing tags; pass null to clear. Keys allow letters, numbers, underscores, and hyphens"
6493
+ ),
6356
6494
  id: z20.string().describe("The MCP integration ID or slug to update"),
6357
6495
  name: z20.string().optional().describe("New display name"),
6358
6496
  description: z20.string().optional().describe("New description"),
@@ -6378,7 +6516,8 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6378
6516
  id: z20.string().describe("The MCP integration ID or slug")
6379
6517
  },
6380
6518
  listMcpIntegrationCapabilities: {
6381
- id: z20.string().describe("The MCP integration ID or slug")
6519
+ id: z20.string().describe("The MCP integration ID or slug"),
6520
+ type: z20.enum(["tool", "prompt", "resource", "resource_template"]).optional().describe("Only return capabilities of this type")
6382
6521
  },
6383
6522
  updateMcpIntegrationCapabilities: {
6384
6523
  id: z20.string().describe("The MCP integration ID or slug"),
@@ -6400,7 +6539,15 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6400
6539
  id: z20.string().describe("Workspace ID"),
6401
6540
  enabled: z20.boolean().describe("Whether workspace has access")
6402
6541
  })
6403
- ).min(1).describe("Array of workspace access updates")
6542
+ ).describe(
6543
+ "Array of workspace access updates; may be empty when only changing global_workspace_access"
6544
+ ),
6545
+ global_workspace_access: z20.object({
6546
+ enabled: z20.boolean().describe("Whether every workspace gets access by default")
6547
+ }).optional().describe("Organisation-wide workspace access default"),
6548
+ override_existing_workspace_access: z20.boolean().optional().describe(
6549
+ "When true, global_workspace_access replaces existing per-workspace settings"
6550
+ )
6404
6551
  }
6405
6552
  };
6406
6553
  var createMcpIntegrationSchema = z20.object(MCP_INTEGRATIONS_TOOL_SCHEMAS.createMcpIntegration).superRefine((value, ctx) => {
@@ -6434,6 +6581,7 @@ function formatMcpIntegration(integration) {
6434
6581
  name: integration.name,
6435
6582
  slug: integration.slug,
6436
6583
  description: integration.description,
6584
+ tags: integration.tags,
6437
6585
  owner_id: integration.owner_id,
6438
6586
  workspace_id: integration.workspace_id,
6439
6587
  status: integration.status,
@@ -6540,7 +6688,7 @@ function registerMcpIntegrationsTools(server, service) {
6540
6688
  server.registerTool(
6541
6689
  "update_mcp_integration",
6542
6690
  {
6543
- description: "Update an MCP integration's name, description, URL, auth, transport, headers, or runtime Secret Reference mappings. Only supplied fields change; URL, auth, header, and secret changes apply immediately and can break active clients, so inspect get_mcp_integration first. Use update_mcp_server when changing only a Portkey server instance's display metadata.",
6691
+ description: "Update an MCP integration's name, description, tags, URL, auth, transport, headers, or runtime Secret Reference mappings. Only supplied fields change; URL, auth, header, and secret changes apply immediately and can break active clients, so inspect get_mcp_integration first. Use update_mcp_server when changing only a Portkey server instance's display metadata.",
6544
6692
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.updateMcpIntegration,
6545
6693
  annotations: {
6546
6694
  title: "Update MCP Integration",
@@ -6602,7 +6750,12 @@ function registerMcpIntegrationsTools(server, service) {
6602
6750
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.listMcpIntegrationCapabilities
6603
6751
  },
6604
6752
  async (params) => {
6605
- const result = await service.mcpIntegrations.listMcpIntegrationCapabilities(params.id);
6753
+ const result = await service.mcpIntegrations.listMcpIntegrationCapabilities(
6754
+ params.id,
6755
+ {
6756
+ type: params.type
6757
+ }
6758
+ );
6606
6759
  return jsonResult({
6607
6760
  total: result.total,
6608
6761
  capabilities: result.data
@@ -6616,7 +6769,6 @@ function registerMcpIntegrationsTools(server, service) {
6616
6769
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.updateMcpIntegrationCapabilities,
6617
6770
  annotations: {
6618
6771
  readOnlyHint: false,
6619
- destructiveHint: false,
6620
6772
  idempotentHint: true,
6621
6773
  openWorldHint: false
6622
6774
  }
@@ -6658,14 +6810,17 @@ function registerMcpIntegrationsTools(server, service) {
6658
6810
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.updateMcpIntegrationWorkspaces,
6659
6811
  annotations: {
6660
6812
  readOnlyHint: false,
6661
- destructiveHint: false,
6662
6813
  idempotentHint: true,
6663
6814
  openWorldHint: false
6664
6815
  }
6665
6816
  },
6666
6817
  async (params) => {
6667
6818
  await service.mcpIntegrations.updateMcpIntegrationWorkspaces(params.id, {
6668
- workspaces: params.workspaces
6819
+ workspaces: params.workspaces,
6820
+ ...params.global_workspace_access !== void 0 ? { global_workspace_access: params.global_workspace_access } : {},
6821
+ ...params.override_existing_workspace_access !== void 0 ? {
6822
+ override_existing_workspace_access: params.override_existing_workspace_access
6823
+ } : {}
6669
6824
  });
6670
6825
  return jsonResult({
6671
6826
  message: `Successfully updated workspace access for MCP integration "${params.id}"`,
@@ -6679,20 +6834,32 @@ function registerMcpIntegrationsTools(server, service) {
6679
6834
  import { z as z21 } from "zod";
6680
6835
  var MCP_SERVERS_TOOL_SCHEMAS = {
6681
6836
  listMcpServers: {
6837
+ tags: resourceTagsSchema.optional().describe("Match resources carrying all supplied tags"),
6682
6838
  current_page: CurrentPageSchema,
6683
6839
  page_size: PageSizeSchema.describe("Number of results per page (max 100)"),
6684
- workspace_id: z21.string().optional().describe("Filter by workspace ID")
6840
+ workspace_id: z21.string().optional().describe("Filter by workspace ID"),
6841
+ id: z21.string().optional().describe("Filter by MCP server ID, or several IDs separated by commas"),
6842
+ search: z21.string().max(255).optional().describe("Search MCP servers (up to 255 characters)")
6685
6843
  },
6686
6844
  createMcpServer: {
6845
+ tags: resourceTagsSchema.nullable().optional().describe(
6846
+ "Key-value tags. Replaces existing tags; pass null to clear. Keys allow letters, numbers, underscores, and hyphens"
6847
+ ),
6687
6848
  name: z21.string().describe("Display name for the MCP server"),
6688
6849
  mcp_integration_id: z21.string().describe("ID or slug of the MCP integration this server belongs to"),
6689
6850
  slug: z21.string().optional().describe("Custom slug. Auto-generated if omitted"),
6690
- description: z21.string().optional().describe("Description of the MCP server")
6851
+ description: z21.string().optional().describe("Description of the MCP server"),
6852
+ workspace_id: z21.string().optional().describe(
6853
+ "Workspace ID or slug; required with an organisation admin API key"
6854
+ )
6691
6855
  },
6692
6856
  getMcpServer: {
6693
6857
  id: z21.string().describe("The MCP server ID or slug to retrieve")
6694
6858
  },
6695
6859
  updateMcpServer: {
6860
+ tags: resourceTagsSchema.nullable().optional().describe(
6861
+ "Key-value tags. Replaces existing tags; pass null to clear. Keys allow letters, numbers, underscores, and hyphens"
6862
+ ),
6696
6863
  id: z21.string().describe("The MCP server ID or slug to update"),
6697
6864
  name: z21.string().optional().describe("New display name"),
6698
6865
  description: z21.string().optional().describe("New description")
@@ -6706,7 +6873,8 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6706
6873
  listMcpServerCapabilities: {
6707
6874
  id: z21.string().describe("The MCP server ID or slug"),
6708
6875
  current_page: CurrentPageSchema,
6709
- page_size: PageSizeSchema.describe("Number of results per page (max 100)")
6876
+ page_size: PageSizeSchema.describe("Number of results per page (max 100)"),
6877
+ type: z21.enum(["tool", "prompt", "resource", "resource_template"]).optional().describe("Only return capabilities of this type")
6710
6878
  },
6711
6879
  updateMcpServerCapabilities: {
6712
6880
  id: z21.string().describe("The MCP server ID or slug"),
@@ -6721,7 +6889,8 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6721
6889
  listMcpServerUserAccess: {
6722
6890
  id: z21.string().describe("The MCP server ID or slug"),
6723
6891
  current_page: CurrentPageSchema,
6724
- page_size: PageSizeSchema.describe("Number of results per page (max 100)")
6892
+ page_size: PageSizeSchema.describe("Number of results per page (max 100)"),
6893
+ search: z21.string().optional().describe("Search by user name or email")
6725
6894
  },
6726
6895
  updateMcpServerUserAccess: {
6727
6896
  id: z21.string().describe("The MCP server ID or slug"),
@@ -6730,7 +6899,10 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6730
6899
  user_id: z21.string().describe("User ID"),
6731
6900
  enabled: z21.boolean().describe("Whether user has access")
6732
6901
  })
6733
- ).min(1).describe("Array of user access updates")
6902
+ ).min(1).optional().describe("Array of user access updates"),
6903
+ default_user_access: z21.enum(["allow", "deny"]).optional().describe(
6904
+ "Server default for users without an explicit override. Provide this, users, or both"
6905
+ )
6734
6906
  },
6735
6907
  listMcpServerConnections: {
6736
6908
  id: z21.string().describe("MCP server ID or slug whose connections to list"),
@@ -6757,12 +6929,20 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6757
6929
  )
6758
6930
  }
6759
6931
  };
6932
+ var updateMcpServerUserAccessSchema = z21.object(MCP_SERVERS_TOOL_SCHEMAS.updateMcpServerUserAccess).refine(
6933
+ (value) => value.users !== void 0 || value.default_user_access !== void 0,
6934
+ {
6935
+ message: "Provide users, default_user_access, or both",
6936
+ path: ["users"]
6937
+ }
6938
+ );
6760
6939
  function formatMcpServer(server) {
6761
6940
  return {
6762
6941
  id: server.id,
6763
6942
  name: server.name,
6764
6943
  slug: server.slug,
6765
6944
  description: server.description,
6945
+ tags: server.tags,
6766
6946
  mcp_integration_id: server.mcp_integration_id,
6767
6947
  status: server.status,
6768
6948
  created_at: server.created_at
@@ -6888,7 +7068,7 @@ function registerMcpServersTools(server, service) {
6888
7068
  server.registerTool(
6889
7069
  "update_mcp_server",
6890
7070
  {
6891
- description: "Update an MCP server's name or description. Changes apply immediately, but URL and auth live on the parent integration, so use update_mcp_integration for those fields.",
7071
+ description: "Update an MCP server's name, description, or tags. Changes apply immediately, but URL and auth live on the parent integration, so use update_mcp_integration for those fields.",
6892
7072
  inputSchema: MCP_SERVERS_TOOL_SCHEMAS.updateMcpServer
6893
7073
  },
6894
7074
  async (params) => {
@@ -6936,7 +7116,8 @@ function registerMcpServersTools(server, service) {
6936
7116
  params.id,
6937
7117
  {
6938
7118
  current_page: params.current_page,
6939
- page_size: params.page_size
7119
+ page_size: params.page_size,
7120
+ type: params.type
6940
7121
  }
6941
7122
  );
6942
7123
  return jsonResult({
@@ -6973,7 +7154,8 @@ function registerMcpServersTools(server, service) {
6973
7154
  params.id,
6974
7155
  {
6975
7156
  current_page: params.current_page,
6976
- page_size: params.page_size
7157
+ page_size: params.page_size,
7158
+ search: params.search
6977
7159
  }
6978
7160
  );
6979
7161
  return jsonResult({
@@ -6987,12 +7169,14 @@ function registerMcpServersTools(server, service) {
6987
7169
  server.registerTool(
6988
7170
  "update_mcp_server_user_access",
6989
7171
  {
6990
- description: "Grant or revoke individual user access to an MCP server. Changes take effect immediately and override the default access setting for the selected users; use list_mcp_server_user_access first if you need the current state.",
7172
+ description: "Grant or revoke individual user access to an MCP server, and/or set the server default (default_user_access) for users without an override. Changes take effect immediately and override the default access setting for the selected users; use list_mcp_server_user_access first if you need the current state.",
6991
7173
  inputSchema: MCP_SERVERS_TOOL_SCHEMAS.updateMcpServerUserAccess
6992
7174
  },
6993
- async (params) => {
7175
+ async (rawParams) => {
7176
+ const params = updateMcpServerUserAccessSchema.parse(rawParams);
6994
7177
  await service.mcpServers.updateMcpServerUserAccess(params.id, {
6995
- user_access: params.users
7178
+ ...params.users !== void 0 ? { user_access: params.users } : {},
7179
+ ...params.default_user_access !== void 0 ? { default_user_access: params.default_user_access } : {}
6996
7180
  });
6997
7181
  return jsonResult({
6998
7182
  message: `Successfully updated user access for MCP server "${params.id}"`,
@@ -7691,7 +7875,7 @@ function registerPromptsTools(server, service) {
7691
7875
  server.registerTool(
7692
7876
  "run_prompt_completion",
7693
7877
  {
7694
- description: "Execute a prompt against the configured model and return the completion. This makes a billable model call, so use render_prompt first when you want to check the template and validate_completion_metadata when billing fields are uncertain.",
7878
+ description: "Execute a prompt against the configured model and return the completion text, plus any tool_calls or function_call the model requested (returned as data, never executed). This makes a billable model call, so use render_prompt first when you want to check the template and validate_completion_metadata when billing fields are uncertain.",
7695
7879
  inputSchema: PROMPTS_TOOL_SCHEMAS.runPromptCompletion
7696
7880
  },
7697
7881
  async (params) => {
@@ -7709,6 +7893,9 @@ function registerPromptsTools(server, service) {
7709
7893
  id: result.id,
7710
7894
  model: result.model,
7711
7895
  response: choice?.message?.content ?? null,
7896
+ // Returned as data only. The server never executes a tool call.
7897
+ ...choice?.message?.tool_calls?.length ? { tool_calls: choice.message.tool_calls } : {},
7898
+ ...choice?.message?.function_call ? { function_call: choice.message.function_call } : {},
7712
7899
  finish_reason: choice?.finish_reason ?? null,
7713
7900
  usage: result.usage ? {
7714
7901
  prompt_tokens: result.usage.prompt_tokens,
@@ -7891,14 +8078,16 @@ var PROVIDERS_TOOL_SCHEMAS = {
7891
8078
  credit_limit: z24.coerce.number().positive().optional().describe("New credit limit for usage"),
7892
8079
  alert_threshold: z24.coerce.number().min(0).max(100).optional().describe("New alert threshold percentage (0-100)"),
7893
8080
  usage_limit_type: z24.enum(["cost", "tokens"]).optional().describe(
7894
- "Type of usage limit: 'cost' (monetary) or 'tokens' (token count). Defaults to 'cost'."
8081
+ "Usage limit type: 'cost' or 'tokens'. If omitted, preserves the existing type; defaults to 'cost' when no limits exist."
7895
8082
  ),
7896
8083
  periodic_reset: z24.enum(["monthly", "weekly"]).optional().describe(
7897
- "Period for resetting usage limits: 'monthly' or 'weekly'. Defaults to 'monthly'."
8084
+ "Reset period: 'monthly' or 'weekly'. If omitted, preserves the existing cadence, including custom reset days; defaults to 'monthly' when no limits exist."
8085
+ ),
8086
+ rate_limit_value: z24.coerce.number().positive().optional().describe(
8087
+ "New rate limit value. Must be provided together with rate_limit_unit."
7898
8088
  ),
7899
- rate_limit_value: z24.coerce.number().positive().optional().describe("New rate limit value"),
7900
8089
  rate_limit_unit: z24.enum(["rpm", "rph", "rpd"]).optional().describe(
7901
- "Rate limit unit: 'rpm' (requests per minute), 'rph' (requests per hour), or 'rpd' (requests per day)"
8090
+ "Rate limit unit: 'rpm' (requests per minute), 'rph' (requests per hour), or 'rpd' (requests per day). Must be provided together with rate_limit_value."
7902
8091
  ),
7903
8092
  expires_at: z24.string().optional().describe("New expiration date in ISO 8601 format"),
7904
8093
  reset_usage: z24.boolean().optional().describe("Set to true to reset accumulated usage metrics")
@@ -7908,6 +8097,18 @@ var PROVIDERS_TOOL_SCHEMAS = {
7908
8097
  workspace_id: z24.string().optional().describe("Workspace ID - required when using organization admin keys")
7909
8098
  }
7910
8099
  };
8100
+ var RATE_LIMIT_PAIR_MESSAGE = "rate_limit_value and rate_limit_unit must be provided together";
8101
+ function hasCompleteRateLimitPair(value) {
8102
+ return value.rate_limit_value === void 0 === (value.rate_limit_unit === void 0);
8103
+ }
8104
+ var createProviderSchema = z24.object(PROVIDERS_TOOL_SCHEMAS.createProvider).refine(hasCompleteRateLimitPair, {
8105
+ path: ["rate_limit_unit"],
8106
+ message: RATE_LIMIT_PAIR_MESSAGE
8107
+ });
8108
+ var updateProviderSchema = z24.object(PROVIDERS_TOOL_SCHEMAS.updateProvider).refine(hasCompleteRateLimitPair, {
8109
+ path: ["rate_limit_unit"],
8110
+ message: RATE_LIMIT_PAIR_MESSAGE
8111
+ });
7911
8112
  function registerProvidersTools(server, service) {
7912
8113
  server.registerTool(
7913
8114
  "list_providers",
@@ -7930,6 +8131,7 @@ function registerProvidersTools(server, service) {
7930
8131
  status: provider.status,
7931
8132
  note: provider.note,
7932
8133
  usage_limits: provider.usage_limits ? {
8134
+ type: provider.usage_limits.type,
7933
8135
  credit_limit: provider.usage_limits.credit_limit,
7934
8136
  alert_threshold: provider.usage_limits.alert_threshold,
7935
8137
  periodic_reset: provider.usage_limits.periodic_reset
@@ -7952,7 +8154,8 @@ function registerProvidersTools(server, service) {
7952
8154
  description: "Create a workspace provider backed by an org integration. The provider inherits the integration key, but its limits and expiration are enforced independently for that workspace. Returns the new provider id and slug.",
7953
8155
  inputSchema: PROVIDERS_TOOL_SCHEMAS.createProvider
7954
8156
  },
7955
- async (params) => {
8157
+ async (rawParams) => {
8158
+ const params = createProviderSchema.parse(rawParams);
7956
8159
  const result = await service.providers.createProvider({
7957
8160
  name: params.name,
7958
8161
  integration_id: params.integration_id,
@@ -7996,6 +8199,7 @@ function registerProvidersTools(server, service) {
7996
8199
  status: provider.status,
7997
8200
  note: provider.note,
7998
8201
  usage_limits: provider.usage_limits ? {
8202
+ type: provider.usage_limits.type,
7999
8203
  credit_limit: provider.usage_limits.credit_limit,
8000
8204
  alert_threshold: provider.usage_limits.alert_threshold,
8001
8205
  periodic_reset: provider.usage_limits.periodic_reset
@@ -8014,21 +8218,29 @@ function registerProvidersTools(server, service) {
8014
8218
  server.registerTool(
8015
8219
  "update_provider",
8016
8220
  {
8017
- description: "Update a provider's metadata, limits, or expiration. reset_usage clears accumulated usage counters immediately, so use it only when you intend to reset quota tracking. Returns the updated provider id and slug.",
8221
+ description: "Update a provider's metadata, limits, or expiration. reset_usage clears accumulated usage counters immediately, so use it only when you intend to reset quota tracking. Returns the updated provider id and slug. Limit updates read the current limits and write them back, and Portkey has no conditional writes, so concurrent limit updates to the same resource can overwrite each other. Serialize them.",
8018
8222
  inputSchema: PROVIDERS_TOOL_SCHEMAS.updateProvider
8019
8223
  },
8020
- async (params) => {
8224
+ async (rawParams) => {
8225
+ const params = updateProviderSchema.parse(rawParams);
8226
+ const usageLimits = await mergeUsageLimitsUpdate(
8227
+ buildUsageLimitsUpdate({
8228
+ credit_limit: params.credit_limit,
8229
+ alert_threshold: params.alert_threshold,
8230
+ type: params.usage_limit_type,
8231
+ periodic_reset: params.periodic_reset
8232
+ }),
8233
+ async () => (await service.providers.getProvider(
8234
+ params.slug,
8235
+ params.workspace_id
8236
+ )).usage_limits
8237
+ );
8021
8238
  const result = await service.providers.updateProvider(
8022
8239
  params.slug,
8023
8240
  {
8024
8241
  name: params.name,
8025
8242
  note: params.note,
8026
- usage_limits: buildUsageLimits({
8027
- credit_limit: params.credit_limit,
8028
- alert_threshold: params.alert_threshold,
8029
- type: params.usage_limit_type,
8030
- periodic_reset: params.periodic_reset
8031
- }),
8243
+ usage_limits: usageLimits,
8032
8244
  rate_limits: params.rate_limit_value !== void 0 && params.rate_limit_unit !== void 0 ? buildRateLimits({
8033
8245
  value: params.rate_limit_value,
8034
8246
  unit: params.rate_limit_unit
@@ -8917,6 +9129,14 @@ function formatWorkspaceDefaults(defaults) {
8917
9129
  metadata: defaults.metadata
8918
9130
  };
8919
9131
  }
9132
+ function formatWorkspaceFlagsAndLimits(workspace) {
9133
+ return {
9134
+ is_default: workspace.is_default ?? workspace.defaults?.is_default,
9135
+ defaults: formatWorkspaceDefaults(workspace.defaults),
9136
+ usage_limits: workspace.usage_limits ?? null,
9137
+ rate_limits: workspace.rate_limits ?? null
9138
+ };
9139
+ }
8920
9140
  function formatWorkspaceSummary(workspace) {
8921
9141
  return {
8922
9142
  id: workspace.id,
@@ -8925,7 +9145,7 @@ function formatWorkspaceSummary(workspace) {
8925
9145
  description: workspace.description,
8926
9146
  created_at: workspace.created_at,
8927
9147
  last_updated_at: workspace.last_updated_at,
8928
- defaults: formatWorkspaceDefaults(workspace.defaults)
9148
+ ...formatWorkspaceFlagsAndLimits(workspace)
8929
9149
  };
8930
9150
  }
8931
9151
  function formatWorkspaceMember(user) {
@@ -8947,7 +9167,7 @@ function formatWorkspaceDetail(workspace) {
8947
9167
  description: workspace.description,
8948
9168
  created_at: workspace.created_at,
8949
9169
  last_updated_at: workspace.last_updated_at,
8950
- defaults: formatWorkspaceDefaults(workspace.defaults),
9170
+ ...formatWorkspaceFlagsAndLimits(workspace),
8951
9171
  users: workspace.users.map(formatWorkspaceMember)
8952
9172
  };
8953
9173
  }
@@ -9294,7 +9514,9 @@ var DESTRUCTIVE_TOOL_PREFIXES = [
9294
9514
  "delete_",
9295
9515
  "remove_",
9296
9516
  "cancel_",
9297
- "reset_"
9517
+ "reset_",
9518
+ "update_",
9519
+ "archive_"
9298
9520
  ];
9299
9521
  var ENTERPRISE_GATED_TOOL_NAMES = /* @__PURE__ */ new Set([
9300
9522
  "get_cost_analytics",
@@ -9427,12 +9649,12 @@ function getToolErrorMessage(error) {
9427
9649
  return String(error);
9428
9650
  }
9429
9651
  var STANDARD_TOOL_OUTPUT_SCHEMA = {
9430
- ok: z29.boolean().describe("Whether the tool call succeeded and returned structured data"),
9431
- data: z29.unknown().optional().describe("Structured success payload when ok is true"),
9652
+ ok: z29.boolean().describe("Call succeeded"),
9653
+ data: z29.unknown().optional().describe("Success payload"),
9432
9654
  error: z29.object({
9433
- message: z29.string().describe("Human-readable error message"),
9434
- details: z29.unknown().optional().describe("Optional structured error details")
9435
- }).optional().describe("Structured error payload when ok is false")
9655
+ message: z29.string().describe("Error message"),
9656
+ details: z29.unknown().optional().describe("Extra error details")
9657
+ }).optional().describe("Failure details")
9436
9658
  };
9437
9659
  var TOOL_SUCCESS_DATA_SCHEMAS = {
9438
9660
  create_access_policy: CreateAccessPolicyResponseSchema,
@@ -9450,7 +9672,10 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9450
9672
  warning: z29.string().describe("Required handling guidance for the one-time secret"),
9451
9673
  id: z29.string().uuid().describe("Rotated API key UUID"),
9452
9674
  key: z29.string().describe("New API key secret, returned only once"),
9453
- key_transition_expires_at: z29.iso.datetime().describe("Time when the previous key stops working")
9675
+ // Offsets such as +00:00 are valid RFC 3339, and the field is optional in
9676
+ // the spec. A strict schema here fails after the rotation already ran,
9677
+ // which would drop the one-time secret.
9678
+ key_transition_expires_at: z29.iso.datetime({ offset: true }).optional().describe("Time when the previous key stops working")
9454
9679
  }),
9455
9680
  create_secret_reference: z29.object({
9456
9681
  message: z29.string().describe("Creation confirmation"),
@@ -9467,9 +9692,9 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9467
9692
  manager_type: SecretManagerTypeSchema.describe(
9468
9693
  "External secret manager type"
9469
9694
  ),
9470
- status: z29.literal("ACTIVE").describe("Current reference status"),
9471
- created_at: z29.iso.datetime().describe("ISO 8601 creation timestamp"),
9472
- last_updated_at: z29.iso.datetime().describe("ISO 8601 last-update timestamp")
9695
+ status: z29.string().describe("Current reference status, ACTIVE for usable references"),
9696
+ created_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 creation timestamp"),
9697
+ last_updated_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 last-update timestamp")
9473
9698
  })
9474
9699
  ).describe(
9475
9700
  "Current page of Secret References without authentication values"
@@ -9488,10 +9713,10 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9488
9713
  secret_key: z29.string().nullable().describe("Selected key within a structured secret"),
9489
9714
  allow_all_workspaces: z29.boolean().describe("Whether all workspaces may use the reference"),
9490
9715
  tags: z29.record(z29.string(), z29.string()).nullable().describe("String metadata tags"),
9491
- status: z29.literal("ACTIVE").describe("Current reference status"),
9716
+ status: z29.string().describe("Current reference status"),
9492
9717
  created_by: z29.string().describe("Creator identifier"),
9493
- created_at: z29.iso.datetime().describe("ISO 8601 creation timestamp"),
9494
- last_updated_at: z29.iso.datetime().describe("ISO 8601 last-update timestamp"),
9718
+ created_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 creation timestamp"),
9719
+ last_updated_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 last-update timestamp"),
9495
9720
  auth_config: z29.record(z29.string(), z29.unknown()).describe("Authentication configuration with sensitive values redacted"),
9496
9721
  object: z29.literal("secret-reference").describe("Portkey object type")
9497
9722
  }),
@@ -9509,7 +9734,7 @@ function getToolOutputSchema(toolName) {
9509
9734
  if (!dataSchema) return STANDARD_TOOL_OUTPUT_SCHEMA;
9510
9735
  return {
9511
9736
  ...STANDARD_TOOL_OUTPUT_SCHEMA,
9512
- data: dataSchema.optional().describe("Structured success payload when ok is true")
9737
+ data: dataSchema.optional().describe("Success payload")
9513
9738
  };
9514
9739
  }
9515
9740
  function isStandardToolEnvelope(value) {
@@ -9571,10 +9796,31 @@ function normalizeToolResult(result) {
9571
9796
  structuredContent: envelope
9572
9797
  };
9573
9798
  }
9799
+ function measureToolResultBytes(result) {
9800
+ const text = getFirstTextContent(result) ?? "";
9801
+ return Buffer.byteLength(JSON.stringify(text)) + Buffer.byteLength(text);
9802
+ }
9803
+ function enforceToolResultLimit(toolName, result) {
9804
+ const limit = getMaxToolResultBytes();
9805
+ const bytes = measureToolResultBytes(result);
9806
+ if (bytes <= limit) return result;
9807
+ return normalizeToolResult({
9808
+ content: [
9809
+ {
9810
+ type: "text",
9811
+ text: `Tool "${toolName}" produced a ${bytes}-byte result, over the ${limit}-byte limit (${MAX_TOOL_RESULT_BYTES_ENV}). Nothing was truncated. Narrow the request with filters, a smaller page_size or a shorter time range, or raise the limit.`
9812
+ }
9813
+ ],
9814
+ isError: true
9815
+ });
9816
+ }
9574
9817
  function wrapToolCallback(toolName, callback) {
9575
9818
  return async (...args) => {
9576
9819
  try {
9577
- return normalizeToolResult(await callback(...args));
9820
+ return enforceToolResultLimit(
9821
+ toolName,
9822
+ normalizeToolResult(await callback(...args))
9823
+ );
9578
9824
  } catch (error) {
9579
9825
  const message = getToolErrorMessage(error);
9580
9826
  const isValidationError = error instanceof z29.ZodError;
@@ -9583,23 +9829,64 @@ function wrapToolCallback(toolName, callback) {
9583
9829
  error: message,
9584
9830
  metadata: { toolName }
9585
9831
  });
9586
- return normalizeToolResult({
9587
- content: [{ type: "text", text }],
9588
- isError: true
9589
- });
9832
+ return enforceToolResultLimit(
9833
+ toolName,
9834
+ normalizeToolResult({
9835
+ content: [{ type: "text", text }],
9836
+ isError: true
9837
+ })
9838
+ );
9590
9839
  }
9591
9840
  };
9592
9841
  }
9593
9842
  var registrationSchemas = /* @__PURE__ */ new WeakMap();
9843
+ var outputSchemasByTool = /* @__PURE__ */ new Map();
9844
+ var jsonSchemaConversions = 0;
9845
+ function memoizeJsonSchemaConversion(schema) {
9846
+ const standard = schema["~standard"];
9847
+ const converters = standard?.jsonSchema;
9848
+ if (!standard || !converters) return schema;
9849
+ const memoize = (direction) => {
9850
+ const convert = converters[direction];
9851
+ if (!convert) return void 0;
9852
+ const results = /* @__PURE__ */ new Map();
9853
+ return (options) => {
9854
+ const key = JSON.stringify(options ?? null);
9855
+ let result = results.get(key);
9856
+ if (!result) {
9857
+ jsonSchemaConversions += 1;
9858
+ result = convert(options);
9859
+ results.set(key, result);
9860
+ }
9861
+ return result;
9862
+ };
9863
+ };
9864
+ return Object.create(schema, {
9865
+ "~standard": {
9866
+ value: {
9867
+ ...standard,
9868
+ jsonSchema: { input: memoize("input"), output: memoize("output") }
9869
+ }
9870
+ }
9871
+ });
9872
+ }
9594
9873
  function normalizeRegistrationSchema(schema) {
9595
- if (!isRecord(schema) || "~standard" in schema) return schema;
9596
- let normalized = registrationSchemas.get(schema);
9597
- if (!normalized) {
9598
- normalized = z29.object(schema);
9599
- registrationSchemas.set(schema, normalized);
9600
- }
9874
+ if (!isRecord(schema)) return schema;
9875
+ if (registrationSchemas.has(schema)) return registrationSchemas.get(schema);
9876
+ const normalized = memoizeJsonSchemaConversion(
9877
+ "~standard" in schema ? schema : z29.object(schema)
9878
+ );
9879
+ registrationSchemas.set(schema, normalized);
9601
9880
  return normalized;
9602
9881
  }
9882
+ function getRegistrationOutputSchema(toolName) {
9883
+ let schema = outputSchemasByTool.get(toolName);
9884
+ if (!schema) {
9885
+ schema = getToolOutputSchema(toolName);
9886
+ outputSchemasByTool.set(toolName, schema);
9887
+ }
9888
+ return schema;
9889
+ }
9603
9890
  function createSafeToolServer(server) {
9604
9891
  const originalRegisterTool = server.registerTool.bind(server);
9605
9892
  const safeServer = Object.create(server);
@@ -9615,7 +9902,7 @@ function createSafeToolServer(server) {
9615
9902
  ...description === void 0 ? {} : { description },
9616
9903
  inputSchema: normalizeRegistrationSchema(config.inputSchema),
9617
9904
  outputSchema: normalizeRegistrationSchema(
9618
- config.outputSchema ?? getToolOutputSchema(name)
9905
+ config.outputSchema ?? getRegistrationOutputSchema(name)
9619
9906
  ),
9620
9907
  annotations: {
9621
9908
  ...inferToolAnnotations(name),
@@ -9819,6 +10106,7 @@ function createMcpServer(options = {}) {
9819
10106
  // src/index.ts
9820
10107
  function main() {
9821
10108
  try {
10109
+ assertByteLimitsConfigured();
9822
10110
  if (!process.env.PORTKEY_API_KEY) {
9823
10111
  Logger.warn(
9824
10112
  "PORTKEY_API_KEY is not set; tool calls will fail until it is configured."